markharrop markharrop -3 years ago 114
Java Question

Shared pref not working

I have a shared pref that I want to save a string from an editText on my first Activity. then in my second activity to call and use this string. so in my main activity, I have this line of code to save the string

SharedPreferences.Editor prefEditor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit();

Then in my second Activity, I have this code to call it

SharedPreferences prefs = this.getSharedPreferences(
"h20music.p9p.harrop99.h20music", Context.MODE_PRIVATE);
myStrValue = prefs.getString("SEARCHSAVE", "defaultStringIfNothingFound");

But if I check to see if the string is saved it returns the "defaultStringIfNothingFound"

What am I doing wrong guys, please? thanks in advance. this is the first time I've worked with saving strings.


The duplication question answer given does not explain what ive done wrong at all?

Answer Source

You aren't using the same shared preferences.

Either use getDefaultSharedPreferences(getContext()) in both places, or use your own version with getSharedPreferences("h20music.p9p.harrop99.h20music") in both places

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download