Search code examples
javaandroidandroid-fragmentsargumentsbundle

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 Floats and Integers 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)?


Solution

  • 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.