Home > other >  Get specific values from Firebase Realtime and collect their values
Get specific values from Firebase Realtime and collect their values

Time:10-19

How do I get specific values from Firebase Realtime and collect all of them to show the user the total value of all children inside the sales list android studio - with java

Get specific values from Firebase Realtime and collect their values android studio - with java

enter image description here

public class SalesFragment extends Fragment {

TextView otherSalesValue, otherEarnsValue;

DatabaseReference databaseReference;

int sale;

String currentUserId;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_sales, container, false);

    currentUserId = FirebaseAuth.getInstance().getCurrentUser().getUid();

    databaseReference = FirebaseDatabase.getInstance().getReference("sales");

    otherSalesValue = root.findViewById(R.id.other_sales_value);
    otherEarnsValue = root.findViewById(R.id.other_earns_value);

    databaseReference.child(currentUserId)
            .addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot uniqueKeySnapshot : dataSnapshot.getChildren()) {
                for (DataSnapshot booksSnapshot : uniqueKeySnapshot.child("total").getChildren()) {
                    String sales = booksSnapshot.getValue(String.class);
                    try {
                        sale = Integer.parseInt(sales);
                    } catch (NumberFormatException ex) {
                        ex.printStackTrace();
                    }

                    sale =  sale;

                    otherEarnsValue.setText(String.valueOf(sale));
                }
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    return root;
}

}

CodePudding user response:

The sales node you read has two dynamic child levels under it, so you need two nested loops over getChildren() before you can get the total property.

databaseReference.child(currentUserId)
        .addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
            for (DataSnapshot dateSnapshot : userSnapshot.getChildren()) {
                                                     //            
  • Related