Home > Net >  How can get rid of the multiply Intents
How can get rid of the multiply Intents

Time:08-12

I have 2 activities. And I need pass a lot of variables from one activity to another activity:

val intent = Intent(this, SecondActivity::class.java)
            intent.putExtra(ACCOUNT1, accoun1)
            intent.putExtra(ACCOUNT2, accoun2)
            intent.putExtra(ACCOUNT3, accoun3)
            intent.putExtra(ACCOUNT4, accoun4)
            intent.putExtra(ACCOUNT5, accoun5)
            intent.putExtra(ACCOUNT6, accoun6)
            intent.putExtra(ACCOUNT7, accoun7)
            intent.putExtra(ACCOUNT8, accoun8)
            intent.putExtra(ACCOUNT9, accoun9)
       

and so on. How can I make this transfer easier? Maybe is some other ways to pass multiply values from one activity to another activity?

CodePudding user response:

I recently had a similar case.

How I solved:

I created an entity that kept all the information for me, that way, I just passed an object between activities, but I had everything I needed inside that object.

Hope this can help.

CodePudding user response:

There is a bundleOf function in the Jetpack core-ktx library that works like mapOf.

val intent = Intent(this, SecondActivity::class.java)
val extras = bundleOf(
    ACCOUNT1 to accoun1,
    ACCOUNT2 to accoun2,
    ACCOUNT3 to accoun3,
    // etc.
)
intent.putExtras(extras)

But that doesn't save much code compared to just using apply unless you use the same bundle of extras in multiple places in your code:

val intent = Intent(this, SecondActivity::class.java).apply {
    putExtra(ACCOUNT1, accoun1)
    putExtra(ACCOUNT2, accoun2)
    putExtra(ACCOUNT3, accoun3)
    //...
}

You could make a parcelable data class that stores all your values and pass that instead. See instructions here for creating the class easily: https://developer.android.com/kotlin/parcelize

@Parcelize
data class AccountInfo(
    val account1: String,
    val account2: String,
    val account3: String,
    //...
): Parcelable

Then you can put this into your bundles, and you don't have to create a bunch of the same kinds of variables in both activities, because all the variables are inside one class.

val intent = Intent(this, SecondActivity::class.java).apply {
    putExtra(ACCOUNT_INFO, myAccountInfoInstance)
}
  • Related