I'm having trouble setting up my ViewModel data for a chat interface i am building, I have a wide range of different types of data i want to show in a chat layout (RecyclerView). These include: Text,Buttons,Card view carousel...
I have set up a Sealed class which i am hoping will be able to contain all of the data classes needed to display this data, which looks like this atm:
sealed class ChatMessage {
abstract var msgTime: Long?
sealed class Text : ChatMessage() {
abstract val originator: String
abstract var content: String
data class Mine(
override val originator: String,
override var msgTime: Long?,
override var content: String
) : Text()
data class Agent(
override val originator: String,
override var msgTime: Long?,
override var content: String
) : Text()
}
sealed class Button : ChatMessage(){
abstract val title: String
abstract val actionText: String
data class General (
override var title: String,
override var actionText: String,
override var msgTime: Long?
) : Button()
}
}
In my adapter i am adding it to an arrayList for display:
var itemsOld: ArrayList<ChatMessage> = ArrayList()
And adding a new item to is as follows:
fun addNewMessage(model: ChatMessage.Text.Mine){
itemsOld.add(model)
itemsOld.sortBy { it.msgTime }
// mRecyclerView!!.smoothScrollToPosition(itemCount - 1)
MyApplication.appContext!!.runOnUiThread {
// Stuff that updates the UI
notifyDataSetChanged()
}
}
But i cannot access
itemsOld[0].content
or
itemsOld[0].originator
only
itemsOld[0].msgTime
How can i structure the Data classes so i have one parent class which can be implemented by the ArrayList and can hold all data classes i may need to display in the RecyclerView at the same time?
None of those fields are available in ChatMessage model. You need to either cast type to a specific data class or use a when() expression which will do the casting for you. Hope this helps, cheers!