I am working on an Android app and I use Firestore to store my Users and their Posts. I want to display posts from Firestore on my feed in a RecyclerView. I use to query and pagination so only 10 posts will be retrieved every time I scroll the RecyclerView to its end. I want the retrieved posts to be stored in a List and this is how I tried:
private void postsRetriever(){
FirebaseFirestore db = FirebaseFirestore.getInstance();
Query first = db.collection("users").document(FirebaseAuth.getInstance().getCurrentUser().getUid().toString()).collection("posts").limit(10);
first.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot documentSnapshots) {
DocumentSnapshot lastVisible = documentSnapshots.getDocuments()
.get(documentSnapshots.size() -1);
Query next = db.collection("users").document(FirebaseAuth.getInstance().getCurrentUser().toString()).collection("posts")
.startAfter(lastVisible)
.limit(10);
next.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
for(DocumentSnapshot documentSnapshot:task.getResult()) {
Post post = documentSnapshot.toObject(Post.class);
list.add(post);
}
}
});
}
});
}
The problem is everytime I try to use the List, I get NullPointerException on list.get(pos).. :
viewHolder.title.setText(list.get(position).getTheTitle());