I want to read Music_ID of the group with Playlist_ID of 2 in firebase.
The following error occurs.
java.lang.NullPointerException: println needs a message
This is my firebase realtime database.
And this is my code.
database = FirebaseDatabase.getInstance();
storage = FirebaseStorage.getInstance();
dref = FirebaseDatabase.getInstance().getReference();
private void Startplaylist(String mood) {
DatabaseReference plist = dref.child("Playlist");
plist.orderByChild("Playlist_ID").equalTo(2).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
// Log.i("Value", dataSnapshot.getValue().toString());
String music_id = dataSnapshot.child("Music_ID").getValue(String.class);
Log.i("Value_id", music_id);
str_musictitle.setText(music_id);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
An alarm pops up that an error occurs in this part.
Log.i("Value_id", music_id);
I think "music_id" is not being read.
I tried to change part
String music_id = dataSnapshot.child("Music_ID").getValue(String.class);
to String music_ids = dataSnapshot.child("Music_ID").getValue().toString();
and run it, but I couldn't get the desired result.
CodePudding user response:
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
The code in your onDataChange
will need to handle this list by looping over dataSnapshot.getChildren()
. Something like this:
DatabaseReference plist = dref.child("Playlist");
plist.orderByChild("Playlist_ID").equalTo(2).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) { //