Whenever I'm trying to pass data from one fragment to other, In next fragment it's returning null
CodePudding user response:
let's transfer data from Fragment A to Fragment B with a Bundle.
class FragmentB : Fragment() {
companion object {
const val KEY_DATA = "KEY_DATA"
fun newInstance(data: String?) = FragmentB().apply{
arguments = Bundle().apply {
putString(KEY_DATA, data)
}
}
}
Now let's send data from FragmentA to FragmentB.
getNavController().pushFragment(FragmentB.newInstance(data))
I gave string as an example, but you can send any value, you can also send data class.
So, how can we get the data in FragmentB?
val sampleData = arguments?.getString(KEY_DATA)
CodePudding user response:
class MyFragment: Fragment {
...
companion object {
@JvmStatic
fun newInstance(isMyBoolean: Boolean)
= MyFragment().apply {
arguments = Bundle().apply {
putBoolean("REPLACE WITH A STRING CONSTANT"
,isMyBoolean)
}
}
}
}
Here is the Android Studio proposed solution (= when you create a Blank-Fragment with File -> New -> Fragment -> Fragment(Blank) and you check "include fragment factory methods").
Put this in your Fragment:
companion object {
@JvmStatic
fun newInstance(isMyBoolean: Boolean)
= MyFragment().apply {
arguments = Bundle().apply {
putBoolean("REPLACE WITH A STRING CONSTANT"
, isMyBoolean)
}
}
}
}
.apply is a nice trick to set data when an object is created, or as they state here:
Calls the specified function [block] with this value as its receiver and returns this value.
Then in your Activity or Fragment do:
val fragment = MyFragment.newInstance(false)
... // transaction stuff happening here
and read the Arguments in your Fragment such as:
private var isMyBoolean = false
override fun onAttach(context: Context?) {
super.onAttach(context)
arguments?.getBoolean("REPLACE WITH A STRING CONSTANT")?
.let {
isMyBoolean = it
}
}
for more info this should help.