I have made an app that starts a counter when I hold the button, and stops counting as soon as I release the button, then start again as soon as I touch it again.. (The app is made to see how long time I can use, to touch a button.)
Anyway, I have made a way to save the data of the counter, so when I kill the app or press the "back button", the data of the counter saves. BUT as soon as I tap the button again it restarts! I can't find a way to fix this. I think it has to do something with:
chromo.setBase(SystemClock.elapsedRealtime()+time)
;
(Found under "ACTION_DOWN") I've used chronometer as my counter by the way. Please help me!
Here's my code:
public class MainActivity extends ActionBarActivity {
Button button1;
Chronometer chromo;
protected long time = 0;
private SharedPreferences prefs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1=(Button)findViewById(R.id.button1);
chromo=(Chronometer)findViewById(R.id.chromo);
prefs = getSharedPreferences("prefs", Context.MODE_PRIVATE);
long savedValue = prefs.getLong("my_chrono", 0);
if(savedValue == 0)
chromo.setBase(SystemClock.elapsedRealtime());
else
chromo.setBase(SystemClock.elapsedRealtime() + savedValue);
button1.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.ACTION_DOWN){
chromo.setBase(SystemClock.elapsedRealtime()+time);
chromo.start();
}
else if( event.getAction() == MotionEvent.ACTION_UP){
time =chromo.getBase()-SystemClock.elapsedRealtime();
chromo.stop();
prefs.edit().putLong("my_chrono", time).apply();
}
return true;
}
});
}}