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.
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()) { // 👈 Loop over results
String music_id = snapshot.child("Music_ID").getValue(String.class); // 👈 Get value for this result
Log.i("Value_id", music_id);
str_musictitle.setText(music_id);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // 👈 Never ignore possible errors
}
});
Related
Firebase Realtime Database tree
I am new to Firebase and Java. All I need to do is display the single line Key1(image linked above) to my app.
This is the java I used:
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference().child("ReNu");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
String values = dataSnapshot.getValue(String.class);
Temp.setText(values);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
The data from that specific line is not getting displayed and which means I am probably not getting the data correctly I assume.
I am not sure how to fix it- any help is highly appreciated.
If you only need to display the value of the key1 field that exists within your ReNu node, then please use the following lines of code:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference renuRef = db.child("ReNu");
renu.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
DataSnapshot snapshot = task.getResult();
String key1 = snapshot.child("key1").getValue(String.class);
Log.d("TAG", key1);
Temp.setText(key1);
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
The result in the logcat will be:
Temp=23.0*C Humidty=56.0%
Along with setting the same value to the Text TextView. Please also note that there is no need for an iteration, since there is only one child under ReNu node.
I need to retrieve specific info from Firebase Realtime Database to send push messages, but don't know how to do it, I need to get in String the device token from all the users, so tried to call Users, the should call user ids (this part is where I'm lost, don't know how to get this path), and then device token.
This is what I have :
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
usersIDs = UsersRef.getKey().toString();
UsersRef.child(usersIDs).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NotNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
if (dataSnapshot.hasChild("device_token")) {
receiverUserDeviceToken = dataSnapshot.child("device_token").getValue().toString();
}
}
}
#Override
public void onCancelled(#NotNull DatabaseError error) {
}
});
According to your last comment:
Correct, I need to get both values.
Please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference users = rootRef.child("Users");
usersRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot userSnapshot : task.getResult().getChildren()) {
String deviceToken = userSnapshot.child("device_token").getValue(String.class);
Log.d("TAG", deviceToken);
}
} else {
Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
}
}
});
The result in the logcat will be:
f4...XMY:APA...wr3
eff...8NT:APA...Bd7
Remember, to be able to get all the results from a DataSnapshot object, you have to iterate through the children using .getChildren().
I need to get nickname value from Firebase Real time database after button is clicked. So i made singleValueListner() in button´s onClick method. But it don´t work.
I have tried debug it, but code didn´t get into singleValueEventListener()
Button getName = (Button)findViewById(R.id.getName);
getName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference db = FirebaseDatabase.getInstance().getReference().child("Member").child(user.getUid());
db.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
TextView tv = (TextView)findViewById(R.id.tv);
tv.setText(data.child("nickname").getValue().toString());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
Database JSON structure:
{
"Member" : {
"1Zuv6VZZ0kPluwc33f1QQQ7DZD93" /* UID */ : {
"-LgIHwiAjfuh5pjK7wzl" : {
"actualScore" : 0,
"bestScore" : 0,
"email" : "some#email.com",
"nickname" : "Vitek",
"season" : 0
}
}
}
}
Database structure:
https://drive.google.com/file/d/15B4b6Rb_WAiS6fioI9gItyijrbDiVjzJ/view
I need to get nickname, I think this is writen good, but not. So, what is wrong?
To get the value of your nickname property, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Member").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String nickname = dataSnapshot.child("nickname").getValue(String.class);
Log.d(TAG, nickname);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
The output in your logcat will be:
Vitek
So there is no need to loop through the DataSnapshot object in order to get the value of your nickname property. If you don't get this result, please check the logcat to see if you have an error message printed out.
You are only referring up to user's id but there is also a parent key of user detail which you need to reference.
tv.setText(data.child("LgiH------").child("nickname").getValue().toString());
but try to remove that second key from your registering user's code because it is not helpful.
You have made a mistake in refering your firebase root node. just change your line as below :
DatabaseReference db = FirebaseDatabase.getInstance().getReference("Member");
Now,just call your singlevalue event.
db.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
TextView tv = (TextView)findViewById(R.id.tv);
tv.setText(data.child("nickname").getValue().toString());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
This will do your stuff. try debugging your code with log at step by step.
The data was removed but it was added back immediately. THis code was placed inside the code for checking of credentials(supposedly will check for users credential before deleting the items). I have tried putting it as a separate code with just the use of a button and it works. But why does the glitch occurs?
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
Query query = ref.child("posts").orderByChild("userid").equalTo(uid);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot Snapshot: dataSnapshot.getChildren()) {
Snapshot.getRef().removeValue();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I am looking for a way to get data from the firebase real-time database in a format like an array[] or a String.
My database looks like this:
Link to image of database
Or:
Database
|
-->Users
|
-->UID1
-->UID2
This is at the root of the database
I want to get a list of all of the UIDs in the "Users" child.
This is the code I have so far and am a bit stuck on:
DatabaseReference databaseReference = firebaseDatabase.getReference("Users");
databaseReference.addValueEventListener(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String UIDs = dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I am a bit of a rookie as it comes to java, android studio, and firebase. I am trying to get the data in a format I know how to use like a String or an Array[] of Strings. I looked around if other people had maybe asked the same question, but I could get the answers to those questions to work/didn't understand them.
Thanks in advance for your time!
To get the a list of uids, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Users");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String uid = ds.getKey();
list.add(uid);
}
//Do what you need to do with your list
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
usersRef.addListenerForSingleValueEvent(valueEventListener);
I recommend you to use the list only inside the callback otherwise it will be empty. If you want to use it outside the onDataChange() method, I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.
For your above question I will give both ways: ArrayList or String with delimiters
ArrayList<String> uids = new ArrayList<String>();
FirebaseDatabase.getInstance().getReference("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
uids.add(snapshot.getKey());
}
}
}
#Override
public void onCancelled(DatabaseError error) {
}
});
For String
String uids = "";
FirebaseDatabase.getInstance().getReference("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
uids += snapshot.getKey() + ",";
}
}
}
#Override
public void onCancelled(DatabaseError error) {
}
});
This gives an output such as: uid1,uid2,uid3,.....uidn,
You can try this:
DatabaseReference ref=
FirebaseDatabase.getInstance().getReference("Users");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
int i = 0;
for(DataSnapshot d : dataSnapshot.getChildren()) {
name[i] = d.getKey();
i++;
}
}
}//onDataChange
#Override
public void onCancelled(DatabaseError error) {
}//onCancelled
});
name[] is an array of strings!