Home > Back-end >  Kotlin Cancels getParceableExtra call when passing data class using Intent
Kotlin Cancels getParceableExtra call when passing data class using Intent

Time:01-05

Trying to pass a data class User from one Activity to another using Intent.

My putExtra looks like this using my observe fun:

val intent = Intent(this, MainActivity::class.java)
            intent.putExtra("userData",userData)
            startActivity(intent)

My get routine looks like this:

userData = intent.getParcelableExtra<User>("userData") as User

or

userData = intent.getParcelableExtra("userData")

My problem is that Android Studio strikes out the function. My User data class is marked @Parcelize. It all ends up getParcelableExtra.

I've add to my gradle build:

id 'kotlin-parcelize'

I've read several posts about Parcelable being more modern than Serialable, so that's the technique I'm using. All the posts are from 2018 or prior and many of them in Java.

How does one send an data class from one Activity to another using Intent?

CodePudding user response:

SOLUTION:

Given the need for compiler version 33 for the most modern solution, I went with a more backward compatible solution. This code translates the data object into a string, then back into the object.

SETUP: (PUT)

private var _userData = MutableLiveData<User>() // does the username and pw validate?
val userData : LiveData<User>
    get() = _userData

SETUP: (GET)

private lateinit var userData: User

PUT CODE:

    val intent = Intent(this, MainActivity::class.java)
    val jsonUserData = Gson().toJson(userData)
    intent.putExtra("userData",jsonUserData)

GET CODE:

val jsonUserData = intent.getStringExtra("userData")
        userData = Gson().fromJson(jsonUserData, User::class.java)

CodePudding user response:

Since getParcelableExtra (String name) is deprecated from api level 33 you can use getParcelableExtra (String name, Class<T> clazz) from api level 33

In Your case use :

val userData =
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        intent.getParcelableExtra("userData", userData::class.java)
    }
    else{
        intent.getParcelableExtra("userData") as userData?
    }

where TIRAMISU is constant value 33

To get more info:Read this: https://developer.android.com/reference/android/content/Intent#getParcelableExtra(java.lang.String, java.lang.Class)

  • Related