2
Hello,
I have a problem while reading the data in Firebase. I use Android Studio 3.0 and Java.
I can connect to the database, get the instance, the logged in user, but I’m not able to read the attributes of the selected node.
The structure of the bank is this one:
{
"user" : {
"YWxsYW5AbmVyb3MuY29tLmJy" : {
"active" : true,
"id" : "YWxsYW5AbmVyb3MuY29tLmJy",
"userEmail" : "[email protected]",
"userName" : "Allan Neros",
}
}
}
What I intend to do is take all the Children from 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());
}
});
User class has the same attributes as the database.
After these codes, I am setting the Activity Textviews with the logged information, but since it is empty, I get a Nullpointerexception (which makes sense, because the logged object is not being created, as it does not enter onDataChange). I built the code with what I found in the Firebase documentation and examples collected on the Internet (including posts here from Stackoverflow).
Any clues as to why this error is happening? Is there a better way to get this information?
Thank you for your attention and help.
If mQuery` really is null, it should not be getting to the little one that creates the Listener, because before it has a System.out.println and should already stop there. Please confirm the exact line of the exception and the error message.
– Pablo Almeida
I make the words of @Pabloalmeida mine, confirm the exception line
– Dev
@Pabloalmeida, thank you for the return. mQuery is not null when you pass mQuery.addListenerForSingleValueEvent(new Valueeventlistener(). However, after going through this part (where I must take the logged object elements to put in the Activity Textviews), in Debugger, mQuery is null. Has something to do with the object’s scope? (mQuery is being instantiated in onCreate)
– Allan John Neros