Waugh
Waugh

Reputation: 213

How to add values of multiple edittexts in android?

I am creating dynamic layout in my code. My UI has multiple rows which are dynamically created at runtime. Each row consists of single edit text. I have created single edit text object and used this object to add in multiple rows.

Lets assume that there are 5 rows so there are 5 edit texts. User can enter/delete numbers in any of the edittext. Depending on what user enters in respective edittexts, I want to update the label.The label should contain addition of all edittext values.

I am calling following function on edit text afterTextChanged callback method.

private void refreshTotalNumberOfDays(Editable editable){

    if(!(editable.length()==0)){
        totalDays = Integer.parseInt(editable.toString());  
    }

    finalTotalDays =totalDays+finalTotalDays;
    ftotalNumberOfDays.setText(String.valueOf(finalTotalDays));
}

But its not adding values correctly.

Upvotes: 1

Views: 2438

Answers (1)

HalR
HalR

Reputation: 11083

You need to change to this:

totalDays = Integer.parseInt(editable.getText().toString());

It should give you the proper integer value.

To total all of them, keep an array of all the editTexts.

Make the array when you create the Activity

ArrayList<EditText> editTextArrayList = new ArrayList<EditText>();
editTextArrayList.add(editText1);
editTextArrayList.add(editText2);
...

Then on your callback Method, total them all up:

int total = 0;
for (EditText editText:editTextArrayList) {
    total +=  Integer.parseInt(editText.getText().toString());
}

Upvotes: 0

Related Questions