所以我遇到了AsyncTask
的问题。如果在postExecute
中捕获到某个错误throwable,我需要doInBackground
才能显示警告对话框。问题是永远不会调用postExecute
。我尝试添加@Override
,但Android Studio表示它没有覆盖其超类中的方法。我也试过改变返回类型。我环顾了这个网站,找不到答案。提前谢谢。
AsyncTask类
public class AsyncTaskActivity extends AsyncTask<Void, Void, Void> {
String exception;
@Override
protected void onPreExecute() {
}
protected void onPostExecute() {
if (exception.contains("java.net.UnknownHostException")) {
MainActivity.showDialog();
Log.i("Error Message", "ERROR MESSAGE SHOWN");
}
}
@Override
protected Void doInBackground(Void... params) {
try {
Log.i("AsyncTask", "Loading...");
// Make a URL to the web page. This takes the string representation of the URL
// and changes it into a URL object
URL url = new URL("http://api.wunderground.com/api/0c0fcc3bf62ab910/conditions/q/IN/Fort_Wayne.json");
// Get the input stream through URL Connection
URLConnection con = url.openConnection();
InputStream is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
// read each line and write to text file
while ((line = br.readLine()) != null) {
Log.i("AsyncTask", line);
TextEditor.file = new File(MainActivity.path, "siteInfo.txt");
TextEditor.writeString(line);
}
TextEditor.saveAndClose();
} catch (Exception e) {
e.printStackTrace();
exception = e.toString();
}
Log.i("AsyncTask", "DONE");
return null;
}
}
showDialog方法
public static void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.context);
builder.setView(R.layout.dialog_layout);
builder.setPositiveButton(
R.string.dialog_close,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
System.exit(1);
}
});
builder.show();
}
答案 0 :(得分:0)
看起来你错过了什么
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (exception.contains("java.net.UnknownHostException")) {
MainActivity.showDialog();
Log.i("Error Message", "ERROR MESSAGE SHOWN");
}
}
答案 1 :(得分:0)
首先请参阅此文档。你错过了onPostExecute()的参数。
https://developer.android.com/reference/android/os/AsyncTask.html
你需要做的是,
@Override
protected void onPostExecute(Params) {
// your logics
}
答案 2 :(得分:0)
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (exception.contains("java.net.UnknownHostException")) {
MainActivity.showDialog();
Log.i("Error Message", "ERROR MESSAGE SHOWN");
}
}
请注意,您需要初始化异常,否则可能会导致NullPointerException