Thursday, April 11, 2013

SharedPreferences In Android

In Android there are 3 ways to store/save the data.

1:  Using Database (Creating table)      See Here How to create Database
2: Using Files
3: Using  SharedPreferences

SharedPreferences


SharedPreferences  Store private primitive data in key-value pairs.
The SharedPreferences class provides a way  that allows you to save and retrieve persistent key-value pairs of primitive data types. 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).


How To Use SharedPreferences:


Get the SharedPreference


SharedPreferences  shfObject = getSharedPreferences("NAME", Context.MODE_PRIVATE); 

Writting Data to SharedPreferences:


We can write boolean, char, String, Int, long or  any type of Data to SharedPreferences and get back the value.

As already discussed that SharedPreferences store data in key value pair.


To write data  to SharedPreference we need  to use  SharedPreferences.Editor    class.

 SharedPreferences.Editor  shfEditorObject=shfObject.edit();

The general format is  to store data in     SharedPreference

shfEditorObject .putDataType("KEYNAME", "VALUE"); 

and do not forget to commit the changes made in SharedPrefenrence by using commit method.

shfEditorObject.commit();
To write a boolean:

shfEditorObject.putBoolean(key, value)
 shfEditorObject.commit();


To write an Int:

shfEditorObject.putInt(key, value)
 shfEditorObject.commit();

To write a String:

shfEditorObject.putString(key, value);
 shfEditorObject.commit();

To write a long:

shfEditorObject.putLong(key, value);
 shfEditorObject.commit();

To write a float:

shfEditorObject.putFloat(key, value);
 shfEditorObject.commit();

Fetch/Retrieve data from  SharedPreferences:


get the   SharedPreferences   with exact same SharedPreferences "NAME"  supplied to store the value

SharedPreferences  shfObject = getSharedPreferences("NAME", Context.MODE_PRIVATE); 

Stored data is fetch using SharedPreference Object, here we will use shfObject to get the data Stored in SharedPreference

the general format is :

shfObject.getDataType("KEY", defaultedValue);

Please note that the above method return the defaultedValue  if "KEY" does not exist.


To get a boolean value

shfObject.getBoolean(key, defaultValue)



To get an Int value

shfObject.getInt(key, defaultValue)

To get a Long value

shfObject.getLong(key, defaultValue)

To get a String value

shfObject.getString(key, defaultValue)

To get a Float value

shfObject.getFloat(key, defaultValue)



SharedPreferences can be used in the  all the Activities, Broadcast Receivers  within an Application.








4 comments: