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.
The problem with storing data in global variable is data will be lost
once user closes the application, but storing the data in shared
preferences will be persistent even though user closes the application.
Application shared preferences allows you to save and retrieve key,
value pair data. Before getting into tutorial, I am giving basic
information needed to work with shared preferences.
Initialization
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 );
Editor editor = pref.edit();
|
Storing Data
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 );
editor.putString( "key_name" , "string value" );
editor.putInt( "key_name" , "int value" );
editor.putFloat( "key_name" , "float value" );
editor.putLong( "key_name" , "long value" );
editor.commit();
|
Retrieving Data
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.
pref.getString( "key_name" , null );
pref.getInt( "key_name" , null );
pref.getFloat( "key_name" , null );
pref.getLong( "key_name" , null );
pref.getBoolean( "key_name" , null );
|
Clearing / Deleting Data
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" );
editor.remove( "email" );
editor.commit();
|
Following will clear all the data from shared preferences
editor.clear();
editor.commit();
|
The following is a simple tutorial which will have a login
form and a dashboard screen. At first user will login using login
details and once he successfully logged in his credentials (name, email)
will be stored in shared preferences.
Download code from this Link:
Session Management
No comments:
Post a Comment