1 回答
TA贡献1796条经验 获得超10个赞
这是因为您正在尝试使用以下行在异步任务的 doInBackground(Params...) 方法内使用后台线程更改 UI:
try { ... return result; } catch (MalformedURLException e1) { Toast.makeText(MainActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show(); } catch (IOException e2) { Toast.makeText(MainActivity.this, "IOException", Toast.LENGTH_SHORT).show(); } catch (Exception e) { Toast.makeText(MainActivity.this, "General exception (doInBackground)", Toast.LENGTH_SHORT).show(); }
你不应该在doInBackground(Params...)内调用Toast。在 onPostExecute(Result) 中执行此操作。
您可以通过忽略错误或在doInBackground中返回特定文本来避免这种情况。像这样:
public class DownloadTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String result = "";
...
try {
...
return result;
} catch (MalformedURLException e1) {
result= "MalformedURLException";
} catch (IOException e2) {
result= "IOException";
} catch (Exception e) {
// do nothing and returning empty
result= "Exception";
}
return result;
}
@Override
protected void onPostExecute(String result) {
// check if there is an error
String errorMessage = "";
switch(result) {
case "MalformedURLException":
errorMessage = "MalformedURLException";
break;
case ""IOException":
errorMessage = "IOException";
break;
case "Exception":
errorMessage = "Exception";
break;
}
// there is an error, show a message.
if(!errorMessage.isEmpty()) {
Toast.makeText(MainActivity.this, "Could not find weather: " + errorMessage, Toast.LENGTH_SHORT).show();
return; // stop the process.
}
// do something when no error found.
}
}
添加回答
举报