Leitvoll
Leitvoll

Reputation: 53

How to make the app not resetting itself?

I have made a counter app that counts down from 100000. Every time I rotate my device 90° or stops it, it starts from 100000 again. How do I make my app stop resetting itself?

Code:

public class SecondActivity extends Activity {

    int counter = 1000001;

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

    public void onClick(View v){}

    public void button1 (View v){
        counter--;
        final Button button2 = (Button) findViewById(R.id.button2);
        button2.setText("" + counter); 
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.second, menu);
        return true;
    }

}

Upvotes: 0

Views: 87

Answers (3)

Yauraw Gadav
Yauraw Gadav

Reputation: 1746

The value of the counter won't persist this way, you will need to use someway to save this value either in SharedPreferences or somewhere at least.

Upvotes: 0

Jitender Dev
Jitender Dev

Reputation: 6925

Understand this thing Each time you rotate your phone i.e. change orientation your instance of activity gets destroyed and new instance of activity gets created i.e. your activity gets re-created followed by activity life cycle. You can't control this behavior but you can save the last counter in SharedPreferences like the last method of activity that will be called is onDestroy(). In this method save the counter and in onCreate() Method get the value of saved time and start the counter from there only.

Upvotes: 0

Robin Krahl
Robin Krahl

Reputation: 5308

Android destroys and rebuilds the current activity on an orientation change. You have to save the state of your activity by implementing the onSaveInstanceState() and onRestoreInstanceState() methods of your Activity.

See this article on developer.android.com for details.

Upvotes: 2

Related Questions