问题
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?
My code:
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);
}
}
EDIT2: I fixed it.
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"
}
}
回答1:
you are using AsyncTask
in the wrong way. Do all operations like download or server requests inside doInBackground(String... params)
method.
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) {
//...
}
}
来源:https://stackoverflow.com/questions/40396164/inputstream-from-url-in-asynctask