I am tring to make the part of a game where when you press the fab icon, a TextView, increase numbers. It starts from zero and increased by one. I tried to save the number, in order to find it the next time, start the app and continue to increase it. I am new at saving and I searched it a little bit.
I wrote a code, where keeps the number when I close it and reopen it, but when I push the fab icon, it starts from the beginning and not from the number I have saved. Perhaps I didn't understand very well the save code how it works. Can anyone help me? Thank you!!
My code in MainActivity is:
int newAge;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final TextView age = (TextView) findViewById(R.id.age);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
newAge++;
age.setText(String.valueOf(newAge));
}
});
//getting preferences
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
int savedAge = prefs.getInt("key", 0); //0 is the default value
age.setText(String.valueOf(savedAge));
}
@Override
protected void onStop(){
super.onStop();
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("key", newAge);
editor.commit();
}
You have to apply savedAge
to newAge
, because once you load your age from the SharedPreferences
, you only apply the laoded age to the TextView and if you click on the button, the TextView will display 1 instead of your saved value.
int newAge;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final TextView age = (TextView) findViewById(R.id.age);
//getting preferences
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
int savedAge = prefs.getInt("key", 0); //0 is the default value
age.setText(String.valueOf(savedAge));
newAge = savedAge; //set the age value, to further increase it by a button click
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
newAge++;
age.setText(String.valueOf(newAge));
}
});
}
@Override
protected void onStop(){
super.onStop();
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("key", newAge);
editor.commit();
}
Try to read through this, to get a better understanding of SharedPreferences in Android.