My problem is that I need to wait for the data from Firebase to be retrieved on the method "onDataChange" before ending my main method.
My code is (CalendarDbHelper) :
public synchronized ArrayList<Day> listDays()
{
final CountDownLatch done = new CountDownLatch(1);
db.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists())
{
for(DataSnapshot postSnapShot:dataSnapshot.getChildren())
{
Day day=postSnapShot.getValue(Day.class);
listDays.add(day);
}
}
done.countDown();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
try {
done.await();
} catch(InterruptedException e) {
e.printStackTrace();
}
return listDays;
}
As you can see, I'm already trying to wait with a CountDownLatch, but it doesn't work : it gets stuck.
I need the listDays for the activity "CalendarActivity" where I use it like this :
//Real initialization of the database
db = FirebaseDatabase.getInstance().getReference();
mDatabase = new CalendarDbHelper(db);
final List<Day> allDays = mDatabase.listDays();
//Activating things to click on
if(allDays.size() > 0){
calendarRV.setVisibility(View.VISIBLE);
calendarRVAdapter = new CalendarAdapter(this, allDays, new CalendarAdapter.OnListItemClickListener() {
@Override
public void onListItemClick(int clickedItemIndex) {
String id = allDays.get(clickedItemIndex).getId();
MyCustomAlertDialog(id);
}
});
calendarRV.setAdapter(calendarRVAdapter);
}else {
calendarRV.setVisibility(View.GONE);
Toast.makeText(this, "There is no product in the database. Start adding now", Toast.LENGTH_LONG).show();
}