Passing Arguments in Android using Safe Args by Navigation Library
Passing Arguments from Fragment to Fragment using Safe Args provided by Navigation
Android Bundle
- Fragments contain arguments in the form of an Android Bundle.
- It is a Key Value store also known as dictionary or associative array.
- Dictionary is a data structure where we use a unique key such as 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 few data classes such as array list.
Use Case :
- Declare the arguments and assign val
- Pass the arguments to the fragments.
argBundle = Bundle()
argBundle.putString(CoolConstants.ARGUMENTS_KEY_STRING, "Content")
argBundle.putInt(CoolConstants.ARGUMENTS_KEY_INT, 14)
val fragment = PlayFragment()
fragment.arguments = argBundle
This works but it can generate bugs likes :
- Types : we have to make sure the types match
- Getting an integer from a string within the bundle returns a default value of zero.
- If we try to get an argument as a string that you haven't set in the bundle it will return null.
- There is no way to guarantee that what you pass into fragment A is what recipient asks for on the other end.
val name = arguments?.getString(CoolConstants.ARGUMENTS_KEY_STRING)
Safe Args
- Safe Args is a gradle plugin that generates code to helps guarantee that the arguments on both side match up.
- It also simplifies argument passing.
Use Case:
- Add the classpath for the navigation-safe-args-gradle-plugin into project Gradle file
- Apply plugin to app Gradle file
// safe args
def nav_version = "2.3.2"
classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"
apply plugin: "androidx.navigation.safeargs"
apply plugin: "androidx.navigation.safeargs"
id "androidx.navigation.safeargs"
view.findNavController().
navigate(PlayFragmentDirections.actionPlayFragmentToGamewonFragment(answer as String))
var args = arguments?.let { GamelostFragmentArgs.fromBundle(it) }
lost_answer.text = args?.answer?:""
Comments
Post a Comment