Issue
I'm new to Android and Firebase. I'm trying to get a String from the Firebase and compare it with the given string.
Now, when I use getValue(), it displays "Cannot resolve method 'getValue' in 'DatabaseReference'"
Here is the structure of my database
Here the name after the node "user1" will change, so I am refining the database till user1
Every time a new folder is created by the app, a new node is created within user1 with the same structure
Now, I want to compare each string in node "AmazonLink" with the given string
Here is my code
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users/user1");
else if(databaseReference.child("AmazonLink").getValue().equals(amazonLink.getText()))
Solution
DatabaseReference#child(String pathString) method, returns an object of type DatabaseReference. As you can see, there is no getValue()
method inside this class. However, DataSnapshot class does contain a getValue().
So in order to check the value of a field in the Realtime Database against a particular value, you have to perform a query and attach a lister like this:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference userOneRef = db.child("Users/user1");
Query query = userOneRef.orderByChild("AmazonLink").equalTo(amazonLink.getText());
query.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
String amazonLink = ds.child("AmazonLink").getValue(String.class);
Log.d("TAG", amazonLink);
}
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
See I have used now DataSnapshot#getValue(Class valueType) which indeed allows me to read the value of the field in a String format.
P.S. The above code will work, only if amazonLink.getText()
will return the exact value of the field it exists in the database.
Answered By - Alex Mamo
Answer Checked By - Pedro (JavaFixing Volunteer)