Muhammad Jawad Khalil
Muhammad Jawad Khalil

Reputation: 31

Preserving Value When Orientation Changes

I am developing a very basic Android App that adds a number in TextView whenever I hit the Button. The digit showing in TextView is also preserved when the orientation of the Mobile changes using the onSaveInstanceState() and onRestoreInstanceState() functions.

The problem is when orientation changes the value is preserved but when the Button is pressed once again after the changing of the orientation it again starts the counting from 0 rather then starting it from the preserved value.

My code:

public class MainActivity extends AppCompatActivity {

    TextView showValue;
    int counter=0;

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

        showValue = (TextView) findViewById(R.id.CounterValue);
    }


    public void countIN(View view)
    {
        counter++;
        showValue.setText(Integer.toString(counter));
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString("my_text", showValue.getText().toString());
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        showValue.setText(savedInstanceState.getString("my_text"));
    }
 }

Thank You for your response.

Upvotes: 3

Views: 80

Answers (2)

Zain
Zain

Reputation: 40830

You can save and get data using several methods

First If your data is small, then you can use onSavedInstanceState and onRestoreInstanceState .. for details follow this answer or this one

Second if you have too much data to store, then use ViewModel instead; this is a tutorial that you can start from.

Upvotes: 1

Basi
Basi

Reputation: 3158

add

counter=Integer.parseInt(savedInstanceState.getString("my_text"));

inside onRestoreInstanceState method

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    showValue.setText(savedInstanceState.getString("my_text"));
    counter=Integer.parseInt(savedInstanceState.getString("my_text"));
}

Upvotes: 1

Related Questions