Android getParcelableExtra deprecated

Viewed 2199

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")
4 Answers

Here are two extension methods that I use for Bundle & Intent:

inline fun <reified T : Parcelable> Intent.parcelable(key: String): T? = when {
  SDK_INT >= 33 -> getParcelableExtra(key, T::class.java)
  else -> @Suppress("DEPRECATION") getParcelableExtra(key) as? T
}

inline fun <reified T : Parcelable> Bundle.parcelable(key: String): T? = when {
  SDK_INT >= 33 -> getParcelable(key, T::class.java)
  else -> @Suppress("DEPRECATION") getParcelable(key) as? T
}

I also requested this to be added to the support library

And if you need the ArrayList support there is:

inline fun <reified T : Parcelable> Bundle.parcelableArrayList(key: String): ArrayList<T>? = when {
  SDK_INT >= 33 -> getParcelableArrayList(key, T::class.java)
  else -> @Suppress("DEPRECATION") getParcelableArrayList(key)
}

inline fun <reified T : Parcelable> Intent.parcelableArrayList(key: String): ArrayList<T>? = when {
  SDK_INT >= 33 -> getParcelableArrayListExtra(key, T::class.java)
  else -> @Suppress("DEPRECATION") getParcelableArrayListExtra(key)
}

Now we need to use getParcelableExtra() with the type-safer class added to API 33

SAMPLE CODE For kotlin

val userData = if (VERSION.SDK_INT >= 33) {
  intent.getParcelableExtra("DATA", User::class.java)
} else {
  intent.getParcelableExtra<User>("DATA")
}

SAMPLE CODE For JAVA

if (android.os.Build.VERSION.SDK_INT >= 33) {
  user = getIntent().getParcelableExtra("data", User.class);
} else {
  user = getIntent().getParcelableExtra("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 = intent.getParcelableExtra (String name, Class<T> clazz)
}else{
    data = intent.getParcelableExtra("data")
}

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);
}

This still requires @SuppressWarnings({"deprecation", "RedundantSuppression"}).

Related