startActivityForResult()返回RESULT_CANCELED

时间:2016-09-19 20:12:37

标签: java android android-intent android-activity onactivityresult

我有2个Activity类和1个Non-Activity类,它们从构造函数中传递的Context调用startActivityForResult()。它的外观如下:FirstActivity - > NonActivity - > SecondActivity - > FirstActivity。在SecondActivity中,需要将自定义对象的ArrayList作为结果传递给FirstActivity。这儿存在一个问题。当调用onActivityResult()时,即使调用了setResult(RESULT_OK,intent),resultCode也是RESULT_CANCELED,但不是RESULT_OK。这是我的代码:

NonActivity

public void showActivity() {
    Intent intent = new Intent(request, ActivityKorak.class);
    intent.putExtra("data", fields);

    request.startActivityForResult(intent, 1);
}

SecondActivity

@Override
public void onBackPressed() {
    super.onBackPressed();

    Intent intent = new Intent();
    intent.putExtra("data", fields);
    setResult(Activity.RESULT_OK, intent);

    finish();
}

FirstActivity

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
    super.onActivityResult(requestCode, resultCode, intent);
    if(resultCode != Activity.RESULT_CANCELED){
        if(requestCode == 1) {
            Bundle extras = intent.getExtras();
            ArrayList<CustomInput> fields = (ArrayList<CustomInput>) extras.getSerializable("data");
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您必须简单地删除

super.onBackPressed();
onBackPressed方法

中的

发生的事情是“super.onBackPressed()”将结果代码设置为“RESULT_CANCELED”并完成您的活动。