Issue
I have a liveData
in a ViewModel that return a list of object (mChannelList: MutableLiveData<List<Channels>> = MutableLiveData()
). I want to send this list to another activity using the putExtra
of Intent
. I make the code below, but when the code pass in startActivity
don´t go to the new activity (MainActivity
).
I put list of objects in Intent
corretly?
SplashScreenActivity.kt
(...)
splashScreenViewModel.getList()?.observe(this, Observer { it : List<Channels> ->
println("*********************** ${it}")
val intent = Intent(this, MainActivity::class.java)
intent.putExtra("EXTRA_PEOPLE", ArrayList(it))
startActivity(intent)
})
The data class:
data class Channels (
var Id: Int?,
var Title: String?,
var CallLetter: String?,
var ChannelPosition: Int?
)
MainActivity.kt
(...)
val bundle = intent.extras
val arr = this.intent.getParcelableArrayListExtra<Parcelable>("EXTRA_PEOPLE")
println("a lista : ${arr[0]}")
Solution
It is not recommended to pass a list of objects between your activities. As @IlyaMaier said, a more robust way is to initialize your ViewModel with your application context and then reuse the same LiveData in your MainActivity.
if you want to continue the same way, there are two reasons why your MainActivity is not being called.
- The observer is not being able to receive new data in your ViewModel Class.
- The data class should extend Pacelable & also add annotation @Parcelize.
Like this:
@Parcelize
data class Channels (
var Id: Int?,
var Title: String?,
var CallLetter: String?,
var ChannelPosition: Int?
) : Parcelable
Answered By - Bharath
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.