0

I am performing multiple times of filter to the data in Firebase Realtime Database. For example, I first filter for people less than age 20, if the result count is less than 50, I will need to re-visit the database to filter again for people less than age 30, etc... Hence, I need to use addChildEventListener multiple times.

The list of people who are selected will then be displayed in a RecyclerView.

I do that using this:

adapter = new Adapter(this, getListFromFirebase());
view= findViewById(R.id.my_view);
view.setLayoutManager(manager);
view.setAdapter(adapter);

Where getListFromFirebase() is a function that use addChildEventListener to get data from Firebase Realtime Database.

However, since Firebase Realtime Database is asynchronous, it always returns an empty list to the RecyclerView when the RecyclerView is initialized. Is there any way that I can make sure that I can successfully get the list that I want from Firebase Realtime Database before entering the RecyclerView?

Grimthorr
  • 6,856
  • 5
  • 41
  • 53
mumu
  • 3
  • 2
  • 4
  • Take a look at this answer:https://stackoverflow.com/questions/53293212/cant-get-the-return-value-from-a-method-that-retrieves-data-from-firebase-realt/53293407#53293407 – PradyumanDixit Nov 15 '18 at 09:40
  • Please check the duplicate to see why do you have this behaviour and how can you solve this using a custom callback. – Alex Mamo Nov 15 '18 at 12:19

1 Answers1

0

Your method getListFromFirebase() will always return null, because of the firebase async task. Instead create a new method where you notifyAdapter, which you can call from onChildAdded method.

Try this,

Declare a variable:

ArrayList<YourModel> list = new ArrayList<>();

Pass it to adapter even if it is empty:

adapter = new Adapter(this, list);
view= findViewById(R.id.my_view);
view.setLayoutManager(manager);
view.setAdapter(adapter);
getListFromFirebase(); // Dont return anything from this method. declare it void


void getListFromFirebase(){
  //firebaselistener task
   onChildAdded(){

     YourModel yourModel = dataSnapshot.getValue();
     mAdapter.addNewData(yourModel); //create a new method to update recyclerview Adapter
   }
}

Adapter:

void addNewData(YourModel newData){
  list.add(newData);  //assign the list value to adapter list
  notifyAdapterChange();
}
ManishPrajapati
  • 459
  • 1
  • 5
  • 16
  • Thanks for your help! However, it still doesnt show anything in the recycler view. Can I know why? Is there anything I missed out? – mumu Nov 16 '18 at 06:05
  • try to print yourModel data in your addNewData method to check whether your data is getting passed. I have also updated the code, try again and let us know. – ManishPrajapati Nov 16 '18 at 06:31