java - 在下一个方法调用之前 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();
解决方案
你可以试试
AccessFile af = new AccessFile()
{
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//code which should be executed after task completion
}
};
af.execute("link);
推荐阅读
- python - uwsgi 烧瓶服务器总是返回“Hello World!”
- javascript - Laravel DataTables 不是函数
- git - 如何在git中管理版本文件
- vue.js - Vue.js 使用 @input 事件发送索引
- javascript - 如何将 PHP 变量传递给 JavaScript?
- r - 如何删除 spplot 中的 zcol 框?
- git - 将分支从另一个远程分支合并到我的分支后,git pull no tracking info for my branch
- java - 在 GridLayout 中交换组件时出现 IndexOutOfBoundException 和 NullPointerException?
- angular - Angular - 如何使用户角色复选框动态化
- react-native - 在 react-native Flatlist 或 scrollview 中,我们可以像 carousal 一样显示循环吗?