我正在LG Eve手机上测试我的应用程序。我有一个尝试从网络上下载内容的应用程序,当它引发异常时,应该启动一个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);
       }


}

最佳答案

不要在doInBackground中显示对话框。该方法不在UI线程上运行。尝试在onPostExecute或onProgressUpdate上显示错误对话框。

08-18 06:31
查看更多