lundi 18 mai 2020

How to get the key of a child node in Firebase Realtime Database after choosing a child randomly

I want to get the key of the child node in the Firebase Realtime Database, which is also the UID. I am randomly choosing a child node and now I want to get the key of that child so that I can do further operations on it.

databaseReferencePickers.addListenerForSingleValueEvent(new ValueEventListener() {
     @Override
     public void onDataChange(DataSnapshot dataSnapshot) {
         try {
            int pickerCount = (int) dataSnapshot.getChildrenCount();
            Random random = new Random();
            int rand = random.nextInt(pickerCount);
            Iterator itr = dataSnapshot.getChildren().iterator();

            for(int i = 0; i <= rand; i++) {
                itr.next();
            }

            pickerDetails = itr.next().toString();

            ObjectMapper oMapper = new ObjectMapper();
            map = oMapper.convertValue(itr.next(), Map.class);
            //pickerUID = Objects.requireNonNull(map.get("key")).toString();
            pickerUID = dataSnapshot.getKey();
            Toast.makeText(OrderPickupActivity.this,pickerUID,Toast.LENGTH_LONG).show();

         } catch (Exception e) {
              Toast.makeText(OrderPickupActivity.this, e.toString(), Toast.LENGTH_LONG).show();
         }
     }

     @Override
     public void onCancelled(DatabaseError databaseError) {

     }
});

Can you please help me with it? Whenever I Toast the value of "PickerUID", I get the value as null.

Here is the image.

I want to retrieve the key from the pickers section.




Aucun commentaire:

Enregistrer un commentaire