1

I am sending a raw JSON as a String in URI navigation with Navigation library. It looks like this.

findNavController().navigate(
                Uri.parse("android-app://androidx.navigation/checkout/${Gson().toJson(orderSummary)}"),
                NavOptions.Builder()
                    .setEnterAnim(R.anim.transition_slide_in_right)
                    .setExitAnim(R.anim.transition_slide_out_left)
                    .setPopExitAnim(R.anim.transition_slide_out_right)
                    .setPopEnterAnim(R.anim.transition_slide_in_left)
                    .build()
            )
        }

and then I retrieve it like so

            arguments?.getString(key)

This works as expected expect for one test case - special chars are not decoded when retrieving the json (specifically % sign)

So when checking the value of this Uri.parse("android-app://androidx.navigation/checkout/${Gson().toJson(orderSummary)}"), it looks as expected contains the % sign but when doing arguments?.getString(key) the % sign is replaced with ? for an unknown char.

How to keep the special chars when getting the string from the arguments?

Lucho
  • 1,455
  • 1
  • 13
  • 25
Rainmaker
  • 10,294
  • 9
  • 54
  • 89

2 Answers2

2

I just fall in same situation, and was thinking about solution for this. Frankly I don't know if this is the best solution or not, but I've encoded my json string, then when receiving it, I've decode it first then convert it back to original object.

HYG:

Encode deep-link url when sending params like below :

val encoded = URLEncoder.encode(Gson().toJson(orderSummary), StandardCharsets.UTF_8.name())
findNavController().navigate(Uri.parse("android-app://androidx.navigation/checkout/${encoded}}"))

Then when receiving your object in the other fragment, you just need to decode it first

val decoded = URLDecoder.decode(arguments?.getString(key),StandardCharsets.UTF_8.name())
Gson().fromJson(decoded, StandardCharsets.UTF_8.name()),OrderSummary::class.java)

Hope this helping someone facing same issue.

0

I ran into a similar issue, I was trying to pass a string navigation argument that contained a '%' character. Using URLEncoder and URLDecoder had issues for me because the navigation library itself does some decoding so the argument would come back to me already partially decoded and I would get a crash trying to use URLDecoder.

If you look in NavDeepLink.kt in the navigation library you can see in a couple spots they call Uri.decode on the arguments. So if you encode the strings with Uri.encode before navigating it should work properly.

val encoded = Uri.encode(Gson().toJson(orderSummary))
findNavController().navigate(Uri.parse("android-app://androidx.navigation/checkout/${encoded}}"))
Gson().fromJson(arguments?.getString(key), OrderSummary::class.java)