0

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();
                prefEditor.putString("SEARCHSAVE",search);
                prefEditor.apply();

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.

******Edit

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

markharrop
  • 866
  • 1
  • 9
  • 30
  • This [answer](https://stackoverflow.com/a/6310080/5015207) to the linked "original" of your question explains how `getDefaultSharedPreferences()` is implemented. One can see that they use a special key (built fom the package name and "_preferences").So the answer implies that the key matters. You "did wrong" by using different keys. IMO your problem can be solved by applying the answer to the other question. That's why - for me - your question is a "duplicate". – Bö macht Blau Aug 16 '17 at 19:51
  • But if this "original" will not do - how about [that one](https://stackoverflow.com/questions/34320668/shared-preferences-not-working-for-storing-receiving-data)? – Bö macht Blau Aug 16 '17 at 19:51

1 Answers1

2

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

Dodd10x
  • 3,344
  • 1
  • 18
  • 27