首页 > 解决方案 > 在下一个方法调用之前 Asynctask 未完成下载

问题描述

我有一个简单的类,它扩展AsyncTask了我在网络上访问文本文件并将内容提取到String tmpString. 这一切都在doInBackground(). 在调用之后,我从另一个类中execute();调用我自己的方法,该方法从.parseContent();tmpString

现在问题来了,当我运行这段代码时,我得到tmpString = null了,这意味着来自网站的内容为空,但我知道Log.d("--------INFO--------", inputLine);通过逐行检查源文件中的打印来检索内容。我怀疑在下一个方法调用之前下载太慢了。当我调试时一切正常,因为下载有时间完成。

使用execute().get();有效,但我读到这不是最佳解决方案,尤其是因为它阻塞了线程。稍后我想为下载添加一个进度条,但将它与它结合起来get()不起作用......显然。

我想做的是只有在下载完成后才调用下一个方法,我该如何实现呢?

代码在这里:

public class AccessFile extends AsyncTask<Object, Void, String>{
    private String urlContent = "";
    @Override
    protected String doInBackground(Object[] params) {
        URL url= null;
        url= new URL((String) params[0]);

        BufferedReader in = null;
        try {
            assert url!= null;
            in = new BufferedReader(
                    new InputStreamReader(
                            url.openStream()));
        } catch (IOException e) {
            e.printStackTrace();
        }

        String inputLine = null;
        inputLine = in.readLine();

        while (inputLine != null){
            Log.d("--------INFO--------", inputLine);
            urlContent += inputLine;
            inputLine = in.readLine();
        }
        in.close();
        return "";
    }
}

我称之为:

AccessFile af = new AccessFile();
af.execute("Link here").get();

标签: javaandroidandroid-asynctask

解决方案


你可以试试

AccessFile af = new AccessFile()
{
     @Override
     protected void onPostExecute(String result) {
           super.onPostExecute(result);
           //code which should be executed after task completion
     }

}; 
af.execute("link);   

推荐阅读