如何使用Firestore在Kotlin中分页数据?

时间:2018-09-20 05:31:59

标签: android firebase kotlin google-cloud-firestore

我创建了从Firestore提取数据的适配器。 但是我需要用Kotlin进行分页,您能帮我吗?

enter image description here

private fun fetch(){
            try {
                mShared = getSharedPreferences("mShared", 0)
                val path = mShared!!.getString("governorate", "Suez").toString()
                dp!!.collection("Fraise")
                        .whereEqualTo("governorate", "${path}")
                        .orderBy("time")
                        .limit(5)
                        .get()
                        .addOnCompleteListener {
                            data.addAll(it.result.toObjects(Data::class.java))
                            adapter = Fraise_adapter(this, data)
                            adapter.notifyDataSetChanged()
                            recyclerView.adapter = adapter
                        }
            } catch (e: Exception) {
                Toast.makeText(this, "Please choose a governorate from the main activity", Toast.LENGTH_LONG).show()
            }
        }

1 个答案:

答案 0 :(得分:1)

这对我有用。用于 Firestore 分页。

private fun first(){

          val first = collectionRef
                .orderBy("priority")
                .limit(3)

        first.get()
            .addOnSuccessListener {

                    var  lastVisible = it.documents[it.size()-1]
                var text = ""
                for (document in it) {
                    val note = document.toObject(Note::class.java)
                    note.noteId = document.id
                    text+= note.title+"\n"

                }
                binding.tvShow.append(text)

                binding.btnShow.setOnClickListener {

                    val  next = collectionRef
                        .orderBy("priority")
                        .startAfter(lastVisible)
                        .limit(3)

                    next.get()
                        .addOnSuccessListener {
                            var text = ""
                            for (document in it) {
                                val note = document.toObject(Note::class.java)
                                note.noteId = document.id
                                text+= note.title+"\n"
                            }

                            if(it.size()>0) {
                                text += "--------------------------\n\n"
                                binding.tvShow.append(text)
                                lastVisible = it.documents[it.size()-1]
                            }
                        }
                }
            }
            .addOnFailureListener {
                Toast.makeText(this, "Failed", Toast.LENGTH_SHORT).show()
                Log.d(TAG, it.message)
            }
    }