Search code examples
androidandroid-fragmentactivity

Activity with fragment and another Activity return null on onActvityResult


ActivityOne -> Contain FragmentOne and I added method onActivityResult

FragmentOne -> contain recyclerView and on item click startActivityForResult going to ActivityTwo

ActivityTwo -> for item details in the recyclerView in FragmentOne

ActivityOne get null data onActivityResult

Code: 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);
    }
}

Code: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);

Code:ActivityTwo

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

Solution

  • Change onBackPressed() as.You just finished activity without send result back. And one more thing in this case super.onBackPressed() will do same thing as finish.So just call one .

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