Home > Net >  Android: Pass data between fragments using bundle
Android: Pass data between fragments using bundle

Time:07-25

I'm trying to pass data between fragments of different activies using bundles.

I have two fragments: Fragment A is attached on Activity A; Fragment B is attached on another activity: Activity B.

I need to pass an edit text string from Fragment A to Fragment B. How can i accomplish that using bundles? Can someone give me an example in kotlin?

This is what I've tried so far:

Fragment A:

val bundle = Bundle()
                    bundle.putString("data", emailField)
                    val dashboardFragment = DashboardHomeFragment()
                    dashboardFragment.arguments = bundle
                    parentFragmentManager.beginTransaction().apply {
                        replace(R.id.home_nav_graph, dashboardFragment)
                        commit()
                    }

Fragment B:

val inputData = arguments?.getString("data")
binding.emailCv.text = inputData.toString()

Thank you in advance.

CodePudding user response:

You have to pass data from Fragment A and after that you have to receive data in activity B and then use data that you receive in Activity B and use bundle when you send data to Fragment B For Example: In Fragment A

val intent = Intent(context, ActivityB::class.java)
intent.putExtra("data", emailField)
startActivity(intent)

In Activity B

val data = intent.getStringExtra("data")
   val bundle = Bundle()
   bundle.putString("data", data) 
   val fragmentB = FragmentB()
   fragmentB.arguments = bundle
   supportFragmentManager.beginTransaction().apply {
                        replace(R.id.home_nav_graph, fragmentB)
                        commit()}

CodePudding user response:

You can simply use broadcast receiver to send/receive data between this two fragments.

  • Related