Yugen
Yugen

Reputation: 23

Retrieving data from nested nodes in Firebase Database

This is my database structure:

enter image description here

All the children of the Request node are timestamps. For a particular timestamp, within the product node, i want to retrieve all the values of the object productName. And then arrange them so that it is composed as the body of an email. The part where i am stuck at is in fetching the data of productName.

So far i've been able to fetch the data of the total in the second node. the code i'm using is this:

    DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Requests");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        collectProducts((Map<String, Object>) dataSnapshot.getValue());
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});



private void collectProducts(Map<String, Object> value) {

    ArrayList<String> products = new ArrayList<>();
    for (Map.Entry<String, Object> entry : value.entrySet()){
        Map singleUser = (Map) entry.getValue();
        products.add((String) singleUser.get("total"));
    }

    Intent emailIntent = new Intent(Intent.ACTION_SEND);
    emailIntent.setType("plain/text");
    emailIntent.putExtra(Intent.EXTRA_EMAIL, "[email protected]");

    StringBuilder sb = new StringBuilder();
    for (String s : products) {
        sb.append(s);
        sb.append("\n");
    }
    emailIntent.putExtra(Intent.EXTRA_TEXT, sb.toString());

    try {
        startActivity(Intent.createChooser(emailIntent, "Send mail..."));
        Log.i("Email sent!", "");
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(Cart.this,
                "There are no email clients installed.", Toast.LENGTH_SHORT).show();
    }

}

But no luck with getting productName.

I am new to Android and Firebase. Any help is appreciated.

Upvotes: 0

Views: 1514

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

Something like this should do the trick:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Requests");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot requestSnapshot: dataSnapshot.getChildren()) {
      DataSnapshot productsSnapshot = requestSnapshot.child("products");
      for (DataSnapshot productSnapshot: productsSnapshot.getChildren()) {
        System.out.println(productSnapshot.child("productName").getValue(String.class));
      }
    }
  }

  @Override
  public void onCancelled(DatabaseError databaseError) {
    throw databaseError.toException(); // don't ignore errors
  }
});

Main differences:

  • It throws an explicit error when the user doesn't have permission on the data.
  • It uses DataSnapshot.getChildren() to loop over children.
  • It uses DataSnapshot.child() to address a specific child snapshot.
  • It uses DataSnapshot.getValue() to retrieve the primitive/String value.

Upvotes: 2

Related Questions