Android,如何从try catch的错误中显示一个对话框?

时间:2012-06-08 18:23:49

标签: java android eclipse try-catch

在我的应用程序中,我连接到一个网站,在AsyncTask开始时使用try catch收集一些信息,从这里我可以在我的catlog中显示错误,如果有任何连接,但我一直在试着运气好显示一个显示连接失败的对话框以及重新连接或退出的选项,请检查我的代码并告诉我我做错了什么或者想知道如何实现这个

 //this is our download file asynctask
class DownloadFileAsync extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(DIALOG_DOWNLOAD_PROGRESS);
    }

    @Override
    protected String doInBackground(String... aurl) {

        try {
        String result = "";
                    try {
                        HttpClient httpclient = new DefaultHttpClient();
                        HttpPost httppost = new HttpPost("http://mywebsiteaddress");
                        // httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                        HttpResponse response = httpclient.execute(httppost);
                        HttpEntity entity = response.getEntity();
                        InputStream webs = entity.getContent();
                        // convert response to string
                        try {
                            BufferedReader reader = new BufferedReader(
                                    new InputStreamReader(webs, "iso-8859-1"), 8);
                            StringBuilder sb = new StringBuilder();
                            String line = null;
                            while ((line = reader.readLine()) != null) {
                                sb.append(line + "\n");
                            }
                            webs.close();

                            result = sb.toString();
                        } catch (Exception e) {
                            Log.e("log_tag", "Error converting result " + e.toString());
                        }
                    } catch (Exception e) {
                        Log.e("log_tag", "Error in http connection " + e.toString());
                    }

                    // parse json data
                    try {
                        JSONArray jArray = new JSONArray(result);
                        for (int i = 0; i < jArray.length(); i++) {
                            JSONObject json_data = jArray.getJSONObject(i);
                            webResult resultRow = new webResult();
                            //infotodownload
                            arrayOfWebData.add(resultRow);

                        }
                    } catch (JSONException e) {
                        Log.e("log_tag", "Error parsing data " + e.toString());
                    }
    } catch (Exception e) {
        // this is the line of code that sends a real error message to the
        // log
        Log.e("ERROR", "ERROR IN CODE: " + e.toString());
        // this is the line that prints out the location in
        // the code where the error occurred.
        e.printStackTrace();
    }
        return null;
    }

    protected void onProgressUpdate(String... progress) {
         Log.d(LOG_TAG,progress[0]);
         mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }

    @Override
    protected void onPostExecute(String unused) {
        //dismiss the dialog after the file was downloaded
        dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
    }

}

//our progress bar settings
@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
        case DIALOG_DOWNLOAD_PROGRESS: //we set this to 0
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setTitle("Conectando al Servidor");
            mProgressDialog.setMessage("Cargando informacion...");
            mProgressDialog.setIndeterminate(false);
            mProgressDialog.setMax(100);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mProgressDialog.setCancelable(true);
            mProgressDialog.show();
            return mProgressDialog;
        default:
            return null;
    }
}

编辑: 然后我尝试添加Arun

建议的下一个代码
 catch (Exception e) {
        // this is the line of code that sends a real error message to the
        // log
        Log.e("ERROR", "ERROR IN CODE: " + e.toString());
        // this is the line that prints out the location in
        // the code where the error occurred.
        e.printStackTrace();
        return "ERROR_IN_CODE";
    }
       return null;       // if I place here return "ERROR_IN_CODE" it calls the dialog but it gets always called so I don't need it here
    }

    @Override
    protected void onPostExecute(String unused) {
        //dismiss the dialog after the file was downloaded
        dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
        if(unused.equals("ERROR_IN_CODE")){                 //I get a system crash here!
            errornote();
        }
    }

}

public void errornote() {
    AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
    alt_bld.setMessage("No se a podido descargar la informacion de los medios, deseas reintentarlo, o salir?").setCancelable(false)
            .setPositiveButton("Conectar de Nuevo", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    new DownloadFileAsync().execute();
                }
            })
            .setNegativeButton("Salir", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // Action for 'NO' Button
                    finish();
                }
            });
    AlertDialog alert = alt_bld.create();
    // Title for AlertDialog
    alert.setTitle("Error en la Conexion!");
    // Icon for AlertDialog
    alert.setIcon(android.R.drawable.ic_dialog_alert);
    alert.show();
}

但也没有工作,我的应用程序崩溃在onPostExecute的if语句行中。我仍然需要帮助。

3 个答案:

答案 0 :(得分:2)

由于您从protected String doInBackground(String... aurl)返回一个String对象,因此从catch块返回一些自定义错误字符串并在protected void onPostExecute(String unused)中访问它。检查返回的String对象是否为自定义错误字符串并在protected void onPostExecute(String unused)中显示对话框,但仅在取消progressDialog之后,即在此行dismissDialog(DIALOG_DOWNLOAD_PROGRESS);之后显示错误对话框。

修改

当控件进入Catch块时,返回一些简单的String,就像你使用的那个“ERROR_IN_CODE”一样。

catch (Exception e) {
    // this is the line of code that sends a real error message to the
    // log
    Log.e("ERROR", "ERROR IN CODE: " + e.toString());
    // this is the line that prints out the location in
    // the code where the error occurred.
    e.printStackTrace();

    return "ERROR_IN_CODE";
}

onPostExecute(String unused)检查以下内容

protected void onPostExecute(String unused) {
    //dismiss the dialog after the file was downloaded
    dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
    if(unused != null && unused.equals("ERROR_IN_CODE")){
        showDialog(SOME_DIALOG_TO_SHOW_ERROR);
    }
}

答案 1 :(得分:1)

尝试调用您的活动runOnUiThread()方法

activity.runOnUiThread(new Runnable() {
        public void run() {
            //your alert dialog builder here
    });

答案 2 :(得分:0)

您没有使用builder创建AlertDialog 删除行builder.show()并添加

AlertDialog alert = builder.create();
alert.show();

我还建议通过asyc任务的progressUpdate()preExecute()和'postExecute()'进行UI更新。