Android - How do I get sharedpreferences from another activity?
In Activity1 while saving preferences use:
SharedPreferences mPrefs = getSharedPreferences("IDvalue", 0);
//Give any name for //preference as I have given "IDvalue" and value 0.
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString(key, value);
// give key value as "sound" you mentioned and value what you // to want give as "1" in you mentioned
editor.commit();
In Activity2 while retrieving shared values use :
SharedPreferences mPrefs = getSharedPreferences("IDvalue",0);
String str = mPrefs.getString("sound", "");
if (str.equals("1")) {
// Do what you want
} else {
// Do what you want
}
Use the following functions to add shared preferences and to fetch the saved values from all activities.
public static void setDefaults(String key, String value, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(key, value);
editor.apply(); // or editor.commit() in case you want to write data instantly
}
public static String getDefaults(String key, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, null);
}