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!
Create a static variable for sharedpref and initialize it as
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