Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

Android - How do I get sharedpreferences from another activity?

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.
question from:https://stackoverflow.com/questions/6186123/android-how-do-i-get-sharedpreferences-from-another-activity

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...