Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix storing of Array in SavedStateHandle/Bundle #1708

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,7 @@ actual fun bundleOf(vararg pairs: Pair<String, Any?>): Bundle = Bundle(pairs.siz
is ShortArray -> putShortArray(key, value)

// Reference arrays
is Array<*> -> putArray(key, value)
is ArrayList<*> -> putArrayList(key, value)
// Perform extra round (with copy) because of compatibility purposes.
// Unlike Android, `listOf` result might be not castable to `ArrayList`.
Expand All @@ -225,6 +226,24 @@ actual fun bundleOf(vararg pairs: Pair<String, Any?>): Bundle = Bundle(pairs.siz
}
}

@Suppress("UNCHECKED_CAST")
private inline fun Bundle.putArray(key: String?, value: Array<*>) {
// Unlike JVM, there is no reflection available to check component type
when (value.firstOrNull()) {
is String -> putStringArray(key, value as Array<String?>?)
is CharSequence -> putCharSequenceArray(key, value as Array<CharSequence?>?)
// Narrowed alternative of Android's [putParcelableArray]
is Bundle -> putBundleArray(key, value as Array<Bundle?>?)
else -> {
if (value.isEmpty()) {
putStringArray(key, value as Array<String?>?)
} else {
throwIllegalValueType(key, value)
}
}
}
}

@Suppress("UNCHECKED_CAST")
private inline fun Bundle.putArrayList(key: String?, value: ArrayList<*>) {
// Unlike JVM, there is no reflection available to check component type
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,16 @@ actual class SavedStateHandle {
is ShortArray -> true

// Reference arrays
is Array<*> -> {
// Unlike JVM, there is no reflection available to check component type
when (value.firstOrNull()) {
is String,
is CharSequence -> true
// Narrowed alternative of Android's [putParcelableArray]
is Bundle -> true
else -> value.isEmpty()
}
}
// [bundleOf] might support [List] instead of [ArrayList] in some cases.
is List<*> -> {
// Unlike JVM, there is no reflection available to check component type
Expand Down