Use of Shared Preferences in Android

For Data Storage Android provides number of ways. Shared Preferences is one of them. We can save primitive data in key-value pairs and reuse it across multiple Activities.
The SharedPreferences class provides a general framework that allows to save and retrieve persistent key-value pairs of primitive data types. This data exists even the Application is killed.
Steps:
1) To get the Object of SharedPreferences use :
  SharedPreferences sharedPrefs = this.getSharedPreferences("newPrefs",MODE_WORLD_READABLE); 
In getSharedPreferences() just put the file name and the mode.
2)To write some data use :
        SharedPreferences.Editor prefsEditor = sharedPrefs.edit();
3)Simple put the data :
        prefsEditor.putString(MY_NAME, "Subrat Mohanty");
        prefsEditor.putString(MY_ID, "E3141");
        prefsEditor.putBoolean(MY_STATUS, true);
4)Commit the data:
        prefsEditor.commit();

There is a xml file created having same name(newPrefs) created in "file Explore" of the package name. This file remains upto the Application exists. When the application is unintalled or "Clear data" is done the xml file got deleted.
 Just pull the file and open it in any editor (Notepad++) and you can see the values.
Again to use the same data in various Activities:
Steps:
1)Create the object of SharedPreferences :   
  SharedPreferences sharPrefs = this.getSharedPreferences("newPrefs",MODE_WORLD_READABLE);   
2) Get the values by using getString() , getBoolean() methods. Put the parameters as Key and default values
        String prefName = sharPrefs.getString(MY_NAME, "not available");
        String preId = sharPrefs.getString(MY_ID, "not available");
         boolean status = sharedPrefs.getBoolean("my status", true);

You can use these values in number of activities by doing the above.

Happy coding... :)

Comments

  1. This is one of the well organized post.I like your blog clarity.Thanks for share with us.
    Android app developers

    ReplyDelete

Post a Comment

Popular posts from this blog

Wireless Android Auto for Non-Google phones

Extracting Java class from .apk files in Android