I want to retrieve the contents of this file and save that to a string.
I've tried using AsyncTask (based on this answer) and here is my class.
class RetreiveURLTask extends AsyncTask<Void, Void, String> {
private Exception exception = null;
public String ResultString = null;
protected String doInBackground(Void ... something) {
URL url;
try {
url = new URL("http://stream.lobant.net/ccfm.info");
HttpURLConnection urlConnection;
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
String stream_url = IOUtils.toString(in, "UTF-8");
urlConnection.disconnect();
return stream_url;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (Exception e) {
this.exception = e;
return null;
}
}
protected void onPostExecute(String stream_url) {
// TODO: check this.exception
// TODO: do something with the feed
if (this.exception != null)
this.exception.printStackTrace();
this.ResultString = stream_url;
}
}
I've tried using my AsyncTask class like this:
AsyncTask<Void, Void, String> stream_task = new RetreiveURLTask().execute();
String stream_url = stream_task.ResultString;
but ResultString isn't recognised.
I'm confused about how this all works. Since the AsyncTask runs in the background, even if I could assign my string to one of the public variables, there is no guarentee that it will be valid when I make the assignment. Even if I were to use some kind of getResult() function, I would need to know when to call it so that the code has completed executing.
So, how is this usually done?
(Also, is my http read code ok?)
My ability: I can code, but am new to android.