0

I'm new to android programming and I was wondering if it's possible to add more than one value in shared preferences at the same time. I have tried the following, but when I try to get the values I can see only the first one. The other value is getting the default value. Can you help me, please?

My code:

    SharedPreferences.Editor editor = getSharedPreferences("prefs", Context.MODE_PRIVATE).edit();
    String string1 = "myString1";
    String string2 = "myString2";
    editor.putString(string1, string2).apply();


    SharedPreferences preferences = getSharedPreferences("prefs", Context.MODE_PRIVATE);
    String string1FromSP = preferences.getString(string1, "default");
    String string2FromSP = preferences.getString(string2, "default");

    Log.e("Value 1", string1FromSP);
    Log.e("Value 2", string2FromSP);
zidniryi
  • 1,212
  • 3
  • 15
  • 36
  • Hi, welcome to SO Community. The above code has a bug, is that Shared SharedPreferences save Key-Value Pair. In ```putString(Key, Value)``` you are passing the ```string1``` as key for saving ```string2``` – Muhammad Farhan Feb 08 '21 at 10:22

1 Answers1

0

Values in Android SharedPreference gets stored like Key Value pair. And You are trying to store it all together like list or varargs.

So to save the values in Your example

SharedPreferences.Editor editor = getSharedPreferences("prefs", Context.MODE_PRIVATE).edit();
String string1 = "myString1";
String string2 = "myString2";
editor.putString("STRING_1", string1).apply();
editor.putString("STRING_2", string2).apply();


SharedPreferences preferences = getSharedPreferences("prefs", Context.MODE_PRIVATE);
String string1FromSP = preferences.getString("STRING_1", "default");
String string2FromSP = preferences.getString("STRING_2", "default");

Log.e("Value 1", string1FromSP);
Log.e("Value 2", string2FromSP);
Bhargav Thanki
  • 4,924
  • 2
  • 37
  • 43