How to get the same instance of activity in fragments?

Consider the situation: There is mainActivity. Form this activity we can call two fragments: fragmentA and fragmentB.

mainActivity has one getter getValue and one setter setValue.

Most of the time this is how application works: mainActivity is created. From it fragmentA is created. After back button is pressed in fragmentA, application moves back to mainActivity and goes to fragmentB.

What I want to do is, I want to setValue to mainActivity in fragmentA and get that value in fragmentB.

I am not able to do this since it looks like both fragments do not have the same instance of activity.

This is how I try to access setters/getters of mainActivity from fragmentA and fragmentB: ((MainActivity)getContext()).getValue();

What am I doing wrong?

Answer

create a Bunde object in Activity

Bundle bundle = new Bundle();

insert values in bundle (can pass multiple values)
key can be any String and should be unique to each value

 bundle.setString(key,"value");

create object of the corresponding Fragment and attach the bundle to it

 fragmentobject.setArguments(bundle);

in the receiving Fragment create Bundle Object

Bundle fragmentbundle = getArguments();
String value = fragmentbundle.getString(key);

this is how you pass value between fragments and activities or activities and activities

Leave a Reply

Your email address will not be published. Required fields are marked *