Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if a key exist firebase Android

I want to check if a key exist in the firebase db. so for example, I want to look for the key "upvotes" to see if it exist or not.

Here is an exmaple, "upvotes" key does not exist in here: enter image description here

Now I my attempt to check if the key "upvotes" is at this location:

        Map<String, Object> newPost = (Map<String, Object>) ids.next().getValue();
            if(newPost.get("upvotes").toString().equals("upvotes")){
                disp_rate = newPost.get("upvotes").toString();
            }
            else
            {
                disp_rate = "0";
            }

My attempt is wrong, so how do I check if the key "upvotes" exist at this location.

like image 816
nothingness Avatar asked Apr 02 '15 19:04

nothingness


1 Answers

If you want to check if key exist or not, try this.

firebaseRef.orderByKey().equalTo(key).addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

              if(dataSnapshot.exists()) {
                   //Key exists
                   Log.d(TAG,""+key);
              } else {
                  //Key does not exist
              }

    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {

    }
});
like image 144
Saurabh Padwekar Avatar answered Sep 30 '22 07:09

Saurabh Padwekar