Please help, I want to create 30 edit text and get the sum of them. Currently, I am able to get the sum however this only work for whole number. when I enter decimal value the sum is not accurate. And the program crash when I delete the value in any one of the edit text, please advise on how I can prevent that. thank you!
for (int i = 1; i < 31; i++) {
EditText editText = new EditText(this);
editText.setHint("Recording Length: " + "#" + i);
editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
editSampling.addView(editText);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
List<Double> getAverageLength= new ArrayList<Double>();
String text = editText.getText().toString();
double value = Double.parseDouble(text);
getAverageLength.add(value);
double sum = 0;
for (int m = 0; m < getAverageLength.size(); m++)
sum = sum + getAverageLength.get(m) / getAverageLength.size();
String toString = String.valueOf(sum);
avgLength.setText(toString);
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
The program logic is slightly faulty. Just use the following code:
EDIT: I forgot to point out the fault in your code. In your onTextChanged, you have re-initialised the list and appended only the current EditText's reading onto it. This may return the wrong sum. Moreover, you did not check whether the EditText's text string was null or blank. I don't see how this will fix your exact problem, though.