Calvin Klein Bottle Calvin Klein Bottle - 5 months ago 12
Android Question

Android Intents - Getting Results with Fragments

I'm developing an Android program and I have two fragments F1, F2, each hosted by its own Activity, A1 and A2 respectively, such that I need communication between fragments A1F1 and A2F2. A1F1 calls A2F2 and I've successfully passed fragment arguments from A1F1 to A2F2. When the user is on A2F2 and hits the back button to return to A1F1, I want to pass data from A2F2 to A1F1 before A2F2 is destroyed. I have been unsuccessful at this. Here's what I've come up with so far.

A1F1

private static final int REQUEST_ID = 1;
private int mVar;

public void onClick(View v) {
Intent intent = A2.newIntent(getActivity(), xyz.getId());
startActivityForResult(intent, REQUEST_ID);
}

public void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == REQUEST_ID){
mVar = data.getIntExtra(ARG_ID, 0);
}
}


A2F2

private static final String ARG_ID = "XZY";
private int var = 0;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
returnResult();
}

public void returnResult(){
Intent data = new Intent();
data.putExtra(ARG_ID, var);
getActivity().setResult(Activity.RESULT_OK, null);
}


The program crashes on the
mVar = data.getIntExtra(ARG_ID, 0);
line. A breakpoint reveals

requestCode = 1
resultCode = -1
data = null
mVar = 0


In A2F2, I am calling the hosting activity
getResult()
because as I understand fragments cannot hold results. Please help.

Answer

You are not adding intent data to your result. Change your method to -

public void returnResult(){
  Intent data = new Intent();
  data.putExtra(ARG_ID, var);
  getActivity().setResult(Activity.RESULT_OK, data); //Change is here
}
Comments