Home > Back-end >  Passing views to a second fragment screen does not display them correctly
Passing views to a second fragment screen does not display them correctly

Time:09-27

I am getting an an error when I try to display 2 input views. They are captured in one fragment screen and then I try to display them on a second fragment screen. The navigation works but they display as resources?... i do not even know what it is called.

This is the setOnClickListener that calls up that screen. I suspect it has something to go with safeArgs

binding.buttonConfirm.setOnClickListener{
    val username = binding.editTextUsername.toString()
    val password = binding.editTextPassword.toString()
    val action = LoginFragmentDirections.actionLoginFragmentToWelcomeFragment(username, password) // this is generated class due to nav graph
    findNavController().navigate(action)
}

enter image description here

in Debugger i added some watches enter image description here

I am a newbie to Android, and to stackoverflow as a poster. Thanks for any help

CodePudding user response:

You're calling toString() on the EditText and not actually getting the text the user has entered - to do that, you need to call getText() which in Kotlin code, you can do via the text property:

val username = binding.editTextUsername.text.toString()
val password = binding.editTextPassword.text.toString()
val action = LoginFragmentDirections.actionLoginFragmentToWelcomeFragment(username, password) // this is generated class due to nav graph
findNavController().navigate(action)

CodePudding user response:

You are taking the view itself instead of its value. To do so, grab the value, not the view.

binding.buttonConfirm.setOnClickListener{
val username = binding.editTextUsername.text.toString()
val password = binding.editTextPassword.text.toString()
val action = LoginFragmentDirections.actionLoginFragmentToWelcomeFragment(username, password) // this is generated class due to nav graph
    findNavController().navigate(action)
}

Alternatively, you can pass data between destinations with Bundle objects.

Create a Bundle object and pass it to the destination using navigate(), as shown below:

val bundle = Bundle()
bundle.putString("username", binding.editTextUserName.text.toString())
bundle.putString("password", binding.editTextPassword.text.toString())
view.findNavController().navigate(R.id.actionLoginFragmentToWelcomeFragment, bundle)

In your receiving destination’s code, use the getArguments() method to retrieve the Bundle and use its contents:

binding.textViewUserName.text = arguments?.getString("username")
binding.textViewPassword.text =arguments?.getString("password")
  • Related