Home > Blockchain >  When values are sent to a second fragment screen, they are incorrectly displayed
When values are sent to a second fragment screen, they are incorrectly displayed

Time:09-27

When I attempt to display two input views from one fragment to another, I get a problem. The navigation is fully functional. But the values appear as resources.

binding.buttonLogin.setOnClickListener{
val userName = binding.etUserName.toString()
val password = binding.etPassword.toString()
val action = LoginFragmentDirections.actionLoginFragmentToWelcomeFragment(userName, password)
    findNavController().navigate(action)
}

On WelcomeFragment I receive the values in the following way:

val args: WelcomeFragmentArgs by navArgs()
binding.tvUserName.text = args.userName
binding.tvPassword.text = args.password

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.etUserName.text.toString()
val password = binding.etPassword.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.etUserName.text.toString())
bundle.putString("password", binding.etPassword.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.tvUserName.text = arguments?.getString("userName")
binding.tvPassword.text =arguments?.getString("password")
  • Related