The Firebase Database doesn't have an exists operation. So the only way to know if an item exists is to retrieve it.
That said, there are a few choices to handle this situation. But I first want to recommend that you fix your data structure: any time you have an array and try to do a contain-operation on it you should likely have used a set. Instead of repeating myself, I'll refer to my answer here: Firebase query if child of child contains a value. Go read it now... I'll be here when you get back.
Now that you've read about sets vs arrays, you'll see that your data is better stored as:
names : {
"john": true,
"jack":true ,
"jason": true,
"jill": true,
"travis": true,
"alice": true
}
Much better. :-)
Now back to your question: you'll have to retrieve an item to check if it exists. I can think of two ways to do that: either get the entire list or get each individual item.
You retrieve the entire list and then use DataSnapshot.exists()
for the specific items:
ref.child("names").addSingleValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.child("john").exists() && !snapshot.child("jane").exists()) {
...
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "onCancelled", databaseError.toException());
// ...
}
});
The alternative is to retrieve the individual items:
ref.child("names/john").addSingleValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.exists()) {
...
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "onCancelled", databaseError.toException());
// ...
}
});
Which one works best depends largely on how many names you expect to have in the list.