我有一个问题,我有一个回收视图,并且里面有一些来自Firebase数据库的项目,当我按下按钮删除该项目时,该项目从数据集中消失了,但是回收视图显示了我我刚刚删除的项目下面的项目,我不明白为什么,因为我检查了堆栈溢出的操作方法,但我做了同样的事情,但是没有用。
我将添加3张照片和代码以更好地说明自己。
任何人都可以解释发生了什么吗?我认为这是循环视图刷新的问题,但不确定100%。
代码:
public class CartActivity extends AppCompatActivity implements OnRemoveItemClickListener{
private TextView total;
private ImageButton removeFromCartt;
private Button pay;
private RecyclerView mResultList2;
private DatabaseReference mUserDatabase;
int i=0;
int Totalprice=0;
private UsersAdapter adapter;
private ArrayList<Users_get> array_data = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
mUserDatabase = FirebaseDatabase.getInstance().getReference("Cart");
total = findViewById(R.id.TotalPrice);
removeFromCartt = findViewById(R.id.removeFromCart);
mResultList2 = findViewById(R.id.cartList);
pay = findViewById(R.id.pay);
mResultList2.setHasFixedSize(true);
mResultList2.setLayoutManager(new LinearLayoutManager(this));
// Attach a listener to read the data at our posts reference
mUserDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
int flag=1;
for(DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
Users_get post = childSnapshot.getValue(Users_get.class);
array_data.add(new Users_get(post.getName(),post.getSurname(),post.getPrice(),childSnapshot.getKey()));
getTotalPrice(post.getPrice(),flag);
}
setAdapter();
}
@Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
}
private void setAdapter() {
adapter = new UsersAdapter(array_data,CartActivity.this);
mResultList2.setAdapter(adapter);
}
public int getTotalPrice(Long price,int flag){
if (array_data != null) {
if(flag==1)
{
Totalprice+=price;
}
else
{
Totalprice-=price;
}
}
System.out.println(Totalprice);
return Totalprice;
}
@Override
public void onRemoveItemClicked(final int position) {
int flag=0;
FirebaseDatabase.getInstance().getReference("Cart").child(array_data.get(position).getKey()).removeValue();
getTotalPrice(array_data.get(position).getPrice(),flag);
array_data.remove(position);
adapter.notifyItemRemoved(position);
}
@Override
protected void onDestroy() {
super.onDestroy();
if(adapter !=null){
adapter.removeListener();
}
}
}
答案 0 :(得分:1)
尝试一下, 当您删除项目时,firebase会再次通知,并且将相同的数据集追加到相同的array_data列表中。
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (adapter == null) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
Users_get post = childSnapshot.getValue(Users_get.class);
array_data.add(new Users_get(post.getName(), post.getSurname(), post.getPrice(), childSnapshot.getKey()));
getTotalPrice(post.getPrice());
}
setAdapter();
} else {
adapter.notifyDataSetChanged();
}
}