user2961375
user2961375

Reputation: 3

how to pass data between fragments in android

i have 2 fragments

in 1st fragment i am calling a 2nd fragment on button click which returns data(on click on list items) and again open 1st fragment with the result displayed (i.e some String data of list item).

But the problem is when i comeback from 2nd to 1st again after selection in 2nd fragment my 1st fragment is displayed only but do not react on button click.

this is my first fragment

i have searched lot but i found activity fragment communication only not fragment to fragment

if any body has solution for fragment to fragment only.please help

Upvotes: 0

Views: 101

Answers (4)

MEGHA RAMOLIYA
MEGHA RAMOLIYA

Reputation: 1927

Step 1: Pass data using a Bundle in FragmentA:

class FragmentA : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_a, container, false)

        // Pass data to FragmentB
        val fragmentB = FragmentB()
        val bundle = Bundle()
        bundle.putString("data_key", "Data from Fragment A")
        fragmentB.arguments = bundle

        // Replace FragmentA with FragmentB
        parentFragmentManager.beginTransaction()
            .replace(R.id.fragment_container, fragmentB)
            .addToBackStack(null)
            .commit()

        return view
    }
}

Step 2: Receive data in FragmentB:

class FragmentB : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_b, container, false)

        val data = arguments?.getString("data_key")

        data?.let {
            // Update UI or perform other operations with the data
        }

        return view
    }
}

Upvotes: 0

Luca Sepe
Luca Sepe

Reputation: 2445

There are a lot of ways, here some hints.

Generally speaking you can use "listeners" (interfaces)

More elegant way using "event bus" paradigm, a clean and simple library is Otto

Upvotes: 1

fida1989
fida1989

Reputation: 3249

Try like this (Example an integer array):

    //Create a public class:
    public class Values{

    public static int[] val = null;

    }


    //Set array in one fragment:
    Values.val = int[] arr1;//arr1 containing your values


    //Get array in another fragment:
    int[] arr2 = Values.val;

Upvotes: 0

C B J
C B J

Reputation: 1868

Another (slightly dirty) way if you are using the compatibility library would be to use the LocalBroadcastManager. Your fragments can send (and listen for) local broadcasts to notify each other of events...

Upvotes: 0

Related Questions