i'm (trying) to create a soccer goals calculator, with two activities, MainActivity and Score, but i'd like to save int value that represent goals when clicking on back button, that what i tried:
public class Score extends Activity {
public Button plus;
public Button minus;
public TextView scoretext;
public int value;
public static final String mypreference = "mypref";
SharedPreferences sharedpreferences;
public void save(View v){
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("inte", value); // Storing integer
editor.apply(); // commit changes
}
public void restore(View v){
this.sharedpreferences = this.getSharedPreferences("myPerf",
Context.MODE_PRIVATE);
if (this.sharedpreferences.contains("inte")) {
okeh.setText(this.sharedpreferences.getInt("inte",value));
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score);
plus = this.findViewById(R.id.plus);
scoretext=this.findViewById(R.id.scoretext);
minus=this.findViewById(R.id.minus);
plus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
value++;
String scorestring=String.valueOf(value);
scoretext.setText(scorestring);
}
});
minus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
value--;
String scorestring=String.valueOf(value);
scoretext.setText(scorestring);
}
});
sharedpreferences = this.getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains("inte")) {
okeh.setText(sharedpreferences.getInt("inte", value));
}
}
}