iiFreeman
iiFreeman

Reputation: 5175

SharedPreferences getString always returns default value

Here is my code:

public void saveValue(String value, String forKey) {
    SharedPreferences.Editor editor = getSharedPreferences().edit();
    editor.putString(value, forKey);
    editor.commit();
    SharedPreferences p = getSharedPreferences();
    System.out.println("JUST SET TO SharedPreferences" + p.getString(forKey, ""));
}

in Logcat:

JUST SET TO SharedPreferences  

But when app stops on the breakpoint I see that values are actually stored in

debugger output

I'm running app on the emulator.

How do I read that values? Thanks!

Upvotes: 0

Views: 1317

Answers (2)

Rod_Algonquin
Rod_Algonquin

Reputation: 26198

The problem is that you are using the forKey as the key which was originally added as a value in the SharedPreferences and not as key here:

editor.putString(value, forKey);

as you can see above the value is the key and the forKey is the value

so therefore when you are getting the value from the SharedPreferences you should use the key to get the value:

p.getString(value, "") //dont use forKey as the value

or you should switch one another

editor.putString(forKey, value);

so the forkey will work

Upvotes: 2

AndroidEx
AndroidEx

Reputation: 15824

I think you switched the key and value here editor.putString(value, forKey);.

The signature is putString (String key, String value).

Upvotes: 1

Related Questions