Reputation: 89
I have a database of users with their emails, role and list of contacts.
I have code to add contacts that when you input into the EditText
, it checks through the database if the email exists and if it does, it appends the email into the contacts list. However, nothing gets added in my database.
public void searchContacts(final String emailInput){
final DatabaseReference users;
users = FirebaseDatabase.getInstance().getReference("users");
users.orderByChild("email").equalTo(emailInput).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()){
if((userSnapshot.child("email").getValue(String.class).equals(emailInput))){
users.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("contacts").child(emailInput).setValue(true);
}
}
}
Upvotes: 0
Views: 73
Reputation: 1
Nothing is added, because you haven't create a list yet. To solve this, please use the following code:
public void searchContacts(final String emailInput){
DatabaseReference users = FirebaseDatabase.getInstance().getReference("users");
users.orderByChild("email").equalTo(emailInput).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>(); //Create the list
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()){
String email = userSnapshot.child("email").getValue(String.class);
if(email.equals(emailInput)){
users.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("contacts").child(emailInput).setValue(true);
list.add(email); //Add the email the list
}
}
//Do what you need to do with list
}
}
}
Upvotes: 1