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?
Ideally you would just save state in
Activity1
. That way you wont have to pass the variable around throughActivity2
and then pass a result (which isn't exactly a result of anything done inActivity2
) back toActivity1
. To save the value ofposition
inActivity1
you should do the following inside of yourActivity
: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
inActivity2
, I would recommend not exposingActivity2
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.