I am passing data via intent with Parcelable and receiving using getParcelableExtra. However getParcelableExtra seems to be deprecated, How do I fix the deprecation warning in this code? Alternatively, are there any other options for doing this? . I am using compileSdkVersion 33.
Code snippet:
var data = intent.getParcelableExtra("data")
Now we need to use getParcelableExtra()
with the type-safer class added to API 33
SAMPLE CODE
val userData = if (VERSION.SDK_INT >= 33) {
intent.getParcelableExtra("DATA", User::class.java)
} else {
intent.getParcelableExtra<User>("DATA")
}
As described in the official documentation , getParcelableExtra
was deprecated in API level 33.
So check if the API LEVEL is >= 33 or change the method,
...
if (Build.VERSION.SDK_INT >= 33) {
data = getParcelableExtra (String name, Class<T> clazz)
}else{
data = intent.getParcelableExtra("data")
}
Here are two extension methods that I use for Bundle
& Intent
:
private inline fun <reified T> Intent.parcelable(key: String, clazz: Class<T>): T? = when {
SDK_INT >= 33 -> getParcelableExtra(key, clazz)
else -> @Suppress("DEPRECATION") getParcelableExtra(key) as? T
}
private inline fun <reified T> Bundle.parcelable(key: String, clazz: Class<T>): T? = when {
SDK_INT >= 33 -> getParcelable(key, clazz)
else -> @Suppress("DEPRECATION") getParcelable(key) as? T
}
For example, in Java:
UsbDevice device;
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.S_V2) {
device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE, UsbDevice.class);
} else {
device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
}
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.