0

I am trying to add all the IDs of documents from a collection "Tasks" in a list call list. There is no error message but the list keeps coming empty. To try to find the error, whether it was not connecting to firebase or if there was another error, I added a toast message to see this and it showed that the for loop was running and it was retrieving the data but the list was still empty. I can assure you there is nothing wrong with the adapter or the recycler view. I am able to write to the firebase. Here is my code

CollectionReference collectionReference = db.collection("Tasks");
collectionReference
    //.whereEqualTo("capital", true)
    .get()
    .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {

            if (task.isSuccessful()) {
                for (QueryDocumentSnapshot document : task.getResult()) {
                    String s = document.getId();
                    list.add(s);
                    Toast.makeText(TaskList.this, document.getId(), Toast.LENGTH_SHORT).show();
                }

            } else {

            }
        }
    });

mAdapter = new MyAdapter(list,this);
recyclerView.setAdapter(mAdapter);

Any help will be appreciated

pbaris
  • 4,525
  • 5
  • 37
  • 61

2 Answers2

0

Firebase sends asynchronous calls. Android does not have built-in functionality like await or something like that. So you have to set the data inside call success msg. If you try to read the data outside the call it won't work.

CollectionReference collectionReference = db.collection("Tasks");
collectionReference
    .get()
    .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
                for (QueryDocumentSnapshot document : task.getResult()) {
                    String s = document.getId();
                    list.add(s);
                    Toast.makeText(TaskList.this, document.getId(),Toast.LENGTH_SHORT).show();
                }
                
            mAdapter = new MyAdapter(list,this);
            recyclerView.setAdapter(mAdapter);
            mAdapter.notifyDataSetChanged();
            } else {
            }
        }
    });
Ashish
  • 6,791
  • 3
  • 26
  • 48
0

I think you can easily use Lambda expressions for a purpose you are looking for, as an example you can do something like this:

List<String> MovieNameList = new ArrayList<>();

List<MovieDTO> movieDTOList = new ArrayList<>();
movieDTOList = getSearchResultFromAPI(searchPhrase);

MovieNameList = movieDTOList.stream()  
                    .filter(x -> x.getName().contains(searchPhrase))
                    .map(MovieDTO::getName)  // == .map(x -> x.getName)
                    .collect(Collectors.toList());

I hope it helps you!

Sobhan
  • 1,280
  • 1
  • 18
  • 31