Android/Firebase - Nullpointerexception when setting Query object

Asked

Viewed 54 times

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.

  • I make the words of @Pabloalmeida mine, confirm the exception line

  • @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)

1 answer

1


If you want to take all the Child from the "Ywxsyw5abmvyb3muy29tlmjy" reference, point your own reference to this Key, and then add a Systener Event directly to the Ference

refFirebase.child("users").child(strUserId);
refFirebase.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            //Supondo que aqui a classe é igual ao seu nó no Firebase
            User loggedUser = dataSnapshot.getValue(User.class);

            //Executa o que precisar com o loggedUser aqui.
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            System.out.println("Erro: " + databaseError.getDetails());
        }
    });
  • Hello, thanks for the return. I replaced my code with the one you put and in the Debugger the refFirebase appears with the keys but without the elements ({}). If I debug the path it appears right /user/strUserId. I thought reading the bank was something simple, not as laborious as it is being.

  • It is because the Ference only brings the value within the event (which is asynchronous). The entity/node itself is the conversion of the dataSnapshot into the event onDataChange.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.