java.lang.NumberFormatException:无效的int:"" (解析)

时间:2015-03-31 03:22:57

标签: java android parsing

列出的错误发生在:(只是一个基本的卡路里计算器 - 在其中输入#s更新calorieTotal的TextView)((最好用按钮服务?)

public class MainActivity extends ActionBarActivity {
EditText breakfastCals;
EditText lunchCals;
EditText dinnerCals;
EditText otherCals;
EditText burnedCals;
TextView calorieTotal;

int n1=0;
int n2=0;
int n3=0;
int n4=0;
int n5=0;
int total=0;

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


    breakfastCals = (EditText) findViewById(R.id.breakfastCals);
    n1= Integer.parseInt(breakfastCals.getText().toString());

    lunchCals = (EditText) findViewById(R.id.lunchCals);
    n2= Integer.parseInt(lunchCals.getText().toString());

    dinnerCals = (EditText) findViewById(R.id.dinnerCals);
    n3= Integer.parseInt(dinnerCals.getText().toString());

    otherCals = (EditText) findViewById(R.id.otherCals);
    n4= Integer.parseInt(otherCals.getText().toString());

    burnedCals = (EditText) findViewById(R.id.burnedCals);
    n5= Integer.parseInt(burnedCals.getText().toString());

    total=((1500-n1-n2-n3-n4)+n5);
    calorieTotal= (TextView) findViewById(R.id.calorieTotal);
    calorieTotal.setText(Integer.toString(total));

}

3 个答案:

答案 0 :(得分:0)

将您的editText设为数字,以避免无效输入并仅接受数字

在xml属性中添加android:inputType="number"

<EditText
android:id="@+id/myNumber"
android:digits="0123456789."
android:inputType="numberDecimal"
/>

答案 1 :(得分:0)

在布局xml中

,将给定代码添加到所有edittext中,其中只需要数字

android:digits="0123456789"

它将允许您的edittext仅用于编号, 所以不会发生NumberFormatException。

答案 2 :(得分:0)

在解析为整数之前,添加值是否为空的条件

if(TextUtils.isEmpty(breakfastCals.getText().toString()) {
n1=0;
}else{

n1= Integer.parseInt(breakfastCals.getText().toString()); 
}

为所有edittext

执行此操作