Passing Data Between Fragments to Activity

88,827

Solution 1

Pass data from each fragment to activity, when activity gets all data then process it. You can pass data using interfaces.

Fragment:

public class Fragment2 extends Fragment {

  public interface onSomeEventListener {
    public void someEvent(String s);
  }

  onSomeEventListener someEventListener;

  @Override
  public void onAttach(Activity activity) {
    super.onAttach(activity);
        try {
          someEventListener = (onSomeEventListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement onSomeEventListener");
        }
  }

  final String LOG_TAG = "myLogs";

  public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment2, null);

    Button button = (Button) v.findViewById(R.id.button);
    button.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        someEventListener.someEvent("Test text to Fragment1");
      }
    });

    return v;
  }
}

Activity:

public class MainActivity extends Activity implements onSomeEventListener{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Fragment frag2 = new Fragment2();
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.add(R.id.fragment2, frag2);
        ft.commit();
    }

  @Override
  public void someEvent(String s) {
      Fragment frag1 = getFragmentManager().findFragmentById(R.id.fragment1);
      ((TextView)frag1.getView().findViewById(R.id.textView)).setText("Text from Fragment 2:" + s);
  }
}

Solution 2

The following link explains the design for communication between fragments.

Communicating with Other Fragments

To allow a Fragment to communicate up to its Activity, you can define an interface in the Fragment class and implement it within the Activity. The Fragment captures the interface implementation during its onAttach() lifecycle method and can then call the Interface methods in order to communicate with the Activity.

Here is an example of Fragment to Activity communication:

public class HeadlinesFragment extends ListFragment {

OnHeadlineSelectedListener mCallback;

// Container Activity must implement this interface
public interface OnHeadlineSelectedListener {
    public void onArticleSelected(int position);
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    // This makes sure that the container activity has implemented
    // the callback interface. If not, it throws an exception
    try {
        mCallback = (OnHeadlineSelectedListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnHeadlineSelectedListener");
    }
}

...
}

Now the fragment can deliver messages to the activity by calling the onArticleSelected() method (or other methods in the interface) using the mCallback instance of the OnHeadlineSelectedListener interface.

For example, the following method in the fragment is called when the user clicks on a list item. The fragment uses the callback interface to deliver the event to the parent activity.

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    // Send the event to the host activity
    mCallback.onArticleSelected(position);
}

Implement the Interface

In order to receive event callbacks from the fragment, the activity that hosts it must implement the interface defined in the fragment class.

For example, the following activity implements the interface from the above example.

public static class MainActivity extends Activity
    implements HeadlinesFragment.OnHeadlineSelectedListener{
...

public void onArticleSelected(int position) {
    // The user selected the headline of an article from the HeadlinesFragment
    // Do something here to display that article
}
}

Deliver a Message to a Fragment

The host activity can deliver messages to a fragment by capturing the Fragment instance with findFragmentById(), then directly call the fragment's public methods.

For instance, imagine that the activity shown above may contain another fragment that's used to display the item specified by the data returned in the above callback method. In this case, the activity can pass the information received in the callback method to the other fragment that will display the item:

public static class MainActivity extends Activity
    implements HeadlinesFragment.OnHeadlineSelectedListener{
...

public void onArticleSelected(int position) {
    // The user selected the headline of an article from the HeadlinesFragment
    // Do something here to display that article

    ArticleFragment articleFrag = (ArticleFragment)
            getSupportFragmentManager().findFragmentById(R.id.article_fragment);

    if (articleFrag != null) {
        // If article frag is available, we're in two-pane layout...

        // Call a method in the ArticleFragment to update its content
        articleFrag.updateArticleView(position);
    } else {
        // Otherwise, we're in the one-pane layout and must swap frags...

        // Create fragment and give it an argument for the selected article
        ArticleFragment newFragment = new ArticleFragment();
        Bundle args = new Bundle();
        args.putInt(ArticleFragment.ARG_POSITION, position);
        newFragment.setArguments(args);

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack so the user can navigate back
        transaction.replace(R.id.fragment_container, newFragment);
        transaction.addToBackStack(null);

        // Commit the transaction
        transaction.commit();
    }
   }
 }

