Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing objects between fragments

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.

  • Using Interface
  • Global class(extends Application class)
  • finally Using bundles

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??

like image 284
Narendhran Avatar asked Feb 16 '17 06:02

Narendhran


People also ask

How do I share objects between fragments?

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.

How pass data from another fragment?

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.


Video Answer


1 Answers

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
}
like image 166
Rachit Avatar answered Oct 13 '22 01:10

Rachit