Versuchen, eine Datei von URL in InputStream-Element (mit AsyncTask) zu erhalten und dann zu verwenden, aber bis jetzt nicht erfolgreich. Sind die Parameter richtig für AsyncTask? Kann ich InputStream wie in meinem Code überprüfen oder ist es falsch und wird immer null zurückgegeben? Irgendwelche anderen Änderungen, die ich machen sollte?InputStream von URL in AsyncTask
Mein 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: ich es fest.
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"
}
}
ich mein Problem gelöst (meine Frage bearbeitet). Danke für den Hinweis, dass ich die Benutzeroberfläche in der onPostExecute() Methode aktualisieren muss! Pseudocode ist ein bisschen verwirrend für Anfänger wie mich, weil ich für meine Aufgabe (in asynctask eingabestream) keine preExecute, progressUpdate, getFromStream() brauche - all diese Dinge sind für die Aufgabe nicht relevant. – user3671635