Solution 3

I tried all the above and it didnt work for me. This is how i made it work.I used interface as means to send data from fragment to activity.

FragmentToActivity.java

public interface FragmentToActivity {
void communicate(String comm);

}

FragmentOne

public class FragmentOne extends Fragment {

private FragmentToActivity mCallback;


@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try {
        mCallback = (FragmentToActivity) context;
    } catch (ClassCastException e) {
        throw new ClassCastException(context.toString()
                + " must implement FragmentToActivity");
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_login, container, 
false);
sendData("Andrews");

return v;
}
@Override
public void onDetach() {
    mCallback = null;
    super.onDetach();
}

public void onRefresh() {
    Toast.makeText(getActivity(), "Fragment : Refresh called.",
            Toast.LENGTH_SHORT).show();
  }
private void sendData(String comm)
    {
    mCallback.communicate(comm);

    }

 }


}

Activity One

public class Account extends AppCompatActivity implements 
  FragmentToActivity{

  @Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
 }

@Override
public void communicate(String s) {


    Log.d("received", s);
      }


}

Solution 4

You have to go back information to your fragment's activity. And your Activity dispatch information to its fragments :

// In fragment A
((ParentActivity)getActivity()).dispatchInformations("test");

// In ParentActivity
public void dispatchInformations(String mesg){
    fragmentB.sendMessage(mesg);
}

This is a basic example

Solution 5

You can use Communicator pattern explained in the above answers. Also, You can use RxJava2.for better decoupling and efficiency.

1- Create the bus:

public final class RxBus {

    private static final BehaviorSubject<Object> behaviorSubject
        = BehaviorSubject.create();


    public static BehaviorSubject<Object> getSubject() {
        return behaviorSubject;
    }

}

2- the sender activity or fragment

//the data to be passed
MyData  data =getMyData();
RxBus.getSubject().onNext(data) ;

3-the receiver activity or fragment

private Subscription subscription;

public onCreate(Bundle savedInstanceState){
    subscription = RxBus.getSubject()
                    .subscribe(new Subscriber<Object>() {

            @Override
            public void onNext(Object o) {
                if (o instanceof MyData) {
                    Log.d("tag", (MyData)o.getData();
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
}

4-unSubscribe to avoid memory leacks:

@Override
protected void onDestroy() {
    super.onDestroy();
 if(subscription!=null){
     subscription.unsubscribe();
   }

}
Share:
88,827
Androi Developer
Author by

Androi Developer

Updated on July 09, 2022

Comments

  • Androi Developer
    Androi Developer almost 2 years

    I need to pass data between from 5 fragments to one Activity, those fragments send data one after another when i reach 5'th fragment then i need to store all 5 fragments data how can we do this. any idea is Great.enter image description here

  • Androi Developer
    Androi Developer over 11 years
    I did like this, when i click, iPhone inthat fragment i have some button and edit text then when i submit i am comming to main screen. again when i click rest of the list items i am performing same operations at the end when i click All Info then i need to send iPhone,BlackBerry,Android,Nokia data to different activities. I don't know how to do this.(stackoverflow.com/questions/14439941/…)
  • Shiva
    Shiva over 11 years
    Can you be more elaborate on the problem you are facing? What is it that you are trying to achieve?
  • srujan maddula
    srujan maddula about 10 years
    Hey Kalyanganov Alexey can you elobarate me how to pass data using interfaces if it is with a simple example appreciated...
  • Kalyaganov Alexey
    Kalyaganov Alexey about 10 years
    Shure. Google have good examples developer.android.com/training/basics/fragments/…
  • Hoo
    Hoo over 8 years
    but if I only have one button which is in the last fragment, how can I do that? stackoverflow.com/questions/32953477/pass-data-to-fragment
  • Variag
    Variag over 5 years
    I've tried your solution. Basically it works but it needs some modifications
  • Jagadeesh
    Jagadeesh almost 3 years
    I have tried many methods none of them is worked. Your method is working. Thank you so much :)
  • Karan Malhotra
    Karan Malhotra over 2 years
    Got null pointer exception at sendData(). By the way, you are sending data back to that activity that inflated this fragment. Right?