Reputation: 3262
I have the following data base:
database
|
places
|
|____user1
| |_____outside: "yes"
|
|____user2
|_____outside: "no"
I am fetching the data like that:
mDatabaseReference = FirebaseDatabase.getInstance().getReference("places");
ValueEventListener placesListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
//this won't work
String place = datas.child("user1").child("outside").getValue().toString();
}
mDatabaseReference.addValueEventListener(placesListener);
But it doesn't work, when I launch my app, I get that it is a null and the app crashes.
Log crash, as requested:
Process: com.example.places, PID: 32431
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
at com.example.places.MainActivity$1.onDataChange(MainActivity.java:44)
at com.google.firebase.database.obfuscated.zzap.zza(com.google.firebase:firebase-database@@16.0.3:75)
at com.google.firebase.database.obfuscated.zzca.zza(com.google.firebase:firebase-database@@16.0.3:63)
at com.google.firebase.database.obfuscated.zzcd$1.run(com.google.firebase:firebase-database@@16.0.3:55)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Upvotes: 0
Views: 44
Reputation: 1169
dataSnapshot.getChildren()
currently iterates over all children in your "places"
Currently you have user1
and user2
.
When you iterate over them in a for loop like you are doing
String place = datas.child("user1").child("outside").getValue().toString();
You will eventually try to look for datas.child("user1") when it does not exist.
in the for loop you can use
datas.child("outside").getValue().toString();
If you log this you will find first user1
outside value printed, and then user2
.
If you need user1 you can add an if statement where you check the key
if(datas.getKey().toString().equals("user1"))
Then do what you need. user1
should not be hardcoded, but a parameter that fetches the user you need.
Upvotes: 1