简体   繁体   中英

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)?

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 .

This is the Kotlin version of @Eugene Krivenjas textual solution - just in case someone prefers copy/pasting to thinking ;)

private fun Bundle.putLongOrSkip(key: String?, value: Long?) =
    apply { value?.let { putLong(key, value) } }

private fun Bundle.getLongOrNull(key: String?) = 
    if (containsKey(key)) getLong(key) else null

Ofc this is possible for floats and ints , too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM