friday
friday

Reputation: 1488

Restore string from shared preferences

I'm currently trying to store and restore a string from the shared preferences but something seems to go wrong.

I want to persistent store a cookie so I try to store the value of it in the shared preferences. Unfortunately it can't be found when I try to retrieve it.

Heres my code:

public void storeString(Activity ctx, String key, String value){
    SharedPreferences prefs = ctx.getSharedPreferences("com.test", Context.MODE_PRIVATE);
    prefs.edit().putString("CAKEPHP", value);
    prefs.edit().commit();

    SharedPreferences newprefs = ctx.getSharedPreferences("com.test", Context.MODE_PRIVATE);
    Log.i("test", "cookie retrieved: "+ newprefs.getString("CAKEPHP", "nodata"));
}

The log output is "cookie retrieved: nodata". Can someone please show me how to get this right?

It might be important that this method is part of a plain java class. When called, the calling activity is passed as a parameter.

Any help or hint is appreciated!

Upvotes: 1

Views: 831

Answers (1)

PravinCG
PravinCG

Reputation: 7708

Create a static variable for sharedpref and initialize it as

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);

You do not need to initialize sharedpreferences repeatedly. Ideally you should initialize it in onCreate and use it throughout the activity.

Additionally you need to call

prefs.edit().putString("CAKEPHP", value).commit();

Upvotes: 1

Related Questions