'Cannot Retreive Boolean from Firebase

I'm sorry if this is a very basic question, but I am not able to figure out this issue. I am trying to do achieve an if statement based on a boolean value in the Firebase database. I have tried various combinations, but my most recent attempt is below.

When I run the app with the below code:

  • Nothing happens
  • There is no error message
  • The "likeButtonNotClicked" button displays (for both true and false conditions)
RetreiveLikeReference = FirebaseDatabase.getInstance().getReference().child("Main Wall Posts").child(postId).child("liked")

 private void UpdateLike() {

      if(RetreiveLikeReference.equals(true)){
          likeButtonClicked.setVisibility(VISIBLE);
          likeButtonNotClicked.setVisibility(GONE);
      } else {
          likeButtonClicked.setVisibility(GONE);
          likeButtonNotClicked.setVisibility(VISIBLE);

      }

    } 

I also tried the code below and got the same result.

RetreiveLikeReference.addValueEventListener(new ValueEventListener() {
           @Override
           public void onDataChange(@NonNull DataSnapshot snapshot) {
               if (snapshot.exists()) {
                   snapshot.getValue();
                   if (snapshot.equals(true)){
                       likeButtonClicked.setVisibility(VISIBLE);
                       likeButtonNotClicked.setVisibility(GONE);

                   } else {
                       likeButtonClicked.setVisibility(GONE);
                       likeButtonNotClicked.setVisibility(VISIBLE);


                   }


               } 
           }

           @Override
           public void onCancelled(@NonNull DatabaseError error) {

           }

       });


Solution 1:[1]

Try getting the boolean value from your database using the Boolean.valueOf() method. You're not telling java the type of value that you are getting so java sets automatically the type of the value to Object.

You can fix it by telling to java that the value type is Boolean like this:

if ((Boolean.valueOf(snapshot.getValue()))) {/* You code here...*/}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 GSepetadelis