Adding Safe Arguments

Passing arguments from FragmentA to FragmentB

Fragments contain arguments in the form of an android bundle, which is a key value store :
A key value store also known as a dictionary or associative array is a data structure which use a unique key such as a string to fetch an Associated Value, there are limited types that can be stored as values in a bundle primitive types such as char, int and float along with various types of arrays, char sequence and a few data classes such as array list.

// first create a bundle val argBundle = Bundle()
argBundle.putString(NAME_KEY_STRING, "content")
argBundle.putInt(SERIAL_KEY_INT, 42)

// finally we set it to fragment when we create itvar fragment = FramentB()
fragment.arguments = argBundle


There are few ways which can create a problems like:

  • It's up to the developer to make sure that the types of arguments match ex. getting the integer from the string within the bundle returns, the default value of zero. 
  • If you try to get the argument of the string that you haven't set in the bundle, it will return null. 
  • There's no way to guarantee that what you pass in to fragmentA is what the recipient asks for in other end. 
So the navigation includes a feature called safe args that can help. 


Safe Args 
 It's the gradle plugin that generates code to help guarantee that the arguments on both side match up while also simplifying arguments passing because it's a Gradle plug-in using it is a two step process in terms of what to add to your Gradle files first. 

1. Add safe-args dependency to project Gradle file. 
"android.arch.navigation:navigation-safe-args-gradle-plugin:$version_navigation"

2. Add safe-args plugin to app Gradle file
apply plugin: 'kotlin-kapt'
apply plugin: 'androidx.navigation.safeargs'

3. Switch the FragmentA to use generated NavDirections when navigating to the FragmentB and FragmentC
view.findNavController().navigate(GameFragmentDirections.actionFragmentAToFragmentB()


4. Add the arg1 and arg2 Integer Arguments using the navigation editor
view.findNavController().navigate(GameFragmentDirections.actionFragmentAToFragmentB(arg1,arg2))


5. Add the parameters to the FragmentA to FragmentB action
view.findNavController().navigate(GameFragmentDirections.actionFragmentAToFragmentB(arg1,arg2))

6. Fetch the args and expand into a class in onCreate within the FragmentB

7. Display the arguments using a Toast
val args = FragmentB.fromBundle(arguments!!)
Toast.makeText(context, "ARG 1 : ${args.arg1}, ARG 2 : ${args.arg2}", Toast.LENGTH_LONG).show()

8. Replace navigation to action IDs with NavDirections in FragmentA, FragmentB, and FragmentC



Comments

Popular Posts