如何从Firebase节点获取价值

时间:2020-05-01 14:33:39

标签: android firebase firebase-realtime-database

enter image description here

我想获取Android Studio中isSeen节点的值。 M6F2mJjQ8uGPXAynZzV是消息的ID,并将消息更改为message。我想在Adapter类中获得此值。

2 个答案:

答案 0 :(得分:1)

如果要获取isSeen值,请尝试以下操作:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Chats");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
         @Override
      public void onDataChange(DataSnapshot dataSnapshot) {
           for(DataSnapshot data: dataSnapshot.getChildren()){
                   Boolean isSeen = data.child("isSeen").getValue(Boolean.class);
                  }
            }

        @Override
       public void onCancelled(DatabaseError databaseError) {
                  throw databaseError.toException();
               }
          });

Chats节点内进行迭代,然后可以检索isSeen

答案 1 :(得分:1)

因此,您想获取一个boolean,转换为string并将其与Another string进行比较:

如果您要这样做,那么这就是您的答案:

//this is the string that you want to compare against
String yourString = "true";

//this is your reference
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Chats");


//make a listener
ValueEventListener listener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        //loop through the random key IDs

        for(DataSnapshot ds : dataSnapshot.getChildren()){
        //get the boolean "isSeen"
        boolean isSeen = ds.child("isSeen").getValue(Boolean.class);

        //convert boolean to string
        String isSeenString = String.valueOf(isSeen);

        //compare isSeenString with your String

        if(isSeenString.equals(yourString)){
          //they are equal

         }else{
          //they are not equal

           }

        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
};

//add the listener
ref.addValueEventListener(listener);