如果用户输入的数字大于Integer数据类型可以处理的数字,我试图从AlertDialog中捕获NumberFormatException。我尝试了以下代码,但我没有找到成功。我试图在setOnItemClickListener方法中捕获异常。
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) throws RuntimeException{
try{
builder= new AlertDialog.Builder(IzbiraHrane.this);
builder.setTitle("Enter your quantity");
// Set up the input
final EditText input = new EditText(IzbiraHrane.this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_NUMBER);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
kolicina = input.getText().toString();
Intent returnIntent = new Intent();
returnIntent.putExtra("kolicina",kolicina);
returnIntent.putExtra("id",id_ji.get(position));
setResult(Activity.RESULT_OK,returnIntent);
finish();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}catch(Exception e){
Toast.makeText(IzbiraHrane.this, "something", Toast.LENGTH_SHORT).show();
}
}
});
答案 0 :(得分:1)
我正在尝试捕获NumberFormatException
为什么不在alertDialog
中处理结果并处理异常。
试试这段代码:
int number = 0; //declare varible
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
try {
if(input.getString().toString().Trim().lenght()>0) //not empty
{
if(Integer.parseInt(input.gettext().toString()) <= 100000 ) //your Int bounds
{
kolicina = input.getText().toString();
number = Integer.parseInt(kolicina);
Intent returnIntent = new Intent();
returnIntent.putExtra("kolicina",kolicina);
returnIntent.putExtra("id",id_ji.get(position));
setResult(Activity.RESULT_OK,returnIntent);
finish();
}
}
} catch (NumberFormatException e) {
}
}
});
在这里,您可以处理edittext
输出字符串以检查它是否在您所需的范围内。还可以轻松捕获Exception
。
答案 1 :(得分:0)
我试图从AlertDialog中捕获NumberFormatException,如果是 用户输入的数字大于Integer数据类型可以处理的数字。
您可以使用 Math.toIntExact() 方法检查是否存在整数溢出/下溢。
示例,类似于以下内容:
try {
int myValue = Math.toIntExact(Long.parseLong(kolicina));
// do something
} catch (ArithmeticException e) {
// if it gets here then there is integer overflow/underflow.
} catch(NumberFormatException e){
// if it gets here then the data entered is not a valid number.
}
Math.toIntExact() - 返回long参数的值;投掷 如果值溢出int,则为异常。