Arduino
Arduino

Reputation: 315

Detect firebase child value is "null" or "0"

This is the value in inside my firebaseDatabse

This is how I retrieve user infomation (e.g Name & Age)

My questions is how to I check if the child value is "null"? Help and guidance needed...... Thanks

Upvotes: 2

Views: 17287

Answers (3)

Sumit Shukla
Sumit Shukla

Reputation: 4494

You can use:

if (dataSnapshot.exists()){}  OR
if (dataSnapshot.getChildrenCount() != 0){} OR
if (dataSnapshot.hasChild("childName")){}

If there is no data, the snapshot will return false when you call exists() and null when you call getValue() on it.

Upvotes: 2

Lewis McGeary
Lewis McGeary

Reputation: 7922

There are a few methods you can call from a DataSnapshot to check if a value is 'null'.

The first thing is to make clear is that Firebase will not store a node or field with a null value, so something like age: null won't be in your database. If the value is null, the age field just won't be there at all.

So the methods available on a DataSnapshot are: exists(), hasChild(String s) and hasChildren() which can be used to check for the existence of something depending on what you're looking for.

Examples of usage would look like:

if (dataSnapshot.exists())

if (dataSnapshot.hasChild("age"))

if (dataSnapshot.child("name").exists())

If you want to check if the value is actually '0' as also mentioned in your question then there is nothing special to that; you would just check if the value equals zero the same as you would in any other situation.

Upvotes: 13

Tata Fombar
Tata Fombar

Reputation: 349

your getters will return a null for empty fields in your snapshot

Upvotes: 2

Related Questions