Basically I am making a tally
counter app which uses int++
to increase the number. I have managed to save whatever number the user has counted up to using SharedPreferences
. Once the app is closed and releaunched the number is still there but once the user presses a button to add or subtract from the counter it restarts from 0 again. How can i make the integer counter continue from where it left off last (and example would be if the user counted up to 20 and relaunched the app they could continue counting from 20 instead of restarting from zero). Here is the code to provide some context:
public class MainActivity extends Activity implements OnClickListener{
public static final String PREFS = "examplePrefs";
Button b1;
Button b2;
TextView tv1;
TextView tv2;
int counter;
int counter2;
String stringCounter;
String stringCounter2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button1);
b2 = (Button) findViewById(R.id.button2);
tv1 = (TextView) findViewById(R.id.textView1);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
SharedPreferences example = getSharedPreferences(PREFS, counter);
String userString = example.getString("userMessage", "Nothing Found");
tv1.setText(userString);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v==b1){
counter++;
stringCounter = Integer.toString(counter);
tv1.setText(stringCounter);
SharedPreferences examplePrefs = getSharedPreferences(PREFS, counter);
Editor editor = examplePrefs.edit();
editor.putString("userMessage", stringCounter);
editor.commit();
}
if (v==b2){
counter--;
stringCounter = Integer.toString(counter);
tv1.setText(stringCounter);
SharedPreferences examplePrefs = getSharedPreferences(PREFS, counter);
Editor editor = examplePrefs.edit();
editor.putString("userMessage", stringCounter);
editor.commit();
}
}
}