我有一个问题,我无法解决,并且老师的解决方案不起作用。当EditText为空时Android应用程序崩溃
问题是当我点击“检查答案”并没有写在EditText
,程序崩溃。我在Android Studio工作。
Java代码:
public class Main extends AppCompatActivity {
int a, b, c, d;
Button Enter, NewExercise, EndLesson;
EditText et;
TextView tv;
ImageView iv;
String st;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
et = (EditText) findViewById(R.id.et);
iv = (ImageView) findViewById(R.id.iv);
a = (int)(10 * Math.random());
b = (int)(10 * Math.random());
c = a + b;
tv.setText("Exmaple: " + a + " + " + b);
et.setText("" + c);
}
public void Show(View view) {
a = (int)(10 * Math.random());
b = (int)(10 * Math.random());
c = a + b;
tv.setText("" + a + " + " + b);
et.setText("");
}
public void Check(View view) {
st = et.getText().toString();
d = Integer.parseInt(st);
if(0 == et.length()) {
Toast.makeText(this,"Please, enter the answer",Toast.LENGTH_LONG).show();
}
if (d == c) {
iv.setImageResource(R.drawable.t);
Toast.makeText(this, "Right", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(this, "False", Toast.LENGTH_LONG).show();
iv.setImageResource(R.drawable.f);
et.setText("");
}
}
}
XML:
<TextView
android:layout_width="wrap_content"
android:textSize="30dp"
android:textColor="#000000"
android:layout_height="wrap_content"
android:id="@+id/tv" />
<ImageView
android:layout_width="match_parent"
android:layout_height="71dp"
app:srcCompat="@drawable/eq"
android:id="@+id/eq" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:textSize="30dp"
android:hint="Enter the answer"
android:ems="10"
android:maxLength="3"
android:gravity="center"
android:id="@+id/et"
android:layout_weight="0.13" />
<ImageView
android:layout_width="match_parent"
android:layout_height="48dp"
app:srcCompat="@drawable/t"
android:id="@+id/iv"
android:layout_weight="0.12" />
<Button
android:text= "Check the answer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="Check"
android:id="@+id/CheckTheAnswer" />
<Button
android:text= "New Exercise"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="Show"
android:id="@+id/NewExercise" />
<Button
android:text="End lesson"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="Exit"
android:id="@+id/EndLesson" />
我为我的英语很抱歉。先谢谢你。
在android日志中是否有任何异常stacktrace? – aleb2000
你应该检查你的et.getText值不应该为null!然后处理它! – hamidrezabstn
此外,当将字符串转换为int时,您应该检查NumberFormatException: 'try {d = Integer.parseInt(st); (NumberFormatException e){ e.printStackTrace(); }' – aleb2000