How to use Shared Preferences and manage User Sessions


Android Storage can be done in many ways and one of the way is shared preferences.Shared Preferences allows us to  manage session.Since Session are useful when you want to store user data globally through out the application. This can be done in two ways. One is storing them in a global variables and second is storing the data in shared preferences.



 Shared Preferences..What it is?

Shared Preferences is an API from Android SDK to store and retrieve application preferences. Shared Preferences are simply sets of data values that stored persistently. Persistently which mean data you stored in the Shared Preferences are still exist even if you stop the application or turn off the device. SharedPreferences available at the Activity level or shared across all Activity in application package.

Shared Preferences are used in android to store some data presistently(i.e. after closing of application, it will persist).If you want to store few amount of data then you can go for Shared Preferences rather than going for Sqlite and all.In that case Shared Preferences are useful.


When to use Shared Preferences ?

1.You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).

2.Think of a situation where you wanna save a small value (a flag probably) that you wanna refer later sometime when user launches the application. Then shared preference comes into action.
You may ask, why we can do it using sqlite too right? But the problem of sqlite is that it’ll want you to write lengthy codes and supporting classes. Shared Preference let you read and write values in couple of lines easily. But always remember, shared preference is not a solution for you to keep complex relational data.

How to Intialize?

Application shared preferences can be fetched using getSharedPreferences() method.You also need an editor to edit and save the changes in shared preferences. The following code can be used to get application shared preferences.

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
How to Store Data In Shared Preference?

You can save data into shared preferences using editor. All the primitive data types like booleans, floats, ints, longs, and strings are supported. Call editor.commit() in order to save changes to shared preferences.

editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing long
editor.commit(); // commit changes

How to retrieve Data From Shared Preferences ?

Data can be retrived from saved preferences by calling getString() (For string) method. Remember this method should be called on Shared Preferences not on Editor.


// returns stored preference value
// If value is not present return second param value - In this case null
pref.getString("key_name", null); // getting String
pref.getInt("key_name", null); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean


And finally how to Clear / Delete Data from shared Preference?


If you want to delete from shared preferences you can call remove(“key_name”) to delete that particular value. If you want to delete all the data, call clear()



editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email
editor.commit(); // commit changes
Following will clear all the data from shared preferences
editor.clear();
editor.commit(); // commit changes

Whats Next?

Yeah,like the article?  Then take a moments to share it and Subscribe our site.  

Hey I'm Venkat
Developer, Blogger, Thinker and Data scientist. nintyzeros [at] gmail.com I love the Data and Problem - An Indian Lives in US .If you have any question do reach me out via below social media

10 comments

NIce Waiting for example Thanks!

Very Nicely Explained Great! When u are Updating with example

Hey, where can I find the "simple sign in form" ?thanks

Here it is Take a look at it
http://androidgreeve.blogspot.in/2014/01/Mange-User-Session-using-Shared-Preference-with-example.html

Very useful. Thank you!

What a bad idea to hardcode this SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
what can happen if you want to use other as private mode (i.e other that 0)?? then you need to look where the "magic number" is located in sourceCode, what happens now if Android decides to change the privateMode Index to 44? then you will get a wonderful exception.
NEVER EVER use magic Numbers, this anti pattern (http://en.wikipedia.org/wiki/Magic_number_(programming)#Unnamed_numerical_constants )can save you a lot of time by finding bugs and testing well developed apps!!
Thanxs anyway for sharing!

Usefull stuff.:)


EmoticonEmoticon