【发布时间】:2017-04-20 12:20:01
【问题描述】:
在我的应用程序中,我有一个植物列表,用户可以插入新植物、修改和删除它们。
用户可以长按列表中的一项将其删除,但如果其他人从另一台设备或我从数据库中删除相同的项目,则列表不会更新,就像在编辑中一样(该项目保留在列表中,您也可以再次删除它,这没有意义)。
这是我在数据更改时更新项目的方法:
PlantViewHolder(View itemView, Context context) {
super(itemView);
cardView = (CardView)itemView.findViewById(R.id.cardView);
plantCommonName = (TextView)itemView.findViewById(R.id.plantCommonName);
plantScientificName = (TextView)itemView.findViewById(R.id.plantScientificName);
plantPhoto = (ImageView)itemView.findViewById(R.id.plantPhoto);
plantCategory = (TextView)itemView.findViewById(R.id.plantCategory);
plantDescription = (TextView)itemView.findViewById(R.id.plantDescription);
plantPrice = (TextView)itemView.findViewById(R.id.plantPrice);
plantStock = (TextView)itemView.findViewById(R.id.plantStock);
this.context = context;
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
database.getReference().child("plants").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dss: dataSnapshot.getChildren()) {
Plant p0 = dss.getValue(Plant.class);
editAt(p0);
}
}
@Override
public void onCancelled(DatabaseError error) {
Log.w("Failed to read value.", error.toException());
}
});
}
方法如下:
private void editAt(Plant p0) {
for(int i = 0; i < plants.size(); i++) {
if(plants.get(i).getID() == p0.getID()) {
plants.get(i).setCommonName(p0.getCommonName());
plants.get(i).setScientificName(p0.getScientificName());
plants.get(i).setPrice(p0.getPrice());
plants.get(i).setStock(p0.getStock());
plants.get(i).setSeason(p0.getSeason());
plants.get(i).setDescription(p0.getDescription());
notifyItemRangeChanged(i, plants.size());
}
}
}
如您所见,我只是修改了列表中的特定项目,但我不知道如何在数据库侦听器中区分或实现删除。
如何检测是否从数据库中删除了某个项目并使用ValueEventListener 将其删除?
【问题讨论】:
标签: android firebase firebase-realtime-database android-recyclerview