我正在和我哥哥一起编写应用程序,但不幸的是,我遇到了一个问题。
当应用程序通过我的asynctask类加载php页面时,它可以正常工作。但我想编程这种情况:如果远程服务器关闭或崩溃,并且没有显示正确的页面,应用程序将显示错误消息。但相反,应用程序崩溃= [
我尝试加载此页面,例如: http://alonadoni.com/sql3.php (我想模拟服务器有问题。常规页面是sql2.php,当服务器工作时它可以正常工作)
当应用尝试加载此页面(sql3.php)时,应用程序崩溃。 我做了另一个实验:我创建了一个文件sql3.php,并在页面中写了“aaaaaaaa”,应用程序在这种情况下不会崩溃。它下载了数据“aaaaa”。在这种情况下,应用程序显示jsonexecption错误。
不幸的是,我无法获取logcat,因为我的旧计算机无法运行模拟器,而且我的手机也无法在开发人员模式下连接到我的计算机= [当我尝试应用程序时我创建了一个apk然后将文件传输到我的手机并安装。
我的代码是:
在OnCreate中:
String serverURL = sss() + "sql3.php?imei=" + imei;
new LongOperation().execute(serverURL);
在OnCreate之外:
private class LongOperation extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Error = null;
protected void onPreExecute() {
}
protected Void doInBackground(String... urls) {
try {
HttpGet httpget = new HttpGet(urls[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
data[x] = Client.execute(httpget, responseHandler);
} catch (ClientProtocolException e) {
Error = e.getMessage();
Toast.makeText(getApplicationContext(),"error2" , Toast.LENGTH_LONG).show();
cancel(true);
} catch (IOException e) {
Error = e.getMessage();
Toast.makeText(getApplicationContext(),"error34" , Toast.LENGTH_LONG).show();
cancel(true);
}
return null;
}
public void onPostExecute(Void unused) {
if (Error != null) {
} else {
try {
JSONObject json = new JSONObject(data[x]);
name = json.getString("name");
} catch (JSONException e) {
Toast.makeText(getApplicationContext(),"e" + e, Toast.LENGTH_LONG).show();
}
}
x++;
}
}
答案 0 :(得分:1)
DoInBackground 只需要包含 NON UI工作,因此引用上下文并在UI线程中执行UI操作可能会导致崩溃。 您可以在asynctask的postexecute中执行UI操作。
Hence Removing toast from above code which refers to UI operation will solve your issue