I have an activity which lets the user select a phone number. Naturally, I'd like my class to remember the id of the contact selected, so I save this in a class field. However when the method onActivityResult returns, my class variable is reset. Here is what I'm trying to do:
Intent intent = new Intent(Intent.ACTION_PICK, People.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
...
public void onActivityResult(int reqCode, int resultCode, Intent intent){
super.onActivityResult(reqCode, resultCode, intent);
switch(reqCode){
case(PICK_CONTACT):
if(resultCode == Activity.RESULT_OK){
Uri contactData = intent.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if(c.moveToFirst()){
contactName = c.getString(c.getColumnIndexOrThrow(People.NAME));
contactId = c.getInt(c.getColumnIndexOrThrow(People._ID));
break;
When I set a breakpoint within this method, the values for contactName and contactId are as I expect, however once the method returns, the values somehow get reset to their defaults. Clearly I'm missing something, but I'm not sure what I'm doing wrong or forgetting.
Thanks!
Iva
Activity
is being Suspended and Re-created.Essentially, if the Intent you're launching with startActivityForResult
is resource-intensive enough, the OS might have to suspend your Activity to free up resources.
So it saves what it can and then returning from the Intent to call onActivityResult
, it has to re-create your Activity. Any instance variables will be reset in this case.
You get around this by either restarting the device or handling it with onSaveInstanceState
and onRestoreInstanceState
.
Read more here: Why oncreate method called after startActivityForResult?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With