Jkrr
Jkrr

Reputation: 49

Firebase database snapshot returns null

I've got this database: enter image description here

and this code:

FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference dataRef = database.getReference();
number = dataRef.child("planlekcji3").child("Monday").child("lessons");
number.addListenerForSingleValueEvent(new ValueEventListener() {
     @Override
     public void onDataChange(DataSnapshot snapshot) {
         n = snapshot.getValue(String.class);
         number.setValue(Integer.parseInt(n)+1);
     }

     public void onCancelled(DatabaseError error){

     }
 });
dataRef.child("planlekcji3").child("Monday").child(n).setValue(newLesson);

I've got this error:

java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()

so "n" variable is null, what's wrong with my code?

Upvotes: 1

Views: 287

Answers (1)

Ziya ERKOC
Ziya ERKOC

Reputation: 839

You should put the setValue part right into onDataChanged . Due to asynchronous nature of firebase listeners change in the n that occured inside onDataChanged will not be reflected on the outside atomically.

FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference dataRef = database.getReference();
number = dataRef.child("planlekcji3").child("Monday").child("lessons");
number.addListenerForSingleValueEvent(new ValueEventListener() {
     @Override
     public void onDataChange(DataSnapshot snapshot) {
         n = snapshot.getValue(String.class);
         number.setValue(Integer.parseInt(n)+1);
   dataRef.child("planlekcji3").child("Monday").child(n).setValue(newLesson);
     }

     public void onCancelled(DatabaseError error){

     }
 });

Hope that helps!

Upvotes: 1

Related Questions