我使用firebase创建To-Do android应用程序。我使用recyclerview和cardview来填充firebase的数据。但是当我在Android Monitor上观看并看到我的调试日志触发两次onChildChanged
时,会发生一些奇怪的事情:
D/DiaryAdapter: onChildChanged:-KIafq035E-pc6uT3Ej7
D/DiaryAdapter: onChildChanged:-KIafq035E-pc6uT3Ej7
并且在recyclerview上导致的项目闪烁两次(当项目更新时闪烁效果)
我把它放在MainFragment.java onStart()
// Setup adapter
diaryAdapter = new DiaryAdapter(getContext(),mDiaryRef);
recyclerDiary.setAdapter(diaryAdapter);
在我的适配器构造函数
上public DiaryAdapter(final Context context, DatabaseReference ref) {
mContex = context;
mDatabaseRefrence = ref;
mChildEventListener = new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());
Diary diary = dataSnapshot.getValue(Diary.class);
mDiary.add(diary);
mDiaryID.add(dataSnapshot.getKey());
notifyItemInserted(mDiary.size() - 1);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Log.d(TAG, "onChildChanged:" + dataSnapshot.getKey());
Diary newDiary = dataSnapshot.getValue(Diary.class);
int diaryIndex = mDiaryID.indexOf(dataSnapshot.getKey());
if (diaryIndex > -1) {
mDiary.set(diaryIndex, newDiary);
notifyItemChanged(diaryIndex);
} else {
Log.w(TAG, "onChildChanged:unknown_child:" + dataSnapshot.getKey());
}
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Log.d(TAG, "onChildRemoved:" + dataSnapshot.getKey());
int diaryIndex = mDiaryID.indexOf(dataSnapshot.getKey());
if (diaryIndex > -1) {
mDiary.remove(diaryIndex);
mDiaryID.remove(diaryIndex);
notifyItemRemoved(diaryIndex);
} else {
Log.w(TAG, "onChildRemoved:unknown_child:" + dataSnapshot.getKey());
}
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey());
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "postComments:onCancelled", databaseError.toException());
Toast.makeText(mContex, "Failed to load diary.",
Toast.LENGTH_SHORT).show();
}
};
ref.addChildEventListener(mChildEventListener);
}
我跟随firebase android示例here
编辑:数据库结构
{
"diary" : {
"2Y4XwraNoRdIFPBJY0XxwdPte0H2" : {
"1437" : {
"-KIahAPVU_WrmP5rDcAa" : {
"created" : 1464159484316,
"infaq" : {
"selesai" : false
},
"ngaji" : {
"ayatAkhir" : 0,
"ayatMulai" : 0,
"selesai" : true,
"surahAkhir" : 0,
"surahMulai" : 0
},
"puasa" : {
"sahur" : false,
"selesai" : true,
"summary" : ""
},
"sholat" : {
"ashar" : true,
"dhuhur" : true,
"done" : true,
"mIsya" : true,
"maghrib" : true,
"subuh" : true
},
"summary" : "Puasa kedua Tos",
"tanggal" : 2,
"tarawih" : {
"ringkasan" : "",
"selesai" : true
},
"updated" : 1464186194796
},
}
}
}