The following code shows what I really mean:
There is an object called on a reference, which belongs to the DatabaseRefence class, which calls the addValueEventListener method to test if a certain value exists in a table in Firebase. I'd like to test this block of code to see if it's true or false. If it is true (that is, if it does not exist, through the code: "if (!dataSnapshot.exists()) {"), then it prints a message: "Prints a message".
But if it's false (ie if it exists in Firebase Database), then do another action (which would be else of the if). But how to insert this code block inside the if, if it's not boolean type, but it is a DatabaseReference type?
The code is:
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
reference = FirebaseDatabase.getInstance().getReference().child("Users").child(cpfEmHash);
if (!dataSnapshot.exists()) {
Toast.makeText(getApplicationContext(), "Prints a message", Toast.LENGTH_LONG).show();
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
if(reference) {
CodePudding user response:
The reference
object in your code is of type DatabaseRefence, which cannot be used in an if statement as it doesn't return a Boolean value.
If you want to know if some data exists at a particular location, then you should only call exists()
, as you already do. So the problem in your code most likely comes from the fact that you are not handling the else past. So you aren't getting anything if data already exists. So in code, it should be as simple as:
if (!dataSnapshot.exists()) {
Toast.makeText(getApplicationContext(), "No data", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Data already present", Toast.LENGTH_LONG).show();
}
Besides that, never ignore potential errors. At a minimum, try to implement:
Log.d("TAG", error.getMessage());
To get the error if something goes wrong.