在读取网络文件时,有时候因为网络文件不能被访问导致出现Exception,这时想弹出一个alertdialog,但是发现打开app后,app马上强制退出了。错误代码如下:
new Thread(new Runnable() {
@Override
public void run() {
try {
list=readExcel();
} catch (IOException e) {
AlertDialog.Builder dialog3 = new AlertDialog.Builder(MainActivity.this);
dialog3.setTitle("错误:");
dialog3.setMessage("错误文字");
dialog3.setCancelable(false);
dialog3.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
dialog3.create().show();
}
}
}).start();
想要弹出alertdialog,必须利用如下方式,先将上面的代码变为:
new Thread(new Runnable() {
@Override
public void run() {
try {
list=readExcel();
} catch (IOException e) {
e.printStackTrace();
showTestDialog();
}
}
}).start();
再定义方法showTestDialog(),则可在不用强制退出app的情况下弹出alertdialog:
public void showTestDialog() {
handler.post(new Runnable() {
@Override
public void run() {
AlertDialog.Builder dialog3 = new AlertDialog.Builder(MainActivity.this);
dialog3.setTitle("错误:");
dialog3.setMessage("错误文字");
dialog3.setCancelable(false);
dialog3.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
dialog3.create().show();
}
});
}