eclipse Android,如何从try catch错误中显示对话框?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10954114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android, how to display a dialog from error of a try catch?
提问by zvzej
In my app I connect to a website to collect some information at start with a AsyncTask, using a try catch, from here I can display in my catlog the error if any at connection, but I have been trying with out luck to show a dialog displaying the connection failure with options to reconnect or quit, please check my code and tell me what I'm doing wrong or an idea of how to accomplish this
在我的应用程序中,我连接到一个网站以从 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;
}
}
EDIT: then I have try adding the next code as of suggested by Arun
编辑:然后我尝试添加 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();
}
but not working either, my app crashes in the if statement line in onPostExecute. I still need help.
但也不起作用,我的应用程序在 onPostExecute 的 if 语句行中崩溃。我仍然需要帮助。
采纳答案by Arun George
Since you are returning a String object from the protected String doInBackground(String... aurl)
return some custom Error String from the catch block and access it in the protected void onPostExecute(String unused)
. Check if the returned String object is the Custom Error String and show the dialog in protected void onPostExecute(String unused)
but only after dismissing the progressDialog i.e. after this line dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
show the error dialog.
由于您正在protected String doInBackground(String... aurl)
从 catch 块返回一些自定义错误字符串并在protected void onPostExecute(String unused)
. 检查返回的 String 对象是否是自定义错误字符串并显示对话框,protected void onPostExecute(String unused)
但仅在关闭 progressDialog 之后,即在此行dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
显示错误对话框之后。
EDIT
编辑
When the control enters the Catch block return some simple String like the one you used "ERROR_IN_CODE".
当控件进入 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";
}
And in the onPostExecute(String unused)
check for the following
并在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);
}
}
回答by IK828
Try calling your activities runOnUiThread() method
尝试调用您的活动 runOnUiThread() 方法
activity.runOnUiThread(new Runnable() {
public void run() {
//your alert dialog builder here
});
回答by Orlymee
you are not using the builder
to create AlertDialog
remove the line builder.show()
and add
您没有使用builder
创建 AlertDialog 删除该行builder.show()
并添加
AlertDialog alert = builder.create();
alert.show();
I will also recommend that do the UI updates through progressUpdate()
or preExecute()
and 'postExecute()' of the asyc task.
我还将建议通过asyc 任务的progressUpdate()
orpreExecute()
和 'postExecute()' 进行UI 更新。
Implementation
执行
@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));
}
});
}