opc0de
opc0de

Reputation: 11767

Storing and retrieving shared preferences in android

I am trying to store some settings using preferences I am using this code:

    SharedPreferences pref = getPreferences(MODE_WORLD_WRITEABLE);
                        pref.edit().putString("some settings", "lalal");
                        pref.edit().commit();

What i am doing wrong the file gets created but is empty

Upvotes: 0

Views: 236

Answers (2)

lenik
lenik

Reputation: 23498

You've got 2 different editors for your prefs, first one adds the string, and second one commits empty changes, because you've changed another editor.

Change this:

   pref.edit().putString("some settings", "lalal");
   pref.edit().commit();

into this:

   pref.edit().putString("some settings", "lalal").commit();

Upvotes: 1

Krishna Suthar
Krishna Suthar

Reputation: 3075

Try this code:

SharedPreferences customSharedPreference = getSharedPreferences("myCustomSharedPrefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = customSharedPreference.edit();
editor.putString("some settings", "lalal");
editor.commit();

and get values using this code:

SharedPreferences shf = getSharedPreferences("myCustomSharedPrefs", MODE_WORLD_READABLE);
String strShPref = shf.getString("some settings", "");

Upvotes: 2

Related Questions