12

I have a simple form where a user can add, edit, and delete people from a list. When a user has chosen to edit a person it executes startActivityForResult so it can make the appropriate changes and refresh the list once the edit is complete. If the user clicks the back button from the edit screen a force close error appears.

I believe it has something to do with the system expecting a result, and I'm not trapping it properly. How would I trap this error?

Here is the onActivityResult code currently in place:


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
 super.onActivityResult(requestCode, resultCode, intent);
 Bundle extras = intent.getExtras();
 switch(requestCode) {
 case ACTIVITY_CREATE:
  String person = extras.getString("person");
  mDbHelper.addPerson(person);
  fillData();
  break;
 case ACTIVITY_EDIT:
  Long rowId = extras.getLong("_id");
  if (rowId != null) {
   String editPerson = extras.getString("person");
   mDbHelper.updatePerson(rowId, editPerson);
  }
  fillData();
  break;
 }
}

Thank you for any help.

alockrem
  • 767
  • 3
  • 9
  • 23

3 Answers3

14

First of all, look at your stack trace using DDMS, it will tell you what line the Exception is occurring on.

What you can do in your calling activity is check for the resultCode, and in your callee activity set it using setResult().

For example, if the user pressed back the resultCode will be RESULT_CANCELED. If this is the case do not try to extract data from the intent.

JRL
  • 76,767
  • 18
  • 98
  • 146
  • Thank you for your help. I'm confident you found the problem, but I'm not sure how to implement it. I searched google and couldn't find an example that matched my scenario. Here is what I attempted to implement, but the error still exists.
    
    case ACTIVITY_EDIT:
     switch (resultCode) {
     case RESULT_OK:
      Long rowId = extras.getLong("_id");
      if (rowId != null) {
       String editPerson = extras.getString("person");
       mDbHelper.updatePerson(rowId, editPerson);
       fillData();
       break;
      }
     }
     break;
    }
    
    Thank you for all of your help.
    – alockrem Aug 22 '10 at 16:22
3

You want to wrap your Activity in an if statement and check resultCode before accessing the intent's bundle:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
 super.onActivityResult(requestCode, resultCode, intent);

// Add this line:
if (resultCode == RESULT_OK) {
 Bundle extras = intent.getExtras();
 switch(requestCode) {
 case ACTIVITY_CREATE:

  break;
 case ACTIVITY_EDIT:

  break;
 }
}
}
Francis Shanahan
  • 2,043
  • 19
  • 21
-2
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK)
    {
        // do your code here
    }
}