Class variables set in onActivityResult are reset when method returns
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 try开发者_如何转开发ing 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
It's Possible that your 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?
Not sure if you still need help with this. onActivityResult is called before onResume when your activity is restarting. Make sure you are not resetting the variable values in onResume.
You will receive this call immediately before onResume() when your activity is re-starting.
http://developer.android.com/reference/android/app/Activity.html#onActivityResult(int, int, android.content.Intent)
May be your configuration is changing when you open new Activity. Try to put configChanges
on your activity in AndroidManifest.
android:configChanges="orientation|keyboardHidden|screenSize"
精彩评论