2

I have simple counter application where, whenever you click the button, a textview shows the number increasing. If you click the button 10 times, the textview shows 10. Then, when I exit from the app and launch the app again, the application restarts all the activities I have done previously.

How can I continue to count where I left off previously? For example, I want to open my app and count up to 8 with the counter. When I exit, and after re-launching the activity, I want to continue counting where I left off from 8.

Please take a look at the source code:

TextView tv4;
ImageButton button5;
int counter=0;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.content_ikinci);

    tv4=(TextView)findViewById(R.id.textView4);


    button5.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            counter++;
            tv4.setText("" + counter);
        }
    });
William Price
  • 4,033
  • 1
  • 35
  • 54
Royal
  • 51
  • 5
  • 1
    You want to use saved instance state. http://stackoverflow.com/questions/151777/saving-activity-state-on-android – J0B Dec 27 '15 at 12:40

2 Answers2

4

On your activity's onStop() method try to save your data in SharedPreferences

SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
 editor.putInt("key", count); 
 editor.commit();

And when you launch it, on your main Activity onCreate() method retrieve your SharedPreferences value by key and continue where you left off

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
 int count = prefs.getInt("key",0); //0 is the default value.
Bö macht Blau
  • 12,820
  • 5
  • 40
  • 61
Boukharist
  • 1,219
  • 11
  • 19
0

If you need to store little pieces of data throughout your activity's lifecycle it should be enough to store your counter variable in a Bundle inside onSaveInstanceState (Bundle outState) method. Note - don't forget to call super of that method after putting your variable into the Bundle.
This particular Bundle is passed to two methods on recreating Activity: onRestoreInstanceState() and onCreate() methods. So you can reset you instance variable from there.
For more info look here: http://developer.android.com/training/basics/activity-lifecycle/recreating.html