[英]java.lang.NumberFormatException: Invalid int: “” (parsing)
The listed error occurs to this: (just a basic calorie calculator- enter #s in it updates the TextView of calorieTotal)((It might be better served with a button?)) 出现以下错误:(只需一个基本的卡路里计算器,在其中输入#即可更新卡路里总值的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));
}
make your editText as a numberic, to avoid invalid input and accept only numbers 将您的editText设为数字,以避免输入无效并仅接受数字
add android:inputType="number"
at the xml attributes. 在xml属性中添加android:inputType="number"
。
<EditText
android:id="@+id/myNumber"
android:digits="0123456789."
android:inputType="numberDecimal"
/>
in your layout xml, add given code to all edittext, in which you want only number 在布局xml中,将给定代码添加到所有edittext中,您只需要数字
android:digits="0123456789"
it will allows your edittext for only number, so NumberFormatException will not occur. 它将只允许您的edittext数字,因此不会发生NumberFormatException。
Before parsing into integer add a condition whether value is empty or not 在解析为整数之前,添加一个条件,值是否为空
if(TextUtils.isEmpty(breakfastCals.getText().toString()) {
n1=0;
}else{
n1= Integer.parseInt(breakfastCals.getText().toString());
}
Do this for all edittext 对所有edittext执行此操作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.