Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class variables set in onActivityResult are reset when method returns

Tags:

android

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

like image 563
ivcheto Avatar asked Jan 16 '10 02:01

ivcheto


1 Answers

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?

like image 129
Joshua Pinter Avatar answered Oct 06 '22 22:10

Joshua Pinter