skip to Main Content

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


  1. Chosen as BEST ANSWER

    I did a little one change on Alex Mamo code .I don't know if its correct way, but it works for me.

    fun Greeting() {
    val cntx = LocalContext.current
    val mydb = Firebase.database
    val messages = remember { mutableStateListOf<Message>() } // 👈
    var authorText  by remember { mutableStateOf("") }
    var contentText  by remember { mutableStateOf("") }
    
    Column {
        Spacer(modifier = Modifier.height(5.dp))
        TextField(value = authorText, onValueChange = {authorText=it})
        TextField(value = contentText, onValueChange = {contentText=it})
        // ------------------------------------------------------------- Adding to List
        Button(onClick = {
            val myref = mydb.getReference("messages")
            var newRecord = Message(authorText,contentText)
            myref.push().setValue(newRecord)
                .addOnSuccessListener {
                    authorText=""
                    contentText=""
                    Toast.makeText(cntx,"successful", Toast.LENGTH_LONG).show() }
                .addOnFailureListener { Toast.makeText(cntx,"Error", Toast.LENGTH_LONG).show() }
        }) { Text(text = "Add") }
        // ------------------------------------------------ Click to show List
        Button(onClick = {
            val ref = mydb.getReference("messages")
            ref.get().addOnCompleteListener {
                if (it.isSuccessful) {
                    val snapshot = it.result
                    //  val messages = mutableListOf<CarClass>() 👈
                    for (messageSnapshot in snapshot.children) {
                        val message = messageSnapshot.getValue(Message::class.java)
                        messages.add(message!!)
                    }
    
    
                } else {
                    Toast.makeText(cntx,"Error", Toast.LENGTH_LONG).show()
    
                }
    
            }
    
        }) { Text(text = "Show List") }
        Spacer(modifier = Modifier.height(10.dp))
        // ------------------------------------------------- Showing List Here 
        LazyColumn {
            items(messages.reversed()){
                Row {
                    Text(text = it.author )
                    Spacer(modifier = Modifier.width(10.dp))
                    Text(text = it.content)
                }
    
            }
            messages.clear()
        }
    
    
    }
    

    }

    data class Message(var author:String="",var content:String="")


  2. 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:

    val db = Firebase.database.reference
    val messagesRef = db.child("messages")
    messagesRef.get().addOnCompleteListener {
        if (it.isSuccessful) {
            val snapshot = it.result
            for (messageSnapshot in snapshot.children) {
                val author = messageSnapshot.getValue(String::class.java)
                val content = messageSnapshot.getValue(String::class.java)
                Log.d(TAG, "$author/$content")
            }
        } else {
            Log.d(TAG, "${it.exception?.message}") //Never ignore potential errors!
        }
    }
    

    So as you can see, you have to create a reference that points to the messages node, call get(), and then iterate through all children to get the data. However, this solution will work only if the messages 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:

    val db = Firebase.database.reference
    val messagesRef = db.child("messages")
    messagesRef.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!!) //👈
            }
            Log.d(TAG, "${messages.size}") //👈
        } else {
            Log.d(TAG, "${it.exception?.message}") //Never ignore potential errors!
        }
    }
    

    The result in your logcat will be:

    2
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search