4

私のアプリでは、AsyncTask で開始時に情報を収集するために Web サイトに接続し、try catch を使用します。ここから、接続時にエラーがあればカタログに表示できますが、運が悪くてダイアログを表示しようとしました再接続または終了のオプションを含む接続障害を表示している場合は、コードを確認して、何が間違っているか、またはこれを達成する方法を教えてください

 //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;
    }
}

EDIT:次に、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 ステートメント行でアプリがクラッシュします。まだ助けが必要です。

4

3 に答える 3

2

アクティビティの runOnUiThread() メソッドを呼び出してみてください

activity.runOnUiThread(new Runnable() {
        public void run() {
            //your alert dialog builder here
    });
于 2012-06-08T18:29:41.527 に答える
2

returnから String オブジェクトをprotected String doInBackground(String... aurl)返すため、catch ブロックからいくつかのカスタム エラー文字列を返し、protected void onPostExecute(String unused). 返された文字列オブジェクトがカスタム エラー文字列であるかどうかを確認し、ダイアログを表示しますprotected void onPostExecute(String unused)が、progressDialog を閉じた後でのみ、つまりこの行の後dismissDialog(DIALOG_DOWNLOAD_PROGRESS);にエラー ダイアログを表示します。

編集

コントロールが Catch ブロックに入ると、「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);
    }
}
于 2012-06-08T18:34:47.720 に答える
0

builderAlertDialog の作成にを使用していない場合は、行builder.show()を削除して追加します

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

また、asyc タスクの「postExecute()」progressUpdate()または「postExecute()」を介して UI の更新を行うことをお勧めします。preExecute()

実装

@ReactMethod
    public void showCustomAlert(String msg){

        final String message = msg;

        this.reactContext.runOnUiQueueThread(new Runnable() {
            @Override
            public void run() {
                AlertDialog.Builder myDialogBox = new AlertDialog.Builder(reactContext.getCurrentActivity());
                myDialogBox.setTitle(Html.fromHtml("<font color='#0037FF'>Konnect</font>"));
                myDialogBox.setMessage(message);
                myDialogBox.setCancelable(true);
                myDialogBox.setPositiveButton("Ok", new DialogInterface.OnClickListener(){

                    public void onClick(DialogInterface dialog, int whichButton) {
                            dialog.dismiss();
                    }

                });
                AlertDialog alertDialog = myDialogBox.create();
                if (Build.VERSION.SDK_INT <= 23) {
                    alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                }else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
                }else {
                    alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_PHONE);
                }

                alertDialog.show();

                WindowManager.LayoutParams wmlp = alertDialog.getWindow().getAttributes();
                wmlp.gravity = Gravity.TOP | Gravity.LEFT;
                wmlp.x = 25;   //x position
                wmlp.y = 450;   //y position
                wmlp.height = 380;
                alertDialog.show();
                alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
            }
        });
    }
于 2012-06-08T18:31:04.827 に答える