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 extends AppCompatActivity {
ListView listView;
FirebaseDatabase database;
DatabaseReference ref;
ArrayList<String> list;
ArrayAdapter <String> adapter;
User user;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
user = new User();
listView = findViewById(R.id.listView);
database = FirebaseDatabase.getInstance();
ref = database.getReference("match1contest1");
list = new ArrayList<>();
adapter = new ArrayAdapter<String>(this,R.layout.user_info,R.id.userInfo, list);
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
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) {
}
});
}
}
My User.java
public class User {
private String name;
private String email;
private String phone;
private String userName;
private String password;
public User() {
}
public User(String name, String email, String phone, String userName, String password) {
this.name = name;
this.email = email;
this.phone = phone;
this.userName = userName;
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
Below Are Images
I Just Want To Update the Value
I don't know why it creates more items
I have only 3 children in firebase
I am Just retrieving data, the data is saved manually from firebase console
Please Help Me...
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