sharedpreferences between activities

我只是一个虾纸丫 提交于 2019-12-01 13:57:18

In your UserProfile class and everywhere else change -

SharedPreferences sharedpreferences = getPreferences(MODE_PRIVATE);

by this -

 sharedpreferences = getSharedPreferences("nameKey", Context.MODE_PRIVATE);

And you are good to go !

You are using sharedpreferences which are local to your two activities, as in docs for this method:

Retrieve a SharedPreferences object for accessing preferences that are private to this activity.

Solution is to use global sharedpreferences with:

 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

A major dilemma is that you are using getPreferences() in UserProfile, but using getSharedPreferences() in EditUserProfile. The first method would only get key-value pairs for the UserProfile activity, while the second is for any part of the app to access. Switch getPreferences() to getSharedPreferences() and you should be good.

http://developer.android.com/guide/topics/data/data-storage.html#pref

From that website: public class Calc extends Activity { public static final String PREFS_NAME = "MyPrefsFile";

@Override
protected void onCreate(Bundle state){
   super.onCreate(state);
   . . .

   // Restore preferences
   SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
   boolean silent = settings.getBoolean("silentMode", false);
   setSilent(silent);
}

@Override
protected void onStop(){
   super.onStop();

  // We need an Editor object to make preference changes.
  // All objects are from android.context.Context
  SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
  SharedPreferences.Editor editor = settings.edit();
  editor.putBoolean("silentMode", mSilentMode);

  // Commit the edits!
  editor.commit();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!