Skip to content Skip to sidebar Skip to footer

Sharedpreferences Between Activities

This question is kind of similar to other sharedpreferences questions but i don't really know how exactly to use it between different activities? Kindly provide the complete activi

Solution 1:

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 !

Solution 2:

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:

SharedPreferencesprefs= PreferenceManager.getDefaultSharedPreferences(this);

Solution 3:

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";

@OverrideprotectedvoidonCreate(Bundle state){
   super.onCreate(state);
   . . .

   // Restore preferencesSharedPreferencessettings= getSharedPreferences(PREFS_NAME, 0);
   booleansilent= settings.getBoolean("silentMode", false);
   setSilent(silent);
}

@OverrideprotectedvoidonStop(){
   super.onStop();

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

  // Commit the edits!
  editor.commit();
}

Post a Comment for "Sharedpreferences Between Activities"