This is in continuation to Part 1
In this post, we shall be working on already created Default Shared Preferences File.
We can create SharedPreferences at 2 levels. one is Application level, another is Activity level.
In previous post, we have seen values being saved to SharedPreferences file automatically by the Preference Objects.
In order to read the values or write to the file programatically, we need to get the handle of the SharedPreferences file.
To get the handle of SharedPreferences File:
SharedPreferences sharedpref =
This gets a SharedPreferences instance that points to the default file.
= getSharedPreferences("PrefFileName", Context.MODE_PRIVATE);
This gets a SPECIFIC SharedPreferences instance by NAME.
This gets the handle for the Activity level SharedPreferences File. File name will be same as the Activity Class name.
Having Context.MODE_PRIVATE specify will make sure the file is accessable only by the application.
Once you have the SharedPreferences object, Reading the values is direct. Based on the datatype, use the appropriate methods like getBoolean(), getString(), getFloat(), getInt(), etc.
Read all the methods here
If the key doesn’t exist, the default value (2nd argument) will be returned by getBoolean().
If the user changes the preference setting, in-order to get notified about the new value during run time, Listener has to be set.
In the example above, if the String value stored in the file is a combination of numberic, if the user enteres “1Z” by mistake, you will see undesired results based on how you use this value. To inform the user about this wrong input dynamically, Listener has to be set.
These are call back functions when there are any changes to file or changes to input fields.
There are 2 SharedPreferences Listeners:
is triggered, AFTER any value is changed in the SharedPreferences File.
is triggered, BEFORE any value is saved to the SharedPreferences File.
If this post helped or have queries please leave ur comments and share.