Home > Software engineering >  Passing generic typed object between activities via intent
Passing generic typed object between activities via intent

Time:04-06

In my application I am trying to pass a generic worker object (which is parcelable) between activities. However, when I get parcelableExtra from intent, it creates new instance of the worker.

As you can see from the code, I assigned test variable to 10 then put it to bundle, when get it from new activity, it gives 15 as default value.

Is there a way to pass same instance reference between activities?

Put worker to intent:

fun newIntent(context: Context, worker: PlayerVideoContentsWorker, position: Int): Intent {
            val intent = Intent(context, PlayerVideoContentsActivity::class.java)
            worker.test = 10
            intent.putExtra(WORKER, worker)
            intent.putExtra(POSITION, position)
            return intent
        }

get worker from intent

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    val worker = intent.getParcelableExtra<PlayerVideoContentsWorker>(WORKER)
    print(worker?.test) //prints 15
    ...

PlayerVideoContentsWorker.kt

@Parcelize
class PlayerVideoContentsWorker(val service: PlayerPaginatableListService<VideoContent, CursorPagination>,
                                val paginationInfo: CursorPaginationInfo)
    : PlayerPaginatableListWorker<VideoContent, CursorPagination>(service, paginationInfo), Parcelable

PlayerPaginatableListWorker

open class PlayerPaginatableListWorker<T : Parcelable, P : IPaginationData>(
        private val service: PlayerPaginatableListService<T, P>,
        private val paginationInfo: CommonPaginationInfo<P>) {
    var test = 15
    ...

CodePudding user response:

You can't make a class Parcelable by just putting @Parcelize above it. @Parcelize is a conventient plugin for making a class Parcelable but the class needs to have certain requirements.

As stated in the documentation:

@Parcelize requires all serialized properties to be declared in the primary constructor

This is not the case for test

Furthermore, the parameters are not of the types listed at the Supported types section there.

CodePudding user response:

However, when I get parcelableExtra from intent, it creates new instance of the worker.

Correct. That is how Intent extras work. Parcelable is a serialization mechanism — think of it as being akin to passing JSON around.

Is there a way to pass same instance reference between activities?

No. Have just one activity, with separate screens implemented via fragments or composables.

  • Related