Home > Blockchain >  The operation does not wait until data is successfully retrieved from Firebase in addSingleValueEven
The operation does not wait until data is successfully retrieved from Firebase in addSingleValueEven

Time:10-04

I am trying to implement the favorite button and store the favorite item in the Firebase Realtime Database. The concept is that clicking the button first will check into the database whether the item is listed in the favorite list or not if yes then delete it and if not then add the item to the favorite list.

here is my code


   mDatabase.getReference().child(FirebaseVar.USERS).child(mUser.getUid()).child(FirebaseVar.FAVOURITE).child(getIntent().getStringExtra(FirebaseVar.FULLKEY)).addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) {
                        Toast.makeText(FoodItemDetailActivity.this, (snapshot.getValue(String.class)), Toast.LENGTH_SHORT).show();
                        if (snapshot.getValue(String.class) == "True")
                        {
                            Log.d("msg", "exist");
                            return;
                        }
                        else
                        {
                            mDatabase.getReference().child(FirebaseVar.USERS).child(mUser.getUid()).child(FirebaseVar.FAVOURITE).child(getIntent().getStringExtra(FirebaseVar.FULLKEY)).setValue("True");
                            return;
                        }
                    }

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

                    }
                });

Now problem is when I click on button simultaneously three times then and only then it shows me that "exist" otherwise I am not getting anything. But yes if the item is not there in DB then it on first click store the item in DB but I don't know why is it happening so.

CodePudding user response:

literally question has been solved just by replacing

 if (snapshot.getValue(String.class) == "True")

with this

 if (Objects.equals(snapshot.getValue(String.class), "True"))

but I don't know why this happened, please can anyone explain?

CodePudding user response:

The == (double equal) operator is used in Java to compare numbers. When it comes to comparing strings, you either use the solution in your answer:

if (Objects.equals(snapshot.getValue(String.class), "True"))

Or even simpler:

if (snapshot.getValue(String.class).equals("True"))

By using String#equals(Object anObject)

One more thing to mention is that boolean values should be stored as boolean values and not as strings, using "True":

childNode
  |
  --- favorite: true

See, now we have true as a boolean and not as a string. See the absence of "" (double quotes)? If you do this change the comparison will look like this:

if (snapshot.getValue(Boolean.class))
  • Related