androidandroid-activityactivity-state

Storing and restoring activity states


When calling another activity, can I be sure that the variable I store in the current activity will be present when it returns?

new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapter, View item, int pos, long id)  {
        Intent i = new Intent(Activity1.this, Activity2.class);
        i.putExtra("position", pos); // 1
        position = pos; // 2
        startActivityForResult(i, REQUEST_CODE); // brings up the edit item activity
    }
});

For the code above, can I use (2) by storing in current activity instance field or should I pass the value using (1) then use getIntExtra() in onActivityResult() to recover that value?


Solution

  • Ideally you would just save state in Activity1. That way you wont have to pass the variable around through Activity2 and then pass a result (which isn't exactly a result of anything done in Activity2) back to Activity1. To save the value of position in Activity1 you should do the following inside of your Activity:

        private static final String KEY_ARG_POSITION = "KEY_ARG_POSITION";
    
        private int position;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            // Do whatever you are doing in onCreate already...
    
            if (savedInstanceState != null) {
                position = savedInstanceState.getInt(KEY_ARG_POSITION);
            }
        }
    
        @Override
        public void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
    
            outState.putInt(KEY_ARG_POSITION, position);
        }
    

    This is also relevant if you don't want to lose that value when the screen orientation changes or the OS kills and restarts your Activity.

    Lastly, just for the sake of keeping your code organized, unless you need to use the value of position in Activity2, I would recommend not exposing Activity2 to any data that it does not need to manage. If you are working on a large app, these sorts of things can add up and quickly get messy.