I have been trying to save a Boolean named "first", which signifies whether the activity has been started for the first time since installing the app. The boolean "first" is initially true but then set to false after the activity has been used once (i.e. The value is set to false, right before the next activity is started). I have tried saving this boolean using SharedPreferences but whenever I start the app after killing it, the MainActivity is still displayed again (this shouldn't happen if "first" is false").
My MainActivity.java looks like this -
protected final static String INTENT_KEY = "NAME";
private static final String PREFS_NAME = "SaveStates"; //The SharedPreferences file name.
private Boolean first = true; // Signifies whether the app started for the first time.
SharedPreferences settings;
SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
settings = getSharedPreferences(PREFS_NAME, 0);
editor = settings.edit();
resetParam(); // Retrieving the boolean "first".
// Start the next activity if the app has been started before.
if (!first) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
startActivity(intent);
}
setContentView(R.layout.activity_main);
}
/** Sends the name input by the user to the next activity */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_name);
String name = editText.getText().toString();
// Send name to next activity if it's not empty.
if (!("".equals(name))) {
setParam(); // SETTING AND SAVING "first" AS FALSE.
intent.putExtra(INTENT_KEY, name);
startActivity(intent);
}
}
/** Saving the Boolean "first" in the SharedPreferences PREF_NAME file */
private void setParam() {
// Saving the Boolean "first" in the SharedPreferences PREF_NAME file.
editor.clear();
editor.putBoolean("first", false);
editor.commit();
}
/** Retrieving the Boolean "first" from the SharedPreferences PREF_NAME file */
private void resetParam() {
first = settings.getBoolean("first", true);
}
When I use the app for the first time (i.e. "first" is true), go to the next activity (i.e. "first" is set to false before the next activity starts), kill the app completely and come back to it, why do I start from the MainActivity again? Why isn't the "first" saved as false in my SharedPreferences file (PREFS_NAME)?