Android开发:30个EditText小数求和异常及崩溃问题求助
Solution to Your EditText Sum/Average Calculation Issues
Hey Janice, let's fix those three headaches you're facing with your 30 EditTexts—crashing when deleting content, wonky decimal calculations, and incorrect sum logic. Here's a step-by-step breakdown and corrected code to get everything working right:
Root Causes of Your Problems
- Crash on delete: When you clear an EditText, you’re trying to parse an empty string with
Double.parseDouble(), which throws aNumberFormatExceptionand crashes your app. - Wrong calculation logic: Your current code only processes the single EditText that’s being edited, not all 30 inputs. That’s why it seemed to work for integers (it just showed the current input) but broke when dealing with decimals or multiple filled fields.
- Decimal display issues: Without proper formatting, floating-point calculations can show messy, imprecise decimal values.
Corrected Code with All Fixes
// Keep a reference to all EditTexts so we can iterate through them later List<EditText> allEditTexts = new ArrayList<>(); 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); allEditTexts.add(editText); // Store each EditText in a list for later use 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) { updateTotalSum(); // Delegate calculation to a clean, reusable method } @Override public void afterTextChanged(Editable s) { } }); } // Separate method to handle sum calculation and display private void updateTotalSum() { double totalSum = 0.0; // Loop through every EditText to calculate the full sum for (EditText et : allEditTexts) { String text = et.getText().toString().trim(); // Skip empty fields to avoid crashes and wrong values if (text.isEmpty()) { continue; } try { double value = Double.parseDouble(text); totalSum += value; } catch (NumberFormatException e) { // Catch invalid input (though the input type should prevent non-numeric text) e.printStackTrace(); } } // Format the result to 2 decimal places for clean display String formattedSum = String.format("%.2f", totalSum); avgLength.setText(formattedSum); }
Key Changes Explained
- Track all EditTexts: We store every EditText in a list so we can loop through all inputs whenever any text changes—this ensures we calculate the true sum of all 30 fields.
- Crash prevention: We check for empty strings before parsing, and wrap the parse in a try-catch block to handle any unexpected invalid input.
- Cleaner code structure: Moving the calculation logic to a separate method makes the code easier to read and modify later.
- Decimal formatting:
String.format("%.2f", totalSum)ensures decimal values display neatly (adjust the number of decimal places as needed for your use case).
Quick Bonus Tip
If you actually wanted to calculate the average instead of the sum (based on your variable names like avgLength), just add a counter for valid inputs and adjust the calculation:
int validInputCount = 0; // ... inside the loop ... validInputCount++; // ... after the loop ... double average = validInputCount > 0 ? totalSum / validInputCount : 0.0; String formattedAvg = String.format("%.2f", average); avgLength.setText(formattedAvg);
内容的提问来源于stack exchange,提问作者Janice goh
相关产品推荐
相关产品推荐

