空の edittext フィールドが 2 つあり、2 つのフィールド内に数字を入力すると、3 番目の textview が上記の 2 つの edittext の分割を自動的に取得します。そのため、それを計算するためのボタンなどはありません。
問題は、任意のフィールドに 1 つの数字を入力すると、アプリが強制的に閉じられることです。これが私のコードとlogcatです:
amount.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable arg0) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
AddFuelActivity.this.updateValue();
}
});
litres.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable arg0) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
AddFuelActivity.this.updateValue();
}
});
protected void updateValue() {
int amountInt = Integer.parseInt(amount.getText().toString());
int litresInt = Integer.parseInt(litres.getText().toString());
float priceFuelAuto = 0;
priceFuelAuto = amountInt / litresInt;
fuelPrice.setText("€ " + priceFuelAuto);
}
logcat エラー: これらは重要なものだと思います。
01-22 13:23:21.650: E/AndroidRuntime(671): java.lang.NumberFormatException: Invalid int: ""
01-22 13:23:21.650: E/AndroidRuntime(671): at java.lang.Integer.invalidInt(Integer.java:138)
01-22 13:23:21.650: E/AndroidRuntime(671): at java.lang.Integer.parseInt(Integer.java:359)
01-22 13:23:21.650: E/AndroidRuntime(671): at java.lang.Integer.parseInt(Integer.java:332)
01-22 13:23:21.650: E/AndroidRuntime(671): atcom.example.mycarfuel.AddFuelActivity.updateValue(AddFuelActivity.java:155)
01-22 13:23:21.650: E/AndroidRuntime(671): atcom.example.mycarfuel.AddFuelActivity$2.onTextChanged(AddFuelActivity.java:67)
コードを修正しました。これが私がしたことです:
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (litres.length() > 0) {
AddFuelActivity.this.updateValue();
}
}
と
int amountInt = 0;
int litresInt = 0;
try {
amountInt = Integer.parseInt(amount.getText().toString());
litresInt = Integer.parseInt(litres.getText().toString());
} catch (NumberFormatException e) {
litresInt = 0;
amountInt = 0;
}
if(amountInt !=0 && litresInt != 0){
float priceFuelAuto = 0;
priceFuelAuto = amountInt / litresInt;
fuelPrice.setText("€ " + priceFuelAuto);
}
返信ありがとうございます