1

I have two fragments and one activity + Main Activity

  1. 1st Fragment where new intent is created that calls the Activity
  2. Activity that is called by above mentioned intent. I want to pass data here
  3. 2nd Fragment from where I want to get Strings from textviews and pass the results to Activity mentioned above

so the fragment that has intent does not contain the information that I want to pass, but another fragment contains, that does not have intent.

The one solution I see is to incorporate 1st Fragment and Activity Code into MainActivity but in this case, I have to copy all my code there.

Is there any other solution?

Ana Koridze
  • 1,532
  • 2
  • 18
  • 28

5 Answers5

1

Create an interface in Fragment1 and this interface must be implement by activity. it will make communicated between Fracment1 and activity. And in implement method you call Fragment

private OnFragmentInteractionListener mListener;

Method when buttin is clicked

    public void onButtonPressed() {
    if (mListener != null) {
        mListener.onFragmentInteraction(data);
    }
}

interface which will be implement by activity

public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    public void onFragmentInteraction(String data);
}
Hiếu Giề
  • 97
  • 1
  • 16
1

I hope i understood your problem.

public class Fragment1 extends Fragment
{
  public Intent getIntent ()
  {
    return neededIntent;
  }
}


public class Fragment2 extends Fragment
{
  public String getStringData ()
  {
    return stringData;
  }
}

public class MyActivity extends Activity
{
  public void makeIntent ()
  {
    Intent i = fragment1.getIntent ();
    String data = fragment2.getStringData ();
  }
}
King Natsu
  • 461
  • 4
  • 19
1

Give tag to both fragments You can create public method in 2nd fragment to get required text and in 1st fragment access that fragment like this

Fragment frag2 = getFragmentMangegetFragmentManager().findFragmentByTag("Frag2");
if(frag2 != null){
text = frag2.getRequiredText();
}
1

If you just wanna pass data from 2nd Fragment to it father Activity you can do as below:

//in 2nd Fragmnet you can call whenever you want:
if(getActivity() != null && getActivity() instanceof  FatherActivity){
     // You can create setYourData in your Father Activity.
     ((FatherActivity)getActivity()).setYourData(yourData);         
}
Kingfisher Phuoc
  • 8,052
  • 9
  • 46
  • 86
1

Are U asking about this ? see this http://developer.android.com/training/basics/fragments/communicating.html

adamin90
  • 216
  • 1
  • 7