How to add multiple integer values from firebase in Android Studio

Viewed 32

Here is my main HomeActivity and AddUserDetails class to handle this.

Can you please give me some suggestions so that my app will not crash and I can total the sum of integer values.

        public class homePage extends AppCompatActivity {
        
            TextView cashValue;
            DatabaseReference TotalIncome;
    
        @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_home_page);
                cashValue = findViewById(R.id.cashValue);
        
                TotalIncome = FirebaseDatabase.getInstance().getReference("Add Income User Data");
                getData();
        
            }
        
            private  void getData(){
                TotalIncome.addValueEventListener(new ValueEventListener() {
                    
         @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                        Integer total=0;
        
                        for (DataSnapshot dataSnapshot:snapshot.getChildren()){
                            AddUserDetails userdata = dataSnapshot.getValue(AddUserDetails.class);
                            Integer cost = Integer.valueOf(userdata.getAmount());
                            total = total+cost;
                        }
        
                        cashValue.setText(""+total);
        
                    }
        
                    @Override
                    public void onCancelled(@NonNull DatabaseError error) {
        
                    }
                });
        
            }
        
        }

Please see an image from my firebase enter image description here

1 Answers

You added a direct integer to textView that's why it throws Resources$NotFoundException exeption. Just change your textView code from

cashValue.setText(""+total);

to this below

cashValue.setText(String.valueOf(total));

Let me know if not solved yet.

Related