below is my code for creating shared pref
public SaveData(Context con) {
this.context = con;
emailSharedPreferences = context.getSharedPreferences(KEY_PREF_EMAIL, Context.MODE_PRIVATE);
emailEdit = emailSharedPreferences.edit();
}
for set data
public void setData(boolean accepted) {
emailEdit = emailSharedPreferences.edit();
emailEdit.putBoolean(KEY, accepted);
emailEdit.apply();
}
for get data
public Boolean getData() {
emailSharedPreferences = context.getSharedPreferences(KEY_PREF_EMAIL, Context.MODE_PRIVATE);
return emailSharedPreferences.getBoolean(KEY, false);
}
At my application launcher screen when i am trying to get data it is returning "true" in some devices.
Now if I have created shared pref by below code
private static SharedPreferences getPreferences(Context context) {
// return context.getSharedPreferences(PREF_NAME, MODE);
return PreferenceManager.getDefaultSharedPreferences(context);
}
private static SharedPreferences.Editor getEditor(Context context) {
return getPreferences(context).edit();
}
For set data
public static void setData(Context context,boolean value){
try {
getEditor(context).putBoolean(KEY, value).commit();
} catch (Exception e) {
e.printStackTrace();
}
}
for get data
public static boolean getData(Context context){
try {
return getPreferences(context).getBoolean(KEY, false);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
now it is working fine on all devices. Can someone explain this why this is happening.
Use this
emailEdit.commit();
after this
emailEdit.putBoolean(KEY, accepted);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.