Home > Software engineering >  Retrieve info from firebase
Retrieve info from firebase

Time:11-05

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

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

CodePudding user response:

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