Home > Blockchain >  What should I do to print only the last data entered in Text?
What should I do to print only the last data entered in Text?

Time:12-28

   private fun getData(){
    firestore.collection("Posts").addSnapshotListener { value, error ->

        if (error!=null){
            Toast.makeText(requireContext(),error.localizedMessage,Toast.LENGTH_SHORT).show()
        }else{
            if (value !=null){
                if (!value.isEmpty){
                    val documents = value.documents
                    for (document in documents){
                        val pc = document.get("Panel Sayisi") as String
                        val ps = document.get("Panel Boyutu") as String
                        val ls = document.get("Arazi Eğimi") as String
                        val lsi = document.get("Arazi Boyutu") as String
                        val c = document.get("Şehir") as String

                        val post = Post(pc,ps,ls,lsi,c)
                        postArrayList.add(post)
                    }
                }
            }
        }
        val db = FirebaseFirestore.getInstance()
        db.collection("Posts").orderBy("Panel Sayisi",Query.Direction.DESCENDING).limit(1)
            .get()
            .addOnCompleteListener {

                val result : StringBuffer = StringBuffer()
                if (it.isSuccessful){
                    for (document in it.result){
                        result.append(document.data.getValue("Panel Sayisi"))
                    }
                    verimText.setText(result)
                }
            }
    }
}

It shows all the data I have added to Cloud Firestore that has the keyword "Panel Sayisi" in verimText. I only want the last data entered to be displayed.

Here is the problem. The last file I added is added in the middle. That's why the value I call last or the first call doesn't change. So it always calls the same value. This middle value should be written at the end or at the beginning. So I can get this data by calling ASCENDING or DESCENDING method.

CodePudding user response:

When you are using the following call to:

.orderBy("Panel Sayisi",Query.Direction.DESCENDING)

It means that are only ordering the documents according to the "Panel Sayisi" field, which doesn't actually solve the problem. The problem is that you don't know that the "c4Q5...q4vP" document is the last document that was added. To solve this issue, you have to add an additional field of type Firestore Timestamp, as explained in my answer from the following post:

And then use the following query:

val db = FirebaseFirestore.getInstance()
val query = db.collection("Posts").orderBy("timestamp", Query.Direction.DESCENDING).limit(1)
  • Related