Thursday 19 March 2015

SharedPreferences in Android to store, fetch and edit values .

You can store,fetch and edit data for specific app in Shared Preferences in following way  :-

Way 1)

Initialize sharedPrefrences object: 
//declare it in onCreate() 
SharedPreferences preferences = this.getSharedPreferences(
      "com.example.android", Context.MODE_PRIVATE);
 
To edit and save preferences(same it used to store new values):
SharedPreferences.Editor editor =preferences.edit();   
editor.putString("Key","Value"); 
editor.commit();
 
To read preferences:
String name = preferences.getString("Key","");

 
 
Way 2)

Initialize sharedPrefrences object:  
 //declare it in onCreate()
SharedPreferences preferences = PreferenceManager. 
                                 getDefaultSharedPreferences(this);
 
To edit and save preferences(same it used to store new values):
 SharedPreferences.Editor editor = preferences.edit();
 editor.putString("key","value");
 editor.commit();
 
To read preferences:
String name = preferences.getString("Key","");

No comments:

Post a Comment