when I manually change value in firebase database I create more items in listview instead of updating value in listview

前端 未结 1 1434
醉酒成梦
醉酒成梦 2021-01-28 21:04

I have No idea what\'s going wrong in my code Please Help Me. Just Trying To Retrieve data to list view.

My MainActivity.java

public class MainActivity e         


        
1条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-28 21:49

    When you update a value in your database, it will trigger your

    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {...
    

    Again, and that will fetch for all childrens (included the updated one) and will be placed inside the list again this will duplicate the items since inside your onDataChange you have a for loop that will loop throught all the childrens again and will add them again to the current populated list.

    What you need to do, is to clear the list when is fetched again

    ref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                list.clear();
                for (DataSnapshot ds: dataSnapshot.getChildren()){
    
                    user = ds.getValue(User.class);
                    list.add(user.getName().toString()+user.getEmail().toString());
    
                }
                listView.setAdapter(adapter);
    
            }
    
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
    
            }
        });
    

    Another way you can do it is to use updateChildren() with a map, this will just update the item you are updating in your database

    0 讨论(0)
提交回复
热议问题