Android:不会为不同的结果代码调用onActivityResult

时间:2017-03-02 06:15:28

标签: android android-intent onactivityresult

我正在使用startActivityForResult开始一项活动,就像这样

@Override
public void onEmptyViewClicked(Calendar time) {
    Bundle bundle = new Bundle();
    bundle.putSerializable("time",time);
    bundle.putInt("fragmentId",1);

    Intent intent = new Intent(this,AddEventActivity.class);
    intent.putExtras(bundle);
    startActivityForResult(intent,1);
}

在AddEventActivity中我根据片段id添加片段。第一个片段添加事件和第二个片段删除events.onAddEvent和onDeleteEvent我使用适当的数据setResult

@Override
public void onAddEventClicked(Bundle bundle) {
    Intent intent = new Intent(this,MainActivity.class);
    intent.putExtras(bundle);
    setResult(1,intent);
    finish();
}

@Override
public void eventDelete(Events event) {
    Bundle bundle = new Bundle();
    bundle.putSerializable("deleteEvent",event);

    Intent newIntent = new Intent(this,MainActivity.class);
    newIntent.putExtras(bundle);
    setResult(2,newIntent);
    finish();
}

OnActivityResult代码是这样的

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(resultCode == 1 && data != null){
        if(requestCode == 1){

        }
    }else if(resultCode == 2){

    }
}
}

现在onActivityResult被调用了onAdding事件,但没有被删除event.eventDelete方法被调用但它没有触发onActivityResult。可能是什么问题?谢谢你。

已更新
我在onActivityResult的第一行调试,但调试器并没有就此止步。

2 个答案:

答案 0 :(得分:2)

startActivityForResult(intent,1); 

此处1是您的requestCode

setResult(1,intent);

此处1是您的resultCode

您为两个事件设置相同的resultcode

将您的onActivityResult更改为

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode == 1) {    //add event
        if (requestCode == 1) {
            if (data != null) {

                if (data.getExtras().containsKey("deleteEvent")) {

                } else {
                }
            }
        }
    } else if (resultCode == 2) { //delete event
        //write code
    }
}

答案 1 :(得分:-1)

你应该添加RESULT_OK并验证这个resultCode:

Intent returnIntent = new Intent();
returnIntent.putExtra("returndata");
setResult(Activity.RESULT_OK, returnIntent);
finish();

此后,您需要在onActivityResult方法中添加验证...

     if(requestCode == CODE_REQUEST){
     if(resultCode == Activity.RESULT_OK){
        //do something here
      }{
       //catch cancel result
   }
    }