سؤال

I want to save some variables after exiting activity which are set during the lifetime of my android activity and show them when I launch activity again but I don't seem to manage to get things working. Here's how I do it:

I created an integer variable "test":

public class MainActivity extends Activity {
int test = 1;

Then I write a method to change this varibale's value by pressing a button:

public void changeValueTest(View view) {
    this.test = 2;
}

Then I use onSaveInstanceState() method to save the changed value:

static final String TEST = "test variable";

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    savedInstanceState.putInt(TEST, this.test);
    super.onSaveInstanceState(savedInstanceState);
}

Then in onCreate() method I put this code to get and show the changed "test" value:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (savedInstanceState != null) {
        this.test = savedInstanceState.getInt(TEST);
        TextView textView1 = (TextView)findViewById(R.id.textView1);
        textView1.setText("Current test value is: " + test);
    }
}

So I open the application, press the button to change the "test" value from 1 to 2, then exit the application, wait until it's properly removed from memory (when Application Manager doesn't show it in "Cached processes" window), start the application again and textView1 view shows 1 instead of 2. What am I doing wrong? Please help! Thanks!

هل كانت مفيدة؟

المحلول

What am I doing wrong?

Nothing. Instance state does not cover the scenario that you are describing.

Mostly, instance state is used in configuration changes (e.g., screen rotation). Secondarily, instance state is used if the user leaves your app by means other than "exit" (by which I assume you mean BACK) and returns to you via means like the recent-tasks list.

نصائح أخرى

As documented in Developer.android , Saved instance only saves your Activity state, It will not save your variable as you wanted, I would suggest you to use SharedPreference instead.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top