[SOLVED] Storing two sharedPreferences but not updating one of them


This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under
CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

Issue

I’m storing each user shared preferences based on what they do with the app, the users can have multiple Gmail accounts and I’m trying to manage sharedpreferences for each account.

I managed to do a copy of my defaultsharedpreferences into each of my users email preference, the thing is that the users preferences never change when I do something with the app, but the default preferences does.

Here is my code:

sharedPrefsDefault = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        sharedPrefs = getSharedPreferences(sharedPrefsDefault.getString(getString(R.string.str_userMail),"error"), Context.MODE_PRIVATE);
        PreferenceManager.setDefaultValues(getApplicationContext(),(sharedPrefsDefault.getString(getString(R.string.str_userMail),"error")), Context.MODE_PRIVATE, R.xml.preferences, false);

This is what I’m doing in onCreate to store the defaultPrefs into my sharedPrefs (user).

Solution

I’m not a hundred percent sure on what you’re planning to achieve but create a SharedPreferences class of your own. Something like this.

public class UserPreferences{

SharedPreferences.Editor editor;
SharedPreferences sharedPreferences;


 public UserPrefs(String userName, Context context) {
    this.context = context;
    sharedPreferences = context.getSharedPreferences(userName, 0);
    editor = sharedPreferences.edit();
 }
 public String getUserMail(){
   return sharedPreferences.getString("userMail","abc@def.gh");
 }
 public String setUserMail(String s){
   editor.putString("userMail",s);
   editor.apply();
 }
}

Answered By – birukhimself

people found this article helpful. What about you?