来自AsyncTask中URL的InputStream [英] InputStream from URL in AsyncTask
问题描述
尝试从URL获取文件到InputStream元素(使用AsyncTask),然后使用它,但到目前为止没有成功.这些参数是否适合AsyncTask?我可以像在代码中一样检查InputStream还是错误,并且它总是返回null?我还应该进行其他更改吗?
Trying to get a file from URL into InputStream element (with AsyncTask) and then use it, but so far unsuccessful. Are the parameters right for AsyncTask? Can I check InputStream like I did in my code or is it wrong and it will always return null? Any other changes I should make?
我的代码:
String url = "https://www.example.com/file.txt";
InputStream stream = null;
public void load() {
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(url);
if (stream == null) {
//fail, stream == null
} else {
//success
}
}
class DownloadTask extends AsyncTask <String, Integer, InputStream> {
@Override
protected void onPreExecute() {
}
@Override
protected InputStream doInBackground(String... params){
try {
URL url = new URL(url);
stream = url.openStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return stream;
}
@Override
protected void onPostExecute(InputStream result) {
super.onPostExecute(result);
}
}
我修好了.
public void load(){
//some code
DownloadTask dt=new DownloadTask();
dt.execute("www.example.com");
}
private class DownloadTask extends AsyncTask<String,Integer,Void>{
InputStream text;
protected Void doInBackground(String...params){
URL url;
try {
url = new URL(params[0]);
HttpURLConnection con=(HttpURLConnection)url.openConnection();
InputStream is=con.getInputStream();
text = is;
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result){
//use "text"
}
}
推荐答案
您以错误的方式使用了 AsyncTask
.在 doInBackground(String ... params)
方法内执行所有操作,例如下载或服务器请求.
you are using AsyncTask
in the wrong way. Do all operations like download or server requests inside doInBackground(String... params)
method.
非常重要的一点是,您应该在 onPostExecute(..)
方法内更新UI.从UI-Thread调用此方法.
Very important to know, that you should update your UI inside the onPostExecute(..)
method. This method get called from UI-Thread.
这是一个示例(伪代码):
Here is an example (pseudo code):
class DownloadTask extends AsyncTask <String, Integer, MyDownloadedData> {
private MyDownloadedData getFromStream(InputStream stream){
// TODO
return null;
}
@Override
protected void onPreExecute() {
}
@Override
protected MyDownloadedData doInBackground(String... params){
try {
URL url = new URL(url);
InputStream stream = url.openStream();
MyDownloadedData data = getFromStream(stream);
return data;
} catch (Exception e) {
// do something
}
return stream;
}
@Override
protected void onPostExecute(MyDownloadedData data) {
//
// update your UI in this method. example:
//
someLabel.setText(data.getName());
}
protected void onProgressUpdate(Integer... progress) {
//...
}
}
这篇关于来自AsyncTask中URL的InputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!