1

What is the best way to pass data from one fragment to another in android ? I know Otto and Event Bus can handle the issue, but what exactly should the non-library way to do out?

Please consider following before answering

http://developer.android.com/training/basics/fragments/communicating.html

Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.

Gufran Khurshid
  • 888
  • 2
  • 9
  • 28

3 Answers3

3

You can do it using Bundle

MyFragment fragment = new MyFragment ();
Bundle data= new Bundle();
data.putString("Key", "Value");
fragment .setArguments(args);    
getFragmentManager().beginTransaction().add(R.id.container, fragment ).commit();

Retrieve the bundle in another fragments onCreate by

String value = getArguments().getString("Key");
Vishwajit Palankar
  • 3,033
  • 3
  • 28
  • 48
  • That's the way to do it when creating a new fragment, but I think the question is what to do when you already have two fragments in place and need to send data between them. – patrick.elmquist Apr 28 '15 at 06:51
  • Please consider following before answering http://developer.android.com/training/basics/fragments/communicating.html Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly. – Gufran Khurshid Apr 29 '15 at 07:32
0

If you don't use Otto / EventBus then you should use listener interfaces.

inmyth
  • 8,880
  • 4
  • 47
  • 52
0

Implement a listener in your MainActivityand pass the value to another fragment from the MainActivity. Fragments are generally used as reusable components and it is always better to reduce the coupling between fragments using listener interfaces in your MainActivity.

Renjith
  • 3,274
  • 19
  • 39