0

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());
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • At which line of code are you getting NPE? – Alex Mamo Jan 12 '20 at 04:54
  • So, the big chunk of code is the method that is supposed to retreve data from Firestore and store it in the List called list, which is a global variable. But when I try to use the list, in the separated line of code ( **viewHolder.title.setText(list.get(position).getTheTitle());** ), i get NPE on list**.get(position)** method – Sebastian Mocanu Jan 12 '20 at 12:07
  • Firebase APIs are asynchronous. So please check the duplicate to see why do you have this behavior and how can you solve this using a custom callback. – Alex Mamo Jan 13 '20 at 08:23

0 Answers0