How to use SharedPreferences in Android to store, fetch and edit values

Viewed 726966

I want to store a time value and need to retrieve and edit it. How can I use SharedPreferences to do this?

31 Answers

To store values in shared preferences:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Name","Jayesh");
editor.commit();

To retrieve values from shared preferences:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String name = sp.getString("Name", "");
SharedPreferences.Editor editor = getSharedPreferences("identifier", 
MODE_PRIVATE).edit();
//identifier is the unique to fetch data from your SharedPreference.


editor.putInt("keyword", 0); 
// saved value place with 0.
//use this "keyword" to fetch saved value again.
editor.commit();//important line without this line your value is not stored in preference   

// fetch the stored data using ....

SharedPreferences prefs = getSharedPreferences("identifier", MODE_PRIVATE); 
// here both identifier will same

int fetchvalue = prefs.getInt("keyword", 0);
// here keyword will same as used above.
// 0 is default value when you nothing save in preference that time fetch value is 0.

you need to use SharedPreferences in AdapterClass or any other. that time just use this declaration and use same ass above.

SharedPreferences.Editor editor = context.getSharedPreferences("idetifier", 
Context.MODE_PRIVATE).edit();
SharedPreferences prefs = context.getSharedPreferences("identifier", Context.MODE_PRIVATE);

//here context is your application context

for string or boolean value

editor.putString("stringkeyword", "your string"); 
editor.putBoolean("booleankeyword","your boolean value");
editor.commit();

fetch data same as above

String fetchvalue = prefs.getString("keyword", "");
Boolean fetchvalue = prefs.getBoolean("keyword", "");

2.for Storing in shared prefrence

SharedPreferences.Editor editor = 
getSharedPreferences("DeviceToken",MODE_PRIVATE).edit();
                    editor.putString("DeviceTokenkey","ABABABABABABABB12345");
editor.apply();

2.for retrieving the same use

    SharedPreferences prefs = getSharedPreferences("DeviceToken", 
 MODE_PRIVATE);
  String deviceToken = prefs.getString("DeviceTokenkey", null);
Related