Search code examples
android-recyclerviewsum

How to get sum of a item inside recyclerview?


Suppose two Items 8 and 4 are there in the list. So the Sum I should get is 12. But I am getting result as 84 and not 12. I am a beginner So I don't have an idea what wrong I am doing here.

private void getCreditEntries() {

    final String shift = kvName.getText().toString();
    final String leaveType = selectLeaveType.getSelectedItem().toString();
    final String employeeCode = empCode.getText().toString();
    final String calendarYear = selectYear.getText().toString();

    DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("LeaveDetails").child(shift)
            .child("Credit").child(employeeCode).child(calendarYear);
    DatabaseReference dbRef = reference.child(leaveType);

    dbRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            list = new ArrayList<>();
            if (!dataSnapshot.exists()) {
                creditEntryLayout.setVisibility(View.GONE);
            } else {
                creditEntryLayout.setVisibility(View.VISIBLE);
                for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
                    LeaveCreditData data = snapshot.getValue(LeaveCreditData.class);
                    list.add(data);
                }
                rvCreditEntry.setHasFixedSize(true);
                rvCreditEntry.setLayoutManager(new LinearLayoutManager(LeaveDetails.this));
                rvCreditEntry.setItemAnimator(new DefaultItemAnimator());
                leaveCreditAdapter = new LeaveCreditAdapter(list, LeaveDetails.this);
                rvCreditEntry.setAdapter(leaveCreditAdapter);
                int total = 0;
                for(int i = 0; i < list.size(); i++){
                    total = Integer.parseInt(total + list.get(i).getTotalLeaveCredit());
                    creditSum.setText(String.valueOf( total));

                     //Suppose two Items 8 and 4 are there in the list
                    // So the Sum I should get is 12.
                   // But I am getting result as 84 and not 12
                }
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Toast.makeText(LeaveDetails.this, databaseError.getMessage(), Toast.LENGTH_LONG).show();
        }
    });

}

Solution

  • I simply edited the code as below and achieved what I wanted.

     int total = 0;
                    for(int i = 0; i < list.size(); i++){
                        total += Integer.parseInt(list.get(i).getTotalLeaveCredit());
                        creditSum.setText(String.valueOf( total));
                }