This is the piece of code that performs a check on the values entered in a table of EditText, if I’m wrong to enter the values, shows me the alertdialog properly, I correct the input, press again the button to complete the input and the app crashes, Why?
button = new Button(this);
button.setText("Riempi la prima Matrice");
tableLayout.addView(button);
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
try {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
array[t] = Double.parseDouble(values[i][j].getText().toString());
t++;
}
}
}
catch (NumberFormatException nfe) {
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(SecondaAttivita.this);
builder.setTitle("Error");
builder.setMessage("Wrong input format");
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setNeutralButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {}
});
builder.show();
}
}
});
This is a logCat
FATAL EXCEPTION: main
java.lang.ArrayIndexOutOfBoundsException
it.bisemanuDEV.prodMatrix.SecondaAttivita$1.onClick(SecondaAttivita.java:96)
android.view.View.performClick(View.java:2408)
android.view.View$PerformClick.run(View.java:8816)
android.os.Handler.handleCallback(Handler.java:587)
android.os.Handler.dispatchMessage(Handler.java:92)
android.os.Looper.loop(Looper.java:123)
android.app.ActivityThread.main(ActivityThread.java:4627)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:521)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
dalvik.system.NativeStart.main(Native Method)
According to your stack trace, when it tries to assign the double to
array[t], it fails because the indextis not valid for the arrayarray.edit: After taking into consideration @Gophermofur’s comment, if the rest of your code outside of this snippet is correct, to fix it, reset
tinside the catch block. e.g. iftstarted as 0, reset it to 0 when theNumberFormatExceptionis caught.2nd edit: if the values are allowed to be edited even after accepting correct input, you probably want to stick the reset of
tinto afinallyblock after the catch instead of inside the catch.