【发布时间】:2019-09-11 02:38:14
【问题描述】:
我的问题是,在结束我的主要方法之前,我需要等待通过方法“onDataChange”检索来自 Firebase 的数据。
我的代码是(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;
}
如您所见,我已经在尝试使用 CountDownLatch 等待,但它不起作用:卡住了。
我需要活动“CalendarActivity”的listDays,我像这样使用它:
//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();
}
【问题讨论】:
-
你试过Handler了吗?后延迟方法??
-
你的 Handler 是什么意思?而且我也从未听说过后延迟方法:c
-
您希望在一段时间后调用方法 db.addValueEventListener() 对吗??
-
不是真的,确实我想等待 onDataChange() 方法完成检索数据,然后返回 listDays,因为如果不等待,返回的 listDays 为 null
-
现在我遇到了你的问题。听着,数据是从 Firebase 异步加载的。你需要了解那件事。
标签: android firebase firebase-realtime-database