Socratease Socratease - 10 months ago 40
Android Question

Cannot retrieve saved SharedPreferences in another activity

So we're working on this Android app. We've got a login activity that receives some information when the user logs in successfully. We've got a class called SessionManager that handles saving said data to SharedPreferences.

SessionManager always retrieves SharedPreferences from the same file always. It's hardcoded in there.

public SessionManager(Context context) {
this.preferences = context.getSharedPreferences(PREFERENCE_NAME, 0);
this.editor = this.preferences.edit();
this.jsonParser = new Gson();

The jsonParser is there so we can save the info as a json object.

public final void storeProfile(UserProfile profile) {
this.editor.putString(STORAGE_KEY, this.jsonParser.toJson(profile));

private static final String STORAGE_KEY = "PROFILE";

private String getStoredValue() {
return this.preferences.getString(STORAGE_KEY, null);

public UserProfile getStoredProfile() {
String val = getStoredValue();
return (val == null) ? null : this.jsonParser.fromJson(val, UserProfile.class);

In theory, this should mean we should be able to store the profile in one activity, then get it back in another activity, right?

Except that's not happening! It looks like I can only retrieve saved information in the same activity where it was saved!

I call storeProfile() in the login activity, then getStoredProfile() in another activity, and it returns null.

I call storeProfile() in the login activity, then getStoredProfile() in the login activity, and it returns the stored profile. It also works if two different SessionManager instances call storeProfile() and getStoredProfile().

I set the stored profile manually in the other activity, and it retrieves the manually stored profile just fine.

Is there some scope rule or something to SharedPreferences that I'm missing?

Answer Source

Turns out I'm a fool and I was accidentally wiping my preferences every time I tried to get them.