我在我的应用程序中使用 AsyncTask,但当它开始时,就好像它永远不会结束。当我在 doInBackground
应用程序卡住并卡在 ThreadPoolExecutor.runWorker(ThreadPoolExecutor$Worker)
后进行调试时。
这是我的代码结构
class FetchSymbolInfo extends AsyncTask<String, Void, Document> {
private Exception exception = null;
@Override
protected Document doInBackground(String... params)
{
try
{
Document doc = null;
//doc = Jsoup.connect(params[0]).get();//application freezes even if I remove this line
return doc;
}
catch (Exception e)
{
this.exception = e;
return null;
}
}
@Override
protected void onPostExecute(Document result)
{
if(exception != null)
{
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(null).create();//////////
alertDialog.setTitle("Error");
alertDialog.setMessage("Could not fetch from internetd\nPlease check your inernet connection and symbol name.");
alertDialog.show();
return;
}
Elements valueElement = result.select("div#qwidget_lastsale");
String valueString = valueElement.toString();
//getting number from string
}
@Override
protected void onPreExecute() {
}
@Override
protected void onCancelled() {
super.onCancelled();
}
@Override
protected void onCancelled(Document result) {
super.onCancelled(result);
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
我正在尝试像这样执行它
String url = "url"; //writing an url
FetchSymbolInfo fetch = new FetchSymbolInfo();
fetch.execute(url);
有什么想法吗?提前致谢!
最佳答案
您正在尝试通过提供 null
Context
创建一个 AlertDialog
。您需要做的是从调用 AsyncTask
的 Activity
传递一个有效的 Context,方法是将 Context 传递给任务的构造函数,然后将其与 Dialog 一起使用:
class FetchSymbolInfo extends AsyncTask<String, Void, Document> {
private Context parent;
// ...
public FetchSymbolInfo(Context c){
parent = c;
}
// ...
if(exception != null){
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(parent).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Could not fetch from internetd\nPlease check your inernet connection and symbol name.");
alertDialog.show();
return;
}
补充:虽然与问题没有直接关系,但我认为在这里提一下很重要,如果你像 OP 那样在新线程中设置断点,你就不会命中它 - 你最好使用 Log
来跟踪进入/退出方法/代码块。
关于android - AsyncTask 停止应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17931949/