Storing and Retrieving Data Using Shared Preferences | in this tutorial, we will learn how to store and retrieve data using Shared Preferences in android.
The primary purpose of using Shared Preferences in android is to store user specific details, such as user specific settings (eg: – username), when a user logged into the application. We can display the username of a person in each page or in each activity using Shared Preferences.
Shared Preferences help us to modify preferences that we want to store on our phone. Shared Preferences is used to stores private data in key-value pairs.
In Shared Preferences save data to shared preference by calling the getSharedPreferences() method.
The SharedPreferences Editor is used to apply the changes which we have made while storing the data. The data is saved using commit() method.
SharedPreferences is application specific, which means the data is lost on performing one of the following options:
- Up on uninstalling the application
- Up on clearing the application data
You can create a new shared preference file or you can accessing existing shared preference file by calling one of the following methods:
- getSharedPreferences() — Use this if you need multiple shared preference files identified by name, which you specify with the first parameter.
SharedPreferences sp; sp=getSharedPreferences("SD", Context.MODE_PRIVATE);
- getPreferences() — Use this if you need to use only one shared preference file for the activity. The file that belongs to the activity, you don’t need to supply a name as above.
SharedPreferences sharedPref; sharedPref=getActivity().getPreferences(Context.MODE_PRIVATE);
There are three types of Mode in Shared Preference:
1. Context.MODE_PRIVATE – default value -Not accessible outside of your application.
2. Context.MODE_WORLD_READABLE – readable to other applications.
3. Context.MODE_WORLD_WRITEABLE – read/write to other applications.
Setting values in Preference:
SharedPreferences sp; sp=getSharedPreferences("SD", Context.MODE_PRIVATE); SharedPreferences.Editor ed=sp.edit(); ed.putString("un",ed1.getText().toString()); ed.putString("up",ed2.getText().toString()); ed.commit();
Retrieve data from preference:
SharedPreferences sp; sp=getSharedPreferences("SD",Context.MODE_PRIVATE); String Uname=sp.getString("un","").toString(); //Value retrieved using the key and stored in a string String Password=sp.getString("up","").toString(); //Value retrieved using the key and stored in a string
Deleting Key value from SharedPreferences
We need an editor class to edit and save the changes in shared preferences.
editor.commit() is used save changes in shared preferences.
Data can be retrieved from saved preferences by calling getString() method.
Clearing or Deleting Data
remove(“key_name”) is used to delete that particular value of a key.
clear() is used to remove all data.