5

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.

nothingness
  • 694
  • 3
  • 9
  • 25
  • In javascript you would get a `snapshot`, and call `hasChild`. See Frank's answer here: http://stackoverflow.com/questions/24824732/test-if-a-data-exist-in-firebase The Java API documentation has details about the Java `hasChild` method: https://www.firebase.com/docs/java-api/javadoc/com/firebase/client/DataSnapshot.html Does that help? – Seamus Apr 02 '15 at 20:30
  • thanks for your reply, I was checking if the key exist not the child but I stumbled across this `exists public boolean exists() Returns true if the snapshot contains a non-null value. Returns: True if the snapshot contains a non-null value, otherwise false` I think this is it, now just need to figured how to use it. – nothingness Apr 02 '15 at 20:43
  • 1
    got it working just needed this function – nothingness Apr 02 '15 at 21:18

2 Answers2

7

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) {

    }
});
Saurabh Padwekar
  • 3,888
  • 1
  • 31
  • 37
3

Just needed to use this boolean function containsKey

so...

boolean check_rate = newPost.containsKey("upvotes");

if(check_rate == true){
                String disp_rate = newPost.get("upvotes").toString();
                rate_count.setText(disp_rate);
            }
            else{
                System.out.println("FAILED");
            }

This will fix the transaction if anyone is having the same issue with upvotes.

nothingness
  • 694
  • 3
  • 9
  • 25