如果我的数据库发生更改,总是会显示旧值和新值。我如何删除旧的而只显示新的。这是我的代码:
private void downloadAccepted(final String plz) {
String userid =
FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users").child(userid).child("acceptedEvents");
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
downloadAcceptedDetails(plz, snapshot.getKey().toString());
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void downloadAcceptedDetails(final String plz, final String id){
DatabaseReference refi = FirebaseDatabase.getInstance().getReference().child("Events").child(plz).child(id);
refi.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Long millis = new Date().getTime();
if (dataSnapshot.getChildrenCount() > 0 ) {
if (Long.parseLong(dataSnapshot.child("ts").getValue().toString()) > millis) {
EventObject eo = new EventObject(dataSnapshot.child("ts").getValue().toString(), dataSnapshot.child("name").getValue().toString(), dataSnapshot.child("street").getValue().toString(), dataSnapshot.child("plz").getValue().toString());
accepted.add(eo);
try{
((globalVariable) getActivity().getApplication()).setAdapter2(adapter2);
}catch (Exception e){
}
adapter2.notifyDataSetChanged();
} else {
removeValuesMyIdeas( plz, id);
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
和我的downloadAccepted中的onData更改始终被调用。我已经尝试过在方法中执行以下操作:
accepted = new ArrayList();
不幸的是,如果我将此行添加到两种方法之一,则始终不会显示任何内容。
答案 0 :(得分:3)
在开始处理响应之前,先使用accepted.clear()
删除旧数据
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
accepted.clear();
//^^^^^^^^^^^^^^
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
downloadAcceptedDetails(plz, snapshot.getKey().toString());
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
答案 1 :(得分:2)
Pavneet's approach有用,但是意味着您可以在任何子项发生更改时刷新整个列表。如果要进行更详细的更新,则需要使用ChildEventListener
,它告诉您添加,删除,修改或移动了哪些子节点。
您共享的第一个侦听器的简单示例:
ref.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildKey) {
downloadAcceptedDetails(plz, dataSnapshot.getKey().toString());
}
public void onChildRemoved(DataSnapshot dataSnapshot) {
// TODO: remove `dataSnapshot.getKey()` from the list
}
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildKey) {
// TODO: update `dataSnapshot.getKey()` in the list
}
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildKey) {
// TODO: move `dataSnapshot.getKey()` in the list
}
@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore exceptions
}
});