2

I need a function to get all data/notes from FirebaseFirestore. How do I make this function wait for all data before return?

I think this function I created is not working in the main thread and return before getting data from firebase

    public static ArrayList<NoteFB> getNotes() {

        FirebaseFirestore db = FirebaseFirestore.getInstance();
        final String TAG = "FB Adapter";

        final ArrayList<NoteFB> doFBs = new ArrayList<>();
        db.collection("notesItem")
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            for (QueryDocumentSnapshot document : task.getResult()) {
                                Log.d(TAG, document.getId() + " => " + document.getData());
                                doFBs.add(document.toObject(NoteFB.class));
                            }
                        } else {
                            Log.w(TAG, "Error getting documents.", task.getException());
                        }
                    }
                });

        return doFBs;
    }

        MyFBAdapter myFBAdapter = new MyFBAdapter(ShowActivity.this, FBAdapter.getNotes());

        rvContacts.setAdapter(myFBAdapter);

This code returns an empty ArrayList that creates an empty recyclerview.

  • Hi. It looks like this code comes from a larger application; for example, what is the context of the call to `getNotes()`? I suggest reviewing the advice on to make a [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). Your question is also difficult to understand due to the way it is written. – Scott McPeak Sep 05 '19 at 20:42
  • hi @ScottMcPeak thanks for comment.. i try to make todo/notes application, it's insert and get data from firebase, i try to make firebase adapter like sqlite adapter but its with static functions were can use it in any place, when i call getNotes() function its return empty arraylist, i traced the code, i found the data come after return statement List from getNote() 23:43:56.028 the data from firebase 23:43:58.834 , how can i make function wait the all data before return. – Ahmed Fayez Sep 05 '19 at 21:02

2 Answers2

1

Lots of these questions popping up lately. I had found the solution a while back : Using the Tasks API.

public static ArrayList<NoteFB> getNotes() {

    FirebaseFirestore db = FirebaseFirestore.getInstance();
    final String TAG = "FB Adapter";

    final ArrayList<NoteFB> doFBs = new ArrayList<>();

    try {
        Task<QuerySnapshot> taskResult = Tasks.await(db.collection("notesItem").get(), 2, TimeUnit.SECONDS)
        for (QueryDocumentSnapshot document : task.getResult()) {
            Log.d(TAG, document.getId() + " => " + document.getData());
            doFBs.add(document.toObject(NoteFB.class));
         }

    } catch(Exception e) {
         Log.w(TAG, "Error getting documents.", e.localizedString());
    }
    return doFBs
}

Forgive me if I made any syntax errors my Java is a little rusty.

Make sure you are calling this code OFF the main thread, otherwise it will crash.

Sean Blahovici
  • 5,350
  • 4
  • 28
  • 38
0

You can use interface for this

public interface NoteDataInterface {
        void onCompleted(ArrayList<NoteFB> listNotes);
    }

Change your method to use interface:

 public static void getNotes(NoteDataInterface noteDataInterface) {

        FirebaseFirestore db = FirebaseFirestore.getInstance();
        final String TAG = "FB Adapter";

        final ArrayList<NoteFB> doFBs = new ArrayList<>();
        db.collection("notesItem")
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            for (QueryDocumentSnapshot document : task.getResult()) {
                                Log.d(TAG, document.getId() + " => " + document.getData());
                                doFBs.add(document.toObject(NoteFB.class));
                            }
                        } else {
                            Log.w(TAG, "Error getting documents.", task.getException());
                        }
                       noteDataInterface.onCompleted(doFBs);
                    }
                });


    }

Then call your method :

 getNoteData(new NoteDataInterface() {
            @Override
            public void onCompleted(ArrayList<NoteFB> listNotes) {
                Log.e("listNotes>>",listNotes.size()+"");
            }
        });
Jignesh Mayani
  • 6,937
  • 1
  • 20
  • 36