Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SharedPreferences does not work - getString always returns the default value

I have a problem with SharedPreferences in Android.

This is my code:

    SharedPreferences s = this.getSharedPreferences("kurs",MODE_WORLD_READABLE);
    s.edit().putString("eur", "1.80");
    s.edit().commit();
    SharedPreferences a = this.getSharedPreferences("kurs",MODE_WORLD_READABLE);
    String kurs = a.getString("eur","7");

    Toast hhh= Toast.makeText(getApplicationContext(),kurs, Toast.LENGTH_LONG);
    hhh.show();

I´m setting the String and want to read it out directly after that in the onCreate method. But i always get the specified default value "7".

What was wrong? I already researched for that problem, but i can´t found helpful things.

Thanks for your help :)

like image 263
Maximii77 Avatar asked Oct 21 '13 12:10

Maximii77


2 Answers

Each time you call "s.edit()" a new editor is created. Thus your "commit()" call is on an instance of the editor that has not had your setting applied. Try this:

SharedPreferences s = this.getSharedPreferences("kurs",MODE_WORLD_READABLE);
Editor editor = s.edit();
editor.putString("eur", "1.80");
editor.commit();
like image 90
EJK Avatar answered Sep 18 '22 00:09

EJK


Please try my code below. What i think is wrong in your code, that you are using different "Editor" instances here:

"s.edit().putString("eur", "1.80");"

and here

s.edit().commit();

private static String APP_SHARED_PREFS = "MyAppID";
// Write the value
SharedPreferences.Editor prefsEditor = getSharedPreferences(APP_SHARED_PREFS, Activity.MODE_PRIVATE).edit();
prefsEditor.putString("KEY", "VALUE");
prefsEditor.commit();
// Get the value
return getSharedPreferences(APP_SHARED_PREFS, Activity.MODE_PRIVATE).getString("KEY", "");
like image 32
alex Avatar answered Sep 20 '22 00:09

alex