Trying to sent data from activity to fragment

Viewed 37

In Main

override fun pastDada(name: String) {
        val bundle = Bundle()
        bundle.putString("USER_NAME", "DDDDDDDD")

        val transction = this.supportFragmentManager.beginTransaction()
        val profileFragmant = fragment_profile()
        profileFragmant.arguments = bundle
        transction.replace(R.id.container,profileFragmant)
    }

In Frafment:

override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        var view =  inflater.inflate(R.layout.fragment_profile2, container, false)


        name = arguments?.getString("USER_NAME")
        Log.e("name", arguments?.getString("USER_NAME").toString())

        Log.e("name", name.toString())
        view.tv_name.text = name

        return view
    }

the result of Log.e("name", name.toString()) is always null and I dont know why maby its becuse my arguments is empty? and if it is,how am I supose to slove it?

Thanks

1 Answers

change your code like this

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    var view =  inflater.inflate(R.layout.fragment_profile2, container, false)


    val bundle = arguments
    val name = bundle!!.getString("USER_NAME")

    Log.e("name", name.toString())
    view.tv_name.text = name

    return view
}
Related