I’d like to implement RecyclerView, along with Firebase to my app. I have a simple structure of the firebase:
The keys, under the Message node, are randomly generated by using .push() on reference. The values are just some dummy messages.
Model
data class Message (val message: String? = null)
MainActivity
private lateinit var mAdapter: MessageAdapter
...
myRef = FirebaseDatabase.getInstance().getReference("Message")
//Set database query
val messages = FirebaseRecyclerOptions.Builder<Message>()
.setQuery(myRef, Message::class.java)
.build()
mAdapter = MessageAdapter(messages)
//Read data
val rv = findViewById<RecyclerView>(R.id.messages_rv)
rv.layoutManager = LinearLayoutManager(this)
rv.adapter = mAdapter
Adapter
class MessageAdapter(messages: FirebaseRecyclerOptions<Message>) :
FirebaseRecyclerAdapter<Message, MessageAdapter.ViewHolder>(messages) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.message_row, parent, false)
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int, model: Message) {
holder.message.text = model.message
}
// Make a textview variable, and initiate it in the init block, which will be called first after creating the ViewHolder object
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val message: TextView = view.findViewById(R.id.message_tv)
}
}
Unfortunately, my app crash with this error:
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.myapplication.Message
I’ve tried to make a different references to the database, but none of them work. How I may solve it?
>Solution :
When you’re using the following reference:
myRef = FirebaseDatabase.getInstance().getReference("Message")
And you pass it to the setQuery() method:
.setQuery(myRef, Message::class.java)
Your adapter expects to render on the screen Message objects. However, under the Message node, there are no such objects but only strings. If you want to map a node into an object of type Message, then you should consider using a schema that looks like this:
db
|
--- Message
|
--- $pushedId
| |
| --- message: "asd"
|
--- $pushedId
|
--- message: "asd13"
This means that the actual message should exist under a pushed ID.
