I am trying to show a al开发者_JS百科ert box in my app when numberformat exception occurs but for some reason the app crashes
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
preRes = new Double(field1.getText().toString());
lastCommand = "+";
field1.setText("");
count = 0;
} catch (NumberFormatException e) {
show = new AlertDialog.Builder(mContext)
.setTitle("Error")
.setMessage("no inputs").setPositiveButton("OK", null).show();
}
}
});
I believe you have to create the Builder before you can begin setting properties. Try something like this (Assuming show
is an AlertDialog):
show = new AlertDialog.Builder(mContext).create();
show.setTitle("Error")
.setMessage("no inputs")
.setPositiveButton("OK", null)
.show();
You miss following after creating your AlertDialog.Builder
AlertDialog alert = show .create();
alert.show();
If you are getting a Null Pointer, try using new AlertDialog.Builder(getContext())..
or new AlertDialog.Builder(this)..
. You might have missed initialing the mContext
field.
If that doesn't work, try
show = new AlertDialog.Builder(mContext)
.setTitle("Error")
.setMessage("no inputs").setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
captureImage();
}
}
).show();
Likely an unchecked exception other than NumberFormatException
is being thrown, for example NullPointerException
.
A NPE could be thrown if either field1
or mContext
are not properly initialized.
Regardless, you need to get logcat working so you can debug the problem. The stacktrace will point you to where the error is occuring.
To open logcat in Eclipse, go to Window > Show View > Other... and select the logcat view.
Alternatively you can access the logcat view from Window > Open Perspective > Other... and select the DDMS perspective.
精彩评论