Java 安卓,如何显示一个对话框从错误的尝试捕捉?
在我的应用程序中,我连接到一个网站,在开始时通过异步任务收集一些信息,使用try-catch,从这里我可以在我的catlog中显示连接时的错误(如果有),但我一直在尝试显示一个对话框,显示连接失败,并提供重新连接或退出选项,请检查我的代码,并告诉我我做错了什么或如何实现这一点的想法Java 安卓,如何显示一个对话框从错误的尝试捕捉?,java,android,eclipse,try-catch,Java,Android,Eclipse,Try Catch,在我的应用程序中,我连接到一个网站,在开始时通过异步任务收集一些信息,使用try-catch,从这里我可以在我的catlog中显示连接时的错误(如果有),但我一直在尝试显示一个对话框,显示连接失败,并提供重新连接或退出选项,请检查我的代码,并告诉我我做错了什么或如何实现这一点的想法 //this is our download file asynctask class DownloadFileAsync extends AsyncTask<String, String, String&g
//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;
}
}
但也不工作,我的应用程序在onPostExecute中的if语句行崩溃。我仍然需要帮助。尝试调用活动runOnUiThread()方法
您没有使用
builder
创建警报对话框
删除行builder.show()
并添加
AlertDialog alert = builder.create();
alert.show();
我还建议通过asyc任务的progressUpdate()
或preExecute()
和“postExecute()”进行UI更新
实施
@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));
}
});
}
@ReactMethod
公共无效showCustomAlert(字符串消息){
最终字符串消息=msg;
this.reactContext.rununuiqueuethread(新的Runnable(){
@凌驾
公开募捐{
AlertDialog.Builder myDialogBox=新建AlertDialog.Builder(reactContext.getCurrentActivity());
myDialogBox.setTitle(Html.fromHtml(“Konnect”);
设置消息(message);
myDialogBox.setCancelable(真);
myDialogBox.setPositiveButton(“确定”,新建DialogInterface.OnClickListener()){
public void onClick(对话框接口对话框,int whichButton){
dialog.dismise();
}
});
AlertDialog AlertDialog=myDialogBox.create();
if(Build.VERSION.SDK\u INT=Build.VERSION\u code.O){
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE\u APPLICATION\u OVERLAY);
}否则{
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位置
wmlp.y=450;//y位置
wmlp.height=380;
alertDialog.show();
alertDialog.getWindow().setBackgroundDrawable(新的ColorDrawable(Color.WHITE));
}
});
}
因为您正在从受保护的字符串doInBackground(String…aurl)返回字符串对象从catch块返回一些自定义错误字符串,并在受保护的void onPostExecute(字符串未使用)中访问它。。检查返回的字符串对象是否为自定义错误字符串,并在progressDialog(对话框下载\u进度)后,在progressExecute(字符串未使用)
中显示对话框,但仅在取消progressDialog后显示代码>显示错误对话框
编辑
当控件进入Catch块时,返回一些简单字符串,如您使用的“ERROR\u IN\u CODE”
并在onPostExecute(字符串未使用)
中检查以下内容
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);
}
}
您不能在doInBackground()的Catch块中显示对话框,因为此函数在非UI线程中运行。请查看答案是否有帮助。@yorkw,不,对话框不显示。根据您上次的编辑,代码执行似乎没有运行到Catch块,请确保Catch块正确触发,换句话说,确保try块中的代码失败并引发实际的异常。@yorkw,我所做的测试只是在仿真器尝试连接以下载其无法下载的信息时,以这种方式断开internet与计算机的连接,因此将出现连接错误。这就是你的意思吗?AlertDialog.Builder.show()的作用与你在这里建议的完全相同。它只是一个较短的变体。请参阅。既然在非UI线程上运行,您如何在doInBackground()中显示对话框?抱歉@Orlymee您编辑帖子时,我还在写评论。我想删除我的否决票,但它显示了一个对话框,上面写着“你上次对这个答案投票是在8分钟前,除非这个答案被编辑,否则你的投票现在被锁定”@orlyme,你能用我的代码给我一个示例,说明如何实现你的想法吗。谢谢@Arun谢谢你提供的所有信息,我喜欢你回答我的问题的方法,但我对所有这些都不熟悉,你能给我一个如何在我的代码中实现自定义错误字符串的示例吗?谢谢@Arun,我已经尝试过了,但它一直在破坏应用程序,在logcat中,我在410行有if(unused.equals…@zvzej)的地方遇到了一个错误,为什么在Catch块后返回null?我想如果没有遇到任何错误,你应该返回结果字符串。无论如何,我已经编辑了onPostExecute(字符串unused)并且添加了空值检查,这应该可以解决您的问题。@Arun,完成了!非常感谢!在返回空值中,我只能说我从在线教程中获得了这部分代码,这就是它在那里的方式,在我的情况下它起了作用。我只需要在返回中添加“ERROR\u in\u code”的广告;在Asynctask中调用捕获案例,以便在任何错误情况下都可以调用它。再次感谢您。@ian,我应该在何处以及如何实现它?@yorkw,您能解释一下如何或在何处使用它吗?@zvzej,假设您将Asynctask实现为活动的内部类,请查看示例代码。
@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));
}
});
}
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";
}
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);
}
}