In a normal fragment transaction we would pass data as:
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);
Isn't this type safe too? So what does it mean when we say that safe args are type safe? What exactly does type safety mean when we say that safe args are type safe?
Thanks in advance!
Yes, you provided the regular form of passing arguments between fragments. This is type safe because
Bundleclass provide API to put and get data of different types. It means that you will not encounterClassCastExceptionusing it (see detailed explanation below)I presume you're talking about Safe args, which is a Gradle plugin for Android that provides a type-safe and easy-to-use mechanism for passing data between destinations in the Android Navigation component.
With Safe Args, you define the arguments for each destination in an XML file, and the plugin generates a strongly-typed class for each destination that contains accessor methods for each argument. These classes help to ensure that the arguments are of the correct type and prevent runtime errors caused by incorrect argument values. That makes this way of passing type safe and you can use it when you're using Android Navigation component.
So you can define your fragments like this:
And start this fragment, passing arguments with Safe Args:
Update
When you use the standard way of passing objects between fragments, it is not being checked on the compile time. So for instance, if you put
Intvalue in aBundleand try to get aStringwith a same key it will return the default value.For example the value of
valuevariable will be null in the example below:You can see why it happens in a
BaseBundle.getString()method: