具有片段和另一个Activity的活动在onActvityResult上返回null

时间:2017-12-11 09:30:44

标签: android android-fragmentactivity

ActivityOne - >包含FragmentOne,我在onActivityResult上添加了方法

FragmentOne - >包含recyclerView和项目单击startActivityForResult转到ActivityTwo

ActivityTwo - >对于FragmentOne中的recyclerView中的项目详细信息

ActivityOne获取onActivityResult

的空数据

代码: ActivityOne

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Utils.showToast("intent receive");
    if (requestCode==1111 && resultCode == RESULT_OK){
        int position =(int) data.getExtras().get("position");
        Log.d("TAG", "onActivityResult: "+ position);
    }
}

代码:FragmentOne

   Intent i = new Intent(mContext.getApplicationContext(), ActivityTwo.class);
            Bundle bundle = new Bundle();
            bundle.putInt("id", id);
            bundle.putInt("position",position);
            i.putExtras(bundle);  
            ((Activity) mContext).startActivityForResult(i,1111);

代码:ActivityTwo

@Override
public void onBackPressed() {
    super.onBackPressed();
    if (hasChanges){
        Intent intent = new Intent();
        intent.putExtra("position",position);
        setResult(Activity.RESULT_OK,intent);
    }
    finish();
}

1 个答案:

答案 0 :(得分:5)

更改onBackPressed() as.You刚刚完成活动而没有发回结果。 在这种情况下,super.onBackPressed()还会做另外一件事,就像完成一样。只需要调用一个。

 @Override
public void onBackPressed() {
    if (hasChanges){
        Intent intent = new Intent();
        intent.putExtra("position",position);
        setResult(Activity.RESULT_OK,intent);
    }
    super.onBackPressed();
}