Google Firebase Check If Child Exists

Google firebase check if child exists

Edit 2; worth putting on top: I think it is worth mentioning that this is actually downloading all data at this snapshot just to check whether any data exists. You should be mindful here. If the reference is huge (e.g. actually the root reference and not a specific child/property) then you should either find a deeper node you can use to check for existence or design your data structure differently so an efficient check is possible.

A database reference is effectively the URL for that data. You want to actually get data to see whether a child exists. This is why the method you seem to be looking for is on DataSnapshot.

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
void onDataChange(DataSnapshot snapshot) {
if (snapshot.hasChild("name")) {
// run some code
}
}
});

Now, this design pattern feels a bit strange. You're reading the whole database just to see whether "name" exists. You can make this a bit more efficient by listening to rootRef.child("name") and then just checking whether snapshot.exists().

If you're trying to do validation here, and not control flow, you should consider putting this code in your rules.json.

edit: I originally used the wrong function name (childExists instead of hasChild)

How do I check if specific child value exists in FireBase (Android)

As others have commented, data is loaded from Firebase asynchronously. By the time you check isFirstTime, the data hasn't been loaded yet, onDataChange hasn't been run yet, so ifFirstTime will have its default value (false for a boolean).

All code that requires data from the database should be inside onDataChange (or invoked from within there). The simplest fix for your code is:

databaseReference = FirebaseDatabase.getInstance().getReference();
DatabaseReference dbRefFirstTimeCheck = databaseReference.child("User").child(user.getUid()).child("Nickname");

dbRefFirstTimeCheck.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
showNewUserBox();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});

Also see some of the many questions about asynchronous loading from Firebase, such as getContactsFromFirebase() method return an empty list (or this quite old classic: Setting Singleton property value in Firebase Listener).

How to check if sub child exists in Firebase Realtime Database?

In order to solve this, you need to use a Query and exists() method on the DataSnapshot object like this:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef
.child("Employees")
.child(mobileNumber) //Could be: 765432189
.child(userPin) //Could be: 123457
.orderBychild("empid")
.equalsTo(enteredUserPIN);
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
//Do something
} else {
//Do something else
}
}

@Override
public void onCancelled(DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(valueEventListener);

According to your edit, please use the follwing code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference employeesRef = rootRef.child("Employees");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
if(ds.child(enteredUserPIN).exists()) {
//Do something
} else {
//Do something else
}
}
}

@Override
public void onCancelled(DatabaseError databaseError) {}
};
employeesRef.addListenerForSingleValueEvent(valueEventListener);

firebase check if child exists

This sounds pretty overcomplicated. In the Firebase Database, it's often best to separate read and write operations as much as possible. And while push ids are a great way to store data in a chronological way; if items have a natural key, it is often better to store them under that key.

For example if your String match is really a String matchId, you can ensure that each match is present at most once by using matchId as the key.

userRef.child("matches").child(matchId).setValue(true);

This operation is idempotent: it will give the same result no matter how often you run it.

You'll note that I don't check of matches already exists: the Firebase Database automatically creates all nodes that are needed to store the value and it automatically removes all nodes that have no values under them.

Firebase Android, checking if an object (with multiple children) exists

Firebase queries can only order/filter by a single property. So there is no WHERE clause within Firebase. What should you do instead, is to couple a compound value named location_mode_spinnerOne. Your database structure should look like this:

Firebase-root
|
-- Students Reports
|
-- Jasna Kuljancic
|
-- Clinical First
|
-- -KuVRQ4OjdfKXCNdLWzb
|
--- data: 3939393
|
--- location: "fifififi"
|
--- mode: "ododododo"
|
--- spinnerOne: "Asylum Hill Family Clinic"
|
--- location_mode_spinnerOne: "fifififi_ododododo_Asylum Hill Family Clinic"

As you probably see, i have added the new compound value location_mode_spinnerOne for each particular category. This means that you can query your Firebase database according to this new location_mode_spinnerOne field. Assuming that the above database structure is correct, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference categoryRef = rootRef.child("Students Reports").child(fullname).child(CATAGORY);
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String searchedText = "fifififi";

for(DataSnapshot ds : dataSnapshot.getChildren()) {
String location_mode_spinnerOne = ds.child("location_mode_spinnerOne").getValue(String.class);
if(!location_mode_spinnerOne.contains(searchedText)) {
categoryRef.child(uniqueID).setValue(subreport);
}
}
}

@Override
public void onCancelled(DatabaseError databaseError) {}
};
categoryRef.addListenerForSingleValueEvent(eventListener);

I gave you an example for searching fifififi keyword. The searchedText text would be the exact searched text typed by the user.

To better understanding, i suggest you see this tutorial.

How to check if path in firebase is there( check if child is there ) flutter

The database.reference().child('classData') statement merely creates a path to a location in the database. It does not trigger a read of the data at that path, so it can't be used to check if data exists at the location.

To determine if data exists, read the data from the database, for example with a once() as shown in this example from the FlutterFire repo:

_messagesRef = database.reference().child('messages');
database.reference().child('counter').once().then((DataSnapshot snapshot) {
print('Connected to second database and read ${snapshot.value}');
});

Then check the value of the DataSnapshot.



Related Topics



Leave a reply



Submit