Search code examples
androidkotlinnavigation

toBundle.toPutInt() method of NavArgs is not working


So, in Android's Navigation, when we want to pass parameters from a FragmentA to a FragmentB, we have two ways to receive this parameter, via Bundle, in FragmentB:

val args: FragmentBArgs by navArgs()

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    val tv: TextView = view.findViewById(R.id.textViewAmount)
    val amount = args.amount
    tv.text = amount.toString()
}

or

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    val tv: TextView = view.findViewById(R.id.textViewAmount)
    val amount = arguments?.getSerializable(KEY_AMOUNT) as Int
    tv.text = amount.toString()
}

Both, I normally get the value. But if I try to change this value directly in the Bundle, the two behave differently. Example:

val args: FragmentBArgs by navArgs()

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    val tv: TextView = view.findViewById(R.id.textViewAmount)
    var amount = args.amount
    tv.text = amount.toString()
    //Trying to change the value to -1
    args.toBundle().putInt(KEY_AMOUNT, -1)
    amount = args.amount
    //The value of amount remains the same, it is not changed to -1
}

In the code below:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    val tv: TextView = view.findViewById(R.id.textViewAmount)
    val amount = arguments?.getSerializable(KEY_AMOUNT) as Int
    tv.text = amount.toString()
    //Trying to change the value to -1
    arguments?.putInt(KEY_AMOUNT, -1)
    amount = args.amount
    //The value of amount is changed and becomes -1
}

They are two different codes, with the same objective. Which should have the same results, but only the last one has the expected result, using arguments?.

The question is because the code using NavArgs from Navigation, does not update the information to -1, even though I request it through the code: args.toBundle().putInt(KEY_AMOUNT, -1)


Solution

  • Because toBundle() returns new bundle consider following code

    fun main() {
        val users = listOf("test1", "test2")
        users.toMutableList().add("test3")
        println(users)
        
        // output: [test1, test2]
    }
    
    

    if I make a mutable list from users and then add an element inside it the code will add the element to the new created list so there is nothing wrong with your example.