在我的应用程序中,我有一个植物列表,用户可以插入新植物、修改和删除它们。
用户可以长按列表中的一个项目将其删除,但是如果其他人从另一台设备或我从数据库中删除相同的项目,则列表不会更新,就像编辑中那样(该项目保留在列表中,您也可以再次删除它,这没有意义)。
这是我在数据更改时更新项目的方法:
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
将其删除?
最佳答案
您不需要使用ValueEventListener
来删除值。只需找到您的引用
并使用removeValue()
方法即可。假设您有一个名为 Plants
的节点,请使用以下代码:
yourReference.child("Plants").child(plantId).removeValue();
其中plantId
是您要删除的特定植物。
如果您想验证某个项目是否存在,请获取您的引用
,然后在 SanpShop
上使用 exists()
方法。
希望有帮助。
关于android - 使用 Firebase 检测 RecyclerView 项目中的删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43519364/