Reputation: 833
I want to save state of my app, when it is paused, in SharedPreferences, and load it when onResume is called:
In my onPause method:
@Override
protected void onPause()
{
super.onPause();
SharedPreferences prefs = getSharedPreferences("MyPrefName", 0);
if(socket!=null && socket.isConnected())
{
releaseOutputSocket();
prefs.edit().putString("started", "started");
}
else
prefs.edit().putString("started", "stoped");
boolean res = prefs.edit().commit(); //res == true
}
In onResume method I do:
@Override
public void onResume()
{
super.onResume();
SharedPreferences prefs = getSharedPreferences("MyPrefName", 0);
Log.v("Main", prefs.getString("started", "default")); // in log I see "default"
}
Can you tell me, what's wrong in my code?
Upvotes: 0
Views: 67
Reputation: 2822
You need to call commit on the reference you use to put the String. When you call prefs.edit(), you obtain a NEW reference, not the same object.
SharedPreferences.Editor prefs = getSharedPreferences("MyPrefName", 0).edit();
[..]
prefs.putString(..);
[..]
prefs.commit();
Upvotes: 0
Reputation: 9276
What you are doing wrong is that you are obtaining a new Editor
object every time you are calling SharedPreferences.edit()
. which according to the documentation does :
Create a new Editor for these preferences, through which you can make modifications to the data in the preferences and atomically commit those changes back to the SharedPreferences object.
so to solve this issue you need to call edit only once. your code can be changed to this:
@Override
protected void onPause()
{
super.onPause();
SharedPreferences prefs = getSharedPreferences("MyPrefName", 0);
Editor edit = prefs.edit();
if(socket!=null && socket.isConnected())
{
releaseOutputSocket();
edit.putString("started", "started");
}
else
edit.putString("started", "stoped");
edit.commit(); //res == true
}
Upvotes: 0
Reputation: 36035
You're creating a new SharedPreferences.Editor each time and committing a blank one. You're not committing the other ones. Instead to this:
SharedPreferences.Editor edit = prefs.edit();
edit.putString("newString", "started");
edit.commit();
Upvotes: 1