Retrieve info from firebase - java

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().

Related

Need to show those users who have subscribed the group. i have stored users id in the members child who have joined the group

I need to show groups in the main activity. Here I am using the if condition but I am not getting any groups.
if (snapshot.child("Members").child(FirebaseAuth.getInstance().getUid()).exists());
Here is the whole code:
FirebaseDatabase.getInstance().getReference().child("Groups").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
list.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
if (dataSnapshot.exists()) {
if (snapshot.child("Members").child(FirebaseAuth.getInstance().getUid()).exists());
Group group = dataSnapshot.getValue(Group.class);
list.add(group);
}
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
When you attach a listener at the following reference:
FirebaseDatabase.getInstance().getReference().child("Groups")
It means that you're reading (downloading) the entire "Groups" node. Which is actually not feasible considering the fact that under that node there may be potentially multiple nodes. So if you want to check the existence of a particular element in the Realtime Database, don't do it on the client, but perform a query:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference groupsRef = db.child("Groups");
Query queryByUid = groupsRef.orderByChild("Members/" + uid);
productsRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
list.clear();
for (DataSnapshot ds : task.getResult().getChildren()) {
Group group = ds.getValue(Group.class);
list.add(group);
Log.d("TAG", group.getGroupName());
}
adapter.notifyDataSetChanged();
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
In this way, you'll only download the documents that match the query and nothing more. Otherwise it will be a waste of resources and bandwidth.

How to read data from Firebase Database? - Java

I'm making a game, if the player wins, then the victory is added to the database. How can I read the data from here?
and paste here:
I read the player's name in a different way, which cannot be repeated with victories and defeats.
To be able to read the data under the jjjj node, please use the following lines of code:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference nameRef = db.child("players").child("jjjj");
nameRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
DataSnapshot snapshot = task.getResult();
String loses = snapshot.child("loses").getValue(Long.class);
String name = snapshot.child("name").getValue(String.class);
String wins = snapshot.child("wins").getValue(Long.class);
Log.d("TAG", loses + "/" + name + "/" + wins);
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
The result in the logcat will be:
3/jjjj/4
Things to notice:
Always create a reference that points to the node that you want to read.
If your database is located in another lcoation than the default, check this answer out.
use this method
This is the method of fetching data from the firebase realtime database
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
reference.child("players").child(name).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});

How do I display this firebase branch's data to app?

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.

"println needs a message" error in android

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
}
});

getvalue() in query return null from Firebase Realtime Database

the databas
setContentView(R.layout.activity_main);
Button readBtn = (Button) findViewById(R.id.readBtn);
EditText testInputTxt = (EditText) findViewById(R.id.testInputTxt);
rootRef = FirebaseDatabase.getInstance().getReference().child("Login");
Query query = rootRef.orderByChild("LoginUserName").equalTo(testInputTxt.getText().toString());
readBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String passwordUser = snapshot.child("LoginPassword").getValue(String.class);
testInputTxt.setText(passwordUser+"tatata");
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
the query works fine it detects that the user is existexists but i wanted to retrieve the value of LoginPassword but it returns null i tried the for DataBase....:snapshot code but it won't detect
Since you are using a Query object, it means that you can potentially get multiple results from the database. That being said, you have to loop through the results using a call to .getChildren() as seen in the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference loginRef = rootRef.child("Login");
Query query = loginRef.orderByChild("LoginUserName").equalTo(testInputTxt.getText().toString());
query.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
String passwordUser = ds.child("LoginPassword").getValue(String.class);
testInputTxt.setText(passwordUser+"tatata");
}
} else {
Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
}
}
});
Please also note that if two users have the same "LoginUserName", then your TextView will always display the value of the last one. So always be sure to have unique user names. To check if a user name already exists, please check my answer from the following post:
Checking if a particular value exists in the Firebase database

Categories