Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Retrieve info from firebase

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) {

        }
    });

firebase tree

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried to edit with your code, but i dont have get() on my list.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading