我怎么知道它是com.google.firebase.firestore.QuerySnapshot
的结尾?
(环境:Android studio 3.1.2)
nextFirestore()
方法是每次查询20个帖子。
showPosts()
方法将逐个显示查询帖子。
在第20篇文章中,showPosts()
将为用户提供对话
“继续或不”
如果用户回答“是”,则再次调用nextFirestore()
方法。
一切顺利,直到帖子结尾。 该应用程序将崩溃,它说:
E / AndroidRuntime:致命异常:主要 过程:com.google.appName,PID:27564 java.lang.ArrayIndexOutOfBoundsException:length = 0;指数= -1 at java.util.ArrayList.get(ArrayList.java:439) 在com.google.appName.Post $ 2.onEvent(Post.java:208) 在com.google.appName.Post $ 2.onEvent(Post.java:188) 在com.google.firebase.firestore.zzg.onEvent(未知来源:1789) 在com.google.firebase.firestore.g.zzh.zza上(SourceFile:28) 在com.google.firebase.firestore.g.zzi.run(未知来源:6) 在android.os.Handler.handleCallback(Handler.java:790) 在android.os.Handler.dispatchMessage(Handler.java:99) 在android.os.Looper.loop(Looper.java:164) 在android.app.ActivityThread.main(ActivityThread.java:6494) at java.lang.reflect.Method.invoke(Native Method) 在com.android.internal.os.RuntimeInit $ MethodAndArgsCaller.run(RuntimeInit.java:438) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
public void nextFirestore(DocumentSnapshot lastVisible)
{
CollectionReference questionRef = db.collection("posts");
mQuery = questionRef.startAfter(lastVisible)
.limit(20);
mRegistration = mQuery.addSnapshotListener(new EventListener<QuerySnapshot>()
{
@Override
public void onEvent(@Nullable QuerySnapshot value,
@Nullable FirebaseFirestoreException e)
{
if (e != null)
{
Log.w(TAG, "Listen failed.", e);
return;
}
List<Posts> realtimeList = new ArrayList<>();
for (DocumentSnapshot doc : value)
{
Posts post = doc.toObject(Posts.class);
assert post != null;
post.postId = doc.getId();
realtimeList.add(question);
}
DocumentSnapshot lastVisible = value.getDocuments().get(value.size() -1);
Log.d(TAG, "next last visible: " + lastVisible);
showPosts(realtimeList,lastVisible);
}
});
}
答案 0 :(得分:1)
看起来你应该在开始索引之前检查value.getDocuments()
返回的List的大小。如果它为零,请停止。