Wednesday, February 20, 2019

Java Saving and Retrieving Preferences

We want to save data and retry after.
First, save data, use this lines.
final String MYPREFS = "mySave";
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences = getSharedPreferences(MYPREFS,mode);
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putBoolean("isTrue", true);
editor.putFloat("lastFloat", 1f);
editor.putInt("Number", 2);
editor.putString("textEntryValue", "My String");
editor.commit();
To get data saved, use this lines, key value must be the same with key value saved.
final String MYPREFS = "mySave";
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences = getSharedPreferences(MYPREFS,mode);
boolean isTrue = mySharedPreferences.getBoolean("isTrue",false);
float mfloat = mySharedPreferences.getFloat("lastFloat", 0f);
int number = mySharedPreferences.getInt("Number", 1);

String stringPreference = mySharedPreferences.getString("textEntryValue","");

Or we can do shortly.
final SharedPreferences.Editor edit = prefs.edit();
 edit.putInt("vi"100);
 edit.commit();  
To get data.
SharedPreferences prefs;
prefs=PreferenceManager.getDefaultSharedPreferences(this);
int so = prefs.getInt("vi", 0);

No comments:

Post a Comment