我在LG Eve手机上测试我的应用程序。我有一个应用程序试图从Web下载一些东西,当它抛出一个异常时,它应该启动一个alertdialog说有一个错误。当手机没有wifi信号时,程序会在builder.create()崩溃(见下面的代码)。但是,当有wifi信号,并且异常被其他东西抛出时(例如,url中的拼写错误),对话框将启动它应该的方式。任何线索,为什么会这样?
onCreateDialog的代码:
@Override
protected Dialog onCreateDialog(int id){
Dialog d = null;
switch (id){
case DIALOG_DATA_ERROR_ID:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(getResources().getString(R.string.error_data));
builder.setCancelable(false);
builder.setNeutralButton("OK", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface d, int id){
d.cancel();
}
});
d = builder.create();
break;
}
return d;
}
调用showDialog的AsyncTask代码:
private static class DownloadJSONTask extends AsyncTask<String, Void, String>{
private ProgressDialog dialog;
private Activity parent;
private JSONParserInterface jsonParser;
public DownloadJSONTask(Activity parent, JSONParserInterface jsonParser){
this.parent = parent;
this.jsonParser = jsonParser;
}
protected void onPreExecute(){
dialog = ProgressDialog.show(parent, "Loading", "Please Wait...", true);
}
protected String doInBackground (String... urls){
try {
return HttpHelper.getResponse(urls[0]);
}catch (Exception e){
dialog.cancel();
parent.showDialog(BoomSetListActivity.DIALOG_DATA_ERROR_ID);
}
return null;
}
protected void onPostExecute(String json){
dialog.cancel();
if (jsonParser != null) jsonParser.parse(json);
}
}
答案 0 :(得分:6)
不要在doInBackground上显示对话框。该方法不在UI线程上运行。尝试在onPostExecute或onProgressUpdate上显示错误对话框。