How can I know it's the end of com.google.firebase.firestore.QuerySnapshot
?
(environment: Android studio 3.1.2)
The nextFirestore()
method is to query 20 posts every time.
showPosts()
method will show the query posts one by one.
At the 20th post, showPosts()
will give user a dialogue
"continue or not"
If user answer yes, then call nextFirestore()
method again.
Everything went well until at the end of posts. the app will crash, it said:
E/AndroidRuntime: FATAL EXCEPTION: main Process: com.google.appName, PID: 27564 java.lang.ArrayIndexOutOfBoundsException: length=0; index=-1 at java.util.ArrayList.get(ArrayList.java:439) at com.google.appName.Post$2.onEvent(Post.java:208) at com.google.appName.Post$2.onEvent(Post.java:188) at com.google.firebase.firestore.zzg.onEvent(Unknown Source:1789) at com.google.firebase.firestore.g.zzh.zza(SourceFile:28) at com.google.firebase.firestore.g.zzi.run(Unknown Source:6) at android.os.Handler.handleCallback(Handler.java:790) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6494) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) at 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);
}
});
}