Google Firestore 分页查询

今天在使用Firestore实现分页查询的功能时,遇到了一个问题:

《Google Firestore 分页查询》 异常截图

定位到这一行

《Google Firestore 分页查询》 定位代码

然而我是完全照着官方的文档写的,唯一区别就是它用的addOnSuccessListener而我是addOnCompleteListener

那就打印一下类型

FirebaseFirestore.getInstance()
    .collection("record")
    .orderBy("date", Direction.DESCENDING)
    .limit(PAGE_SIZE)
    .get()
    .addOnCompleteListener {
        select_record_srl.finishLoadMore()
        if (it.isSuccessful) {
            val result = it.result.toObjects(Record::class.java)
            lastVisible = if (result.size == 0) {
                //无数据
                null
            } else {
                recordAdapter.addData(result)
                it.result.documents[result.lastIndex]
            }
            println(lastVisible?.javaClass) //打印类型
            select_record_srl.isEnableLoadMore = result.size >= PAGE_SIZE
        } else {
            Log.w("Firebase", "Error querying record", it.exception)
            ToastUtils.showShort(R.string.toast_query_record_fail)
        }
    }
class com.google.firebase.firestore.QueryDocumentSnapshot

执行上面的代码,打印lastVisible的类型,发现是QueryDocumentSnapshot,而它继承于DocumentSnapshot,所以才会报出之前的类型错误

目前本人的解决方法比较简单,直接类型强转为DocumentSnapshot

FirebaseFirestore.getInstance()
                .collection("record")
                .orderBy("date", Direction.DESCENDING)
                .startAfter(lastVisible as DocumentSnapshot)
                .limit(PAGE_SIZE)
                .get()
                ...

官方文档也没有对此进行说明,对它背后实现的源码也不清楚,有了解的大神可以解答一下。

    原文作者:AlexZwh
    原文地址: https://www.jianshu.com/p/560a0b990263
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