-1

Since getParcelable is deprecated for Android Tiramisu and later i want to make an extension function to get the parcelables from my Intent through my Bundle

So i have

            val server = if (Build.VERSION.SDK_INT >= 33) {
                it.getParcelable("server", Server::class.java)
            } else {
                it.getParcelable("server")
            }

And i want to create an extension for every model like this

fun <T> T.getParcelable(bundle: Bundle, key: String): T? = 
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
        bundle.getParcelable(key, this!!::class.java)
    else
        bundle.getParcelable(key)

However, when i try to use it i get an unresolved reference error enter image description here

How can i fix that?

0

2 Answers 2

2

Something like this?

inline fun <reified T : Any> KClass<T>.getParcelable(bundle: Bundle, key: String): T? =
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
        bundle.getParcelable(key, T::class.java)
    else
        bundle.getParcelable(key)

And you use it like this

val server = Server::class.getParcelable(bundle, "server")
Sign up to request clarification or add additional context in comments.

2 Comments

Nope. Plenty of errors..! Have you tried it?
I edited my original post @james04
1

Extension functions are actually static methods on initialised variables & not exactly on classes. That's why it isn't working.

What you can do is:

  1. You can either make your Server an object.
  2. Add a blank companion object { } to your Server class & use the below extension function.
fun <T> T.getParcelable(bundle: Bundle, key: String): T? {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        bundle.getParcelable(key, this!!::class.java)
    } else bundle.getParcelable(key)
}

Example usage:

intent?.extras?.let { bundle ->
    val server = Server.getParcelable(bundle, "server")
}

Edit: Alternatively, the below can also be done which is a better option:
val server = Server::class.getParcelable(bundle, "server")

1 Comment

Your answer seems correct, however i wouldn't like to do this to all my models.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.