How do I handle the back button when startActivityForResult is active?

前端 未结 3 1640
囚心锁ツ
囚心锁ツ 2021-01-04 11:35

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 th

相关标签:
3条回答
  • 2021-01-04 12:11

    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.

    0 讨论(0)
  • 2021-01-04 12:14

    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;
     }
    }
    }
    
    0 讨论(0)
  • 2021-01-04 12:28
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK)
        {
            // do your code here
        }
    }
    
    0 讨论(0)
提交回复
热议问题