jeudi 18 mars 2021

Values from checkboxes not working in Android

I have made a test app. When one or more checkboxes are selected and a button is clicked, the numbers corresponding to the checkboxes should get added up and displayed in a textView (which initially displays 0).

MainActivity.java :

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        CheckBox rice = findViewById(R.id.rice);
        boolean ateRice = rice.isChecked();

        CheckBox egg = findViewById(R.id.egg);
        boolean ateEgg = egg.isChecked();

        CheckBox bread = findViewById(R.id.bread);
        boolean ateBread = bread.isChecked();

        int cal = countCal(ateRice, ateEgg, ateBread);
        String calString = String.valueOf(cal);

        Button calculate = findViewById(R.id.calculate);

        calculate.setOnClickListener(view -> {
            TextView numCal = findViewById(R.id.cal);
            numCal.setText(calString);
        });

    } //onCreate

    private int countCal(boolean ateRice, boolean ateEgg, boolean ateBread) {
        int calories = 0;
        if(ateRice){
            calories = calories + 20;
        }
        if(ateEgg){
            calories = calories + 50;
        }
        if(ateBread){
            calories = calories + 10;
        }
        return calories;
    } //countCal

}

But when I click the button, nothing happens and the textView keeps displaying 0. What should I do?

(Here's how the app looks)




Aucun commentaire:

Enregistrer un commentaire