Iam using build-in Navigation drawer activity with three fragment menus, I want to communicate over those fragments means wants to pass data from one to another. And I found there is a three possible way to communicating with fragments. Also I have understood clearly that the fragment never communicate directly.
And now my question is which is the best way to communicate with fragments, currently Iam using second method
which is I put(getter&setter class) all those object to the Globalized objects which extends Application Class
. Is this the right approach or not??
In android, we can use ViewModel to share data between various fragments or activities by sharing the same ViewModel among all the fragments and they can access everything defined in the ViewModel. This is one way to have communication between fragments or activities.
To pass data between fragments in the same fragment manager, the listener should be added to the destination fragment with requestKey in order to receive the result produces from another fragment with the same key.
You can implement Serializable in your Object class and then pass it simply using bundles. I'm assuming you're launching the second_fragment from your first_fragment.
In your first Fragment:
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
Fragment2 fragment2 = new Fragment2();
Bundle bundle = new Bundle();
YourObj obj = SET_YOUR_OBJECT_HERE;
bundle.putSerializable("your_obj", obj);
fragment2.setArguments(bundle);
ft.replace(android.R.id.content, fragment2);
ft.addToBackStack(null);
ft.commit();
In Fragment two:
Bundle bundle = getArguments();
YourObj obj= (YourObj) bundle.getSerializable("your_obj");
EDIT
To Serialize your object, simply implement Serializable in your Object class.
If your Object class is YourObj.class
public class YourObj implements Serializable {
int id;
String name;
// GETTERS AND SETTERS
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With