在firebase中,onDataChange()函数被多次调用,经过一些搜索,我发现它将被称为监听器连接的次数。但是我已经多次附加了监听器,因为我需要不同的查询并获取不同类型的数据库。我怎样才能解决这个问题。我已经使用了addValueEventListener 9次来检索或排序存储在数据库中不同节点的不同数据。获取数据的适当方法是什么。任何帮助,将不胜感激。这是我使用过代码的一些地方。
firebaseUrl.addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
String temp, temp1;
Log.e(TAG, "onDataChange: mytime " + dataSnapshot.getValue());
long timeStampLong = (long) dataSnapshot.child("time").child("timestamp").getValue();
SimpleDateFormat sfd = new SimpleDateFormat("HH:mm:ss");
temp1 = sfd.format(new Date(timeStampLong));
try {
if (isTimeBetweenTwoTime("08:00:00", "20:00:00", temp1)) {
//do something
}
} catch (ParseException e) {
e.printStackTrace();
}
}
public void onCancelled(DatabaseError databaseError) {
}
});
firebaseUrl.child("time").child("timestamp").setValue(ServerValue.TIMESTAMP);
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
String temp1;
long timeStampLong = (long) dataSnapshot.child("time").child("timestamp").getValue();
SimpleDateFormat sfd1 = new SimpleDateFormat("HH:mm:ss");
temp1 = sfd1.format(new Date(timeStampLong));
onClickShowAnswerButton(temp1);
}
public void onCancelled(DatabaseError databaseError) {
}
});
public void onClickShowAnswerButton(String time) {
try {
if (isTimeBetweenTwoTime("08:00:00", "20:00:00", time)) {
showDialogBox("Today's Answer", "The answer can be seen in between 8 PM to 8 AM only");
} else {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String correctAnswerString, yourAnswerString;
String title;
correctAnswerString = dataSnapshot.child("questions").child(imagename).child("correctAnswer").getValue(String.class);
yourAnswerString = dataSnapshot.child("users").child(uid).child("questions").child(imagename).child("yourAnswer").getValue(String.class);
if (correctAnswerString.equals(yourAnswerString))
title = "CorrectAnswer: " + correctAnswerString + "\nCongratulations your answer answer is correct ";
else if (yourAnswerString == null)
title = "Answer: " + correctAnswerString + "\nYou haven't answered the question";
else
title = "Answer: " + correctAnswerString + "\nYour Answer: " + yourAnswerString + "\nSorry your answer is incorrect";
showDialogBox("Today's Answer", title);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
} catch (ParseException e) {
e.printStackTrace();
}
}
答案 0 :(得分:0)
IMO你应该做的是连接一次监听器,然后通过缓存或持久存储使这些数据可用于其他方法。您可以创建一个在更新firebase时更新的数据对象,并可能使用数据绑定之类的东西来更新UI。但是你需要附加一个监听器,尽管有多少其他地方需要数据。您可以随时获取数据。