jerry jerry - 5 months ago 13
Android Question

Passing Nullable Values from Activity to Fragment

When passing

Strings
from an activity to a fragment using

Bundle args = new Bundle();
args.putString(key, value);
fragment.setArguments(args);


I can also pass potential
null
and receive it in the fragment with

String string = getArguments().getString(key);


I'd also like to pass nullable
Float
s and
Integer
s but the corresponding
putInt()
and
putFloat()
methods don't allow passing
null
. I am now passing additional flags as arguments that indicate whether a value is set or not but that seems rather clumsy in comparison. Is there a better way to pass potential null values (preferably available in API level 14 and later)?

Answer

I prefer to skip putting something in case of null into bundle.
In fragment just check Bundle.containsKey(String key), if doesn't means null.