I want to send a string data from activity to a fragment, but it always giving error. I checked the links below and tried them, but still same.
send data from activity to fragment android studio Send data from activity to fragment in Android
My code is like below, myActivity.kt (I didn't delete the comment lines, I also tried them too)
img_foto1.setOnClickListener {
val bundle = Bundle()
bundle.putString("imgviewname", "img_foto1")
val fraginfo = adsCameraOrGallery()
fraginfo.arguments = bundle
//val imgviewBundle = Bundle()
//imgviewBundle.putString("coba", "img_foto1")
//imgviewBundle.putSerializable("modelassign", "test")
//val fragmentObj = adsCameraOrGallery()
//fragmentObj.setArguments(imgviewBundle)
//val transactionData: FragmentTransaction = supportFragmentManager.beginTransaction()
//transactionData.add(0, fragmentObj, "viewtaskfragment")
//transactionData.commit()
//val transactionData: FragmentTransaction = supportFragmentManager.beginTransaction()
//transactionData.add(0, fraginfo, "viewtaskfragment")
//transactionData.commit()
var dialog = adsCameraOrGallery()
dialog.show(supportFragmentManager,"Choose photo")
}
Fragment class is like below;
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
var args : Bundle = Bundle()
var dataFromActivity = args.getBundle("imgviewname")
var temp = args.getString("imgviewname")
//comingData = this!!.arguments!!.getString("imgviewname")
}
So from the fragment, both of the lines' data above is null. There is no data coming from the activity.
If I use the line below, in the fragment, this time I'm receving "KotlinNullPointerException" error.
ComingDataFromActivity = this!!.arguments!!.getString("imgviewname")
How can I do that? Thanks.
Regarding to @Mike's suggestions, these lines belove worked for me, updating the post.
Activity;
img_foto1.setOnClickListener {
val bundle = Bundle()
bundle.putString("imgviewname", "img_foto1")
val fraginfo = adsCameraOrGallery()
fraginfo.arguments = bundle
var dialog = adsCameraOrGallery()
dialog.arguments =bundle
dialog.show(supportFragmentManager,"Choose foto")
}
Fragment;
var comingData = this!!.arguments!!.getString("imgviewname")