0

I have a button that increase a variable by one and the result is printed in a TextView. When I rotate the device the variable value is maintained, but if I exit the activity and then re-enter, every value is reset. How can I fix this?

int n=0;

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

    final TextView tv = (TextView)findViewById(R.id.tvProva);
    Button b = (Button)findViewById(R.id.bProva);

    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            n++;
            tv.setText(""+n);
        }
    });

    if(savedInstanceState!=null){
        n = savedInstanceState.getInt("n");
        tv.setText(""+n);
    }
}


@Override
protected void onSaveInstanceState(Bundle outState) {

    super.onSaveInstanceState(outState);

    outState.putInt("n", n);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
    super.onRestoreInstanceState(savedInstanceState);

    savedInstanceState.getInt("n");
}
Lorenzo
  • 11
  • 2
  • 1
    You can use shared preferences. You can save the last updated value in preferences in method onStop, and after restarting activity you can retrieve the same value in onCreate method. – Tejas Shelke Apr 26 '19 at 10:38

1 Answers1

0

There are a couple of potential options.

SharedPreferences, as Tejas said, below is an example of how you might use this;

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); 

To save you value;

Editor editor = pref.edit();
editor.putInt("n", n);
editor.apply();

To retrieve your value;

pref.getInt("n", 0);

The above was taken from a previous post; https://stackoverflow.com/a/24099496/4644276

Alternatively you could leverage the Repository pattern. A repository in simplest terms is an object that can persist for the life of the application, therefore it can persist across different activities. It cannot however survive killing the application unless you leverage SharePreferences as previously discussed or using an API or local database.

If you'd like to look in to the repository pattern further than it is discussed in the Guide to app architecture page on the Android Developer portal.

https://developer.android.com/jetpack/docs/guide

Daniel T-D
  • 665
  • 6
  • 8
  • Repository pattern ? are you trying to say singleton to store the value ? – akshay_shahane Apr 26 '19 at 11:03
  • You could leverage a Singleton, it depends on the nature of what you're storing. In this case it's not ideal as that value doesn't need to be accessed outside of the Activitie's domain. I was merely suggesting it as option because the titled question was "Restoring variables if exit and re-entering activity" and a Singleton could be an option. – Daniel T-D Apr 26 '19 at 11:06