I am bit confused with how this shared preference works. I had a sample code from a website based on shared preferences. My problem is, editor.commit() doesn’t update immediately. Here is my sample code,
public class PreferencesDemo extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get the app's shared preferences
SharedPreferences app_preferences =
PreferenceManager.getDefaultSharedPreferences(this);
// Get the value for the run counter
int counter = app_preferences.getInt("counter", 0);
// Update the TextView
TextView text = (TextView) findViewById(R.id.text);
TextView text1 = (TextView) findViewById(R.id.text1);
text.setText("This app has been started " + counter + " times.");
// Increment the counter
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("counter", counter+2);
editor.apply();
editor.commit(); // Very important
text1.setText("This app has been started " + counter + " times.");
}
}
As you can see, I have counter whose value I am displaying in the first textView and after the commit statement I am printing the updated value in next TextView. But still both the textviews prints the same default value as ‘0’. So if I restart the app, both the textviews are updated.
How to solve this problem. Any help is appreciated.
try this
for store value in sharePreferences..
for get value