Android SharedPreferences provides an easy and efficient way to store data in the form of Key value pairs in Android. Unlike other storage options whose setup is a bit complex, SharedPreferences provides an easy way to read and write data into a file.
What are SharedPreferences?
SharedPreferences are just key value pairs which are stored in an xml file. If we know the key, we can access the value.
What kind of data can I store using Android SharedPreferences?
We can store all primitive data types like int, float, long, boolean, String in SharedPreferences. For data that is complex and bulkier than this, it is better to use sqlite, which we’ll also discuss in my future tutorials.
Accessing Android SharedPreferences
Accessing Android SharedPreferences can be done by using the following code:
//Accessing android sharedpreferences Context context = getActivity(); SharedPreferences sharedPref = context.getSharedPreferences("MY_KEY", Context.MODE_PRIVATE);
We can observe that from the above lines of code, getSharedPreferences() method from context takes in two parameters:
Key – It is the one which is used to save the datatype in SharedPreferences
Mode – Which sets whether the data should be visible to other apps. MODE_PRIVATE is the default mode.
Different Types of Modes Available:
File creation mode: for use with openFileOutput(String, int), if the file already exists then write data to the end of the existing file instead of erasing it.
Database open flag: when set, the database is opened with write-ahead logging enabled by default.
File creation mode: the default mode, where the created file can only be accessed by the calling application (or all applications sharing the same user ID).
Database open flag: when set, the database is opened without support for localized collators.
Writing data to Android SharedPreferences
To write data to Android sharedPreferences we need to create SharedPreferences.Editor by calling edit() method from SharedPreferences as follows:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putInt("MY_KEY", "Vamsi Tallapudi"); editor.commit();
Reading data from Android SharedPreferences
//reading data from android sharedPreferences SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); String myName = sharedPref.getString("MY_KEY", "my default value");
So where is my data stored?
The data for the respective app will be stored in the following directory:
Here is the video so that it would be easier to understand Android SharedPreferences with an example.
The sourcecode for the example created in the above Youtube Video on Android SharedPreferences is in the below link pointing to github.
This completes our tutorial on SharedPreferences. We’ll discuss about various other storage options available in Android in upcoming articles.