I am working on an Android project and have a button that inserts data into the Realtime Database child and it’s working fine. but now i need to get that data as a list and append it to listof to be able then to display it in a lazyColumn.
here are images from Firebase and Kotlin files
have seen many ways to add data but couldn’t find any solution about how to get data as a list.
here is my last code update :
when i click display, my app get crush. could you please check what’s missing here
fun Greeting() {
val mydb = Firebase.database.reference
var authorText by remember { mutableStateOf("") }
var contentText by remember { mutableStateOf("") }
var myList = mutableListOf<Message>()
Column(modifier = Modifier.fillMaxSize()) {
TextField(value = authorText, onValueChange = {authorText=it})
TextField(value = contentText, onValueChange = {contentText=it})
Button(onClick = {
val message = Message(authorText,contentText)
mydb.child("messages").push().setValue(message) }) {
Text(text = "insert")
}
Button(onClick = {
val rf = mydb.child("messages")
rf.get().addOnCompleteListener {
if (it.isSuccessful) {
val snapshot = it.result
val messages = mutableListOf<Message>()
for (messageSnapshot in snapshot.children) {
val message = messageSnapshot.getValue(Message::class.java)
messages.add(message!!)
}
myList=messages
} else {
Log.d(TAG, "${it.exception?.message}") //Never ignore potential errors!
}
}
}) { Text(text = "display")
}
LazyColumn {
items(myList){
Row {
Text(text = it.author)
Spacer(modifier = Modifier.width(2.dp))
Text(text = it.content)
}
}
}
}
}
data class Message(var author:String,var content:String)
2
Answers
I did a little one change on Alex Mamo code .I don't know if its correct way, but it works for me.
}
data class Message(var author:String="",var content:String="")
Because you said in the last comment that you’re looking for a solution to read the data under the
messages
node on Android, then please check the below solution using Kotlin:So as you can see, you have to create a reference that points to the
messages
node, callget()
, and then iterate through all children to get the data. However, this solution will work only if themessages
node is a direct child of your root reference.Or if you already have a clas called
Message
and you want to create a list of messages, then you can use:The result in your logcat will be: