Reputation: 67
I am trying to make and app which will backup my contact list to firebase database. I can store all contacts into the database, but when I save new numbers and hit sync button again, it pushes all contacts again. I have the ArrayList of my contacts now I want to check each and every contacts if it already exists in firebase or not. If it does not exist, it should be inserted.
public void SyncNow(View view) {
final DatabaseReference root = FirebaseDatabase.getInstance().getReference();
for (i=0; i<storeContacts.size(); i++){
UserContact contact = storeContacts.get(i);
final String number = contact.getContactNumber();
Query query = root.child("contactList").orderByChild("contactNumber").equalTo(number);
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
//do nothing
}else {
String key = root.push().getKey();
root.child("ContactList").child(key).setValue(contact);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
This code is adding only the last contact of my UserContact ArrayList for size of arraylist. I have 108 contact it pushing the last contact 108 times. Someone please help.
Upvotes: 2
Views: 621
Reputation:
you used for each loop then i think all record will be add that does not have firebase database ..
for (UserContact contact:storeContacts){
}
Upvotes: 0
Reputation: 138824
To solve this, you need to do a little change in your database strcuture by saving those numbers as in the following database strcuture:
Firebase-root
|
--- phoneNumbers
|
--- phoneNumberOne
| |
| --- //details
|
--- phoneNumberTwo
| |
| --- //details
|
--- phoneNumberThree
|
--- //details
Now it's very simply to check a number for existens.
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference phoneNumberToCheckRef = rootRef.child("phoneNumbers").child(phoneNumberToCheck");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.exists()) {
//Add number
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
phoneNumberToCheckRef.addListenerForSingleValueEvent(valueEventListener);
Upvotes: 1