check if a key exist firebase Android

浪子不回头ぞ 提交于 2019-12-07 07:24:08

问题


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:

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.


回答1:


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.




回答2:


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

    }
});


来源:https://stackoverflow.com/questions/29421210/check-if-a-key-exist-firebase-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!