Android - How do i get sharedpreferences from another activity?

erdomester picture erdomester · May 31, 2011 · Viewed 85.3k times · Source

In my app there is a button (activity1). When user clicks it i want no sound in the game. I thought i should do this by using sharedpreferences in activity1 in the onClick method of the button:

SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("sound","1");
editor.commit();

The sound and the game starts in another activity (activity2). I need to read the set sharedpreferences there but i don't know how to do it.

Thanks

Edit

I have left this line out:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Activity1.this);

Based on your help in the Activity2.class I read the preferences like this:

SharedPreferences myPrefs = getSharedPreferences("Activity1", MODE_PRIVATE);  //Activity1.class
String ifsound = myPrefs.getString("sound","");

 if (ifsound.equals("1"))
 {
     Toast.makeText(Activity1.this, "1", Toast.LENGTH_LONG).show();
 }
 else
 {
      Toast.makeText(Activity1.this, "0", Toast.LENGTH_LONG).show();
 }
  1. In Activity1.class i click on the button to set the "sound" to "1".
  2. I click on another btn that opens Activity2.class where i always get always "0" in the Toast msg.

Answer

includeMe picture includeMe · May 31, 2011

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.commit();
}

public static String getDefaults(String key, Context context) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    return preferences.getString(key, null);
}