[英]AlertDialog Force Close with EditText
I got the error: 我得到了错误:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.crmdev.circuitorlcparalelo, PID: 6778
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference
at com.crmdev.circuitorlcparalelo.MainActivity$3.onClick(MainActivity.java:70)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6626)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)
For the following code with AlertDialog: 对于带有AlertDialog的以下代码:
AlertDialog.Builder result = new AlertDialog.Builder(MainActivity.this);
result.setTitle("Iterações");
result.setMessage("Digite o número de iterações desejadas: ");
final EditText iteracoes = new EditText(this);
iteracoes.setInputType(InputType.TYPE_CLASS_NUMBER);
iteracoes.setGravity(9);
iteracoes.setPadding(10,10,10,10);
result.setView(iteracoes);
result.setPositiveButton("Calcular", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if(iteracoes.getText().equals("")){
Toast.makeText(getApplicationContext(), "Digite algum valor para as iterações!", Toast.LENGTH_LONG).show();
iteracoes.setText("");
}
else{
//Pega o numero de iterações
iteracao = Integer.getInteger(iteracoes.getText().toString());
tensaof = onCalculo(iteracao);
Bundle dad = new Bundle();
dad.putDouble("resultado", tensaof);
Intent intent = new Intent(MainActivity.this, ResultActivity.class);
intent.putExtras(dad);
startActivity(intent);
}
}
});
result.show();
Every time i press the button Calcular the applicantion Force Close's, I change the function onCalculo but continues the same way. 每次我按一下Calcular申请人的“强制关闭”按钮时,我都会更改onCalculo函数,但会以相同的方式继续。 When the function onCalculo only altered a TextView , the application did not have this problem.
当函数onCalculo仅更改TextView时 ,应用程序没有此问题。 I can't see what's going wrong.
我看不到出了什么问题。 Thanks.
谢谢。
Because you are using wrong method to parse from a String
to an Integer
. 因为您使用错误的方法将
String
解析为Integer
。 You should you 你应该
iteracao = Integer.parseInt(iteracoes.getText().toString());
instead of 代替
iteracao = Integer.getInteger(iteracoes.getText().toString());
By the way parseInt
method might throws NumberFormatException
so you should put in a try/catch
block to prevent the app from crashing. 顺便说一句,
parseInt
方法可能会引发NumberFormatException
因此您应该放入try/catch
块中,以防止应用程序崩溃。
Integer iteracao = null;
try {
iteracao = Integer.parseInt(iteracoes.getText().toString());
} catch (NumberFormatException e) {
// TODO: Show a toast to let users know the input value is not valid
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.