-1

So I'm just trying to save a string.. But everytime I rerun the app, I get null for the saved String :/ I'm 100% sure I'm calling the save method, and that the string it not null when I'm saving it.

public class CFUser {

private final static String ID_KEY="myUserID";
private static String userID;

public static String getUserID(Context context) {
    if(userID==null) {
        SharedPreferences prefs= context.getApplicationContext().getSharedPreferences(ID_KEY, 0);
        userID=prefs.getString(ID_KEY, null);
        }

    return userID;
}
public static void setUserID(String id, Context context) {
    userID=id;
    Log.d("saving", id);
    SharedPreferences prefs=context.getApplicationContext().getSharedPreferences(ID_KEY, 0);
    prefs.edit().putString(ID_KEY, userID);
    prefs.edit().apply();
}
public static boolean isLoggedIn(Context context) {
    return getUserID(context)!=null;
}

}

many thanks!

Leo Starić
  • 331
  • 1
  • 4
  • 16

2 Answers2

2

In this code, you are creating two different SharedPreferences.Editor Objects:

SharedPreferences prefs=context.getApplicationContext().getSharedPreferences(ID_KEY, 0);
prefs.edit().putString(ID_KEY, userID);
prefs.edit().apply();

So that means you are putting the String in Editor1, but are committing the (non-existant) changes of Editor2.
You need to do it this way:

SharedPreferences prefs=context.getApplicationContext().getSharedPreferences(ID_KEY, 0);
SharedPreferenced.Editor edit = prefs.edit();
edit.putString(ID_KEY, userID);
edit.apply();
Tobias Baumeister
  • 2,107
  • 3
  • 21
  • 36
0

At the moment the name of your entire SharedPreferences file is myUserID because of how you're retrieving the SharedPreferences. Instead use the following. This isn't causing the issue but I'm assuming you don't want the SharedPreferences file as your ID key...

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);

Then when you're writing to the preferences make sure you're using the same Editor.

Editor editor = preferences.edit();
editor.putString(ID_KEY,userID);
editor.apply();
StuStirling
  • 15,601
  • 23
  • 93
  • 150