我在我的应用程序中使用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);
有什么想法吗?提前谢谢你!
最佳答案
您试图通过提供AlertDialog
null
来创建Context
。您需要做的是从调用Activity
的AsyncTask
传递一个有效的上下文,方法是将上下文传递给任务的构造函数,然后将其与对话框一起使用:
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
来跟踪进入/退出方法/代码块。