I am using SharedPreference to store the state of checkboxes but even i am storing true in it , its still retrieving false.
Here is my code -
@Override
public void onPause()
{
super.onPause();
saveState();
}
@Override
public void onResume()
{
super.onResume();
loadState();
}
@Override
public void onRestart()
{
super.onRestart();
loadState();
}
public void saveState()
{
SharedPreferences sp = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
for(int i = 0; i < itemCheck.length; i++)
{
Boolean b = itemCheck[i];
Log.e(TAG, b.toString());
editor.putBoolean(i+"", itemCheck[i]);
}
}
public void loadState()
{
SharedPreferences sp = getPreferences(Context.MODE_PRIVATE);
for(int i = 0; i < itemCheck.length; i++)
{
itemCheck[i] = sp.getBoolean(i+"", false);
Boolean b = itemCheck[i];
Log.e(TAG, b.toString());
}
for(int i = 0; i < itemCheck.length; i++)
{
lv.setItemChecked(i, itemCheck[i]);
}
}
Its giving me false because i set false as a default value in getBoolean which should be returned in the absence of predefined key. Please take a look and tell me what i di开发者_JAVA百科d wrong. Thanks
You never call commit()
on your editor I think :)
Try this:
public void saveState()
{
SharedPreferences sp = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
for(int i = 0; i < itemCheck.length; i++)
{
Boolean b = itemCheck[i];
Log.e(TAG, b.toString());
editor.putBoolean(i+"", itemCheck[i]);
}
editor.commit();
}
use editor.commit()
after editor.putBoolean(i+"", itemCheck[i]);
精彩评论