Hello,
I have a problem reading the data in Firebase. I use Android Studio 3.0 and Java.
I can connect to the database, get the instance, the user logged in, but I can not read the attributes of the selected node.
The bank structure is this here:
{
"user" : {
"YWxsYW5AbmVyb3MuY29tLmJy" : {
"active" : true,
"id" : "YWxsYW5AbmVyb3MuY29tLmJy",
"userEmail" : "[email protected]",
"userName" : "Allan Neros",
}
}
}
What I want is to get all the children of the "YWxsYW5AbmVyb3MuY29tLmJy" node.
The Java code I wrote to solve is this one:
FirebaseDatabase dbsFirebase = FirebaseDatabase.getInstance();
DatabaseReference refFirebase = dbsFirebase.getReference();
System.out.println("Reference: " + refFirebase.toString());
//strUserId é uma String que retorna o id do nó, e está funcionando corretamente
Query mQuery = refFirebase.child("user").orderByChild("id").equalTo(strUserId).limitToFirst(1);
System.out.println("Query: " + mQuery.getRef().getKey());
//A aplicação encerra nesta linha, nem passa pelo onDataChange
mQuery.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
loggedUser = new User();
//User loggedUser = dataSnapshot.getValue(User.class);
loggedUser.setId(dataSnapshot.child("id").getValue().toString());
loggedUser.setUserName(dataSnapshot.child("userName").getValue().toString());
loggedUser.setUserEmail(dataSnapshot.child("userEmail").getValue().toString());
}
@Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("Erro: " + databaseError.getDetails());
}
});
The User class has the same attributes as the bank.
After these codes, I'm defining the Activity TextViews with the loggedUser information, but since it's empty, I get a NullPointerException (which makes sense, because the loggedUser object is not being created because it does not go into the onDataChange) . I built the code with what I found in the Firebase documentation and in examples collected on the internet (including posts here from StackOverflow).
Any clue why this error is happening? Is there a better way to get this information?
Thank you for your attention and help.