I am trying to write a snippet of code that takes a URL and displays its textual contents to an EditText view. This is not going well, I have milled around other links that I thought gave the answer such as making my network calls from an AsyncTask described here:
Android Honeycomb: Fragment not able to start AsyncTask?
but that doesn’t seem to work. It is really one function (that calls another) that is all I am trying to use here. Those functions are posted for completeness:
public static InputStream getInputStreamFromUrl(String url){
InputStream contentStream = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(url));
contentStream = response.getEntity().getContent();
} catch(Exception e){
e.printStackTrace();
}
return contentStream;
}
public static String getStringFromUrl(String url) {
BufferedReader br = new BufferedReader(new InputStreamReader(getInputStreamFromUrl(url)));
StringBuffer sb = new StringBuffer();
try{
String line = null;
while ((line = br.readLine())!=null){
sb.append(line);
}
}catch (IOException e){
e.printStackTrace();
}
return sb.toString();
}
and these are called from my:
private class FragmentHttpHelper extends AsyncTask<Void, Void, Boolean>{
protected void onPostExecute(Boolean result) {
contractTextTxt.setText(getStringFromUrl(urlReferenceTxt.getText().toString()));
}
@Override
protected Boolean doInBackground(Void... params) {
// TODO Auto-generated method stub
return true;
}
}
Which is executed when the button to fetch url is clicked:
retrieveURLReferenceBtn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
new FragmentHttpHelper().execute();
}
});
So by putting things in an asynctask I thought I was going to get around the honeycomb 3.0
NetworkOnMainThreadException but it seems not. Any ideas what to try next?
It looks like you aren’t putting your actual network calls in the doInBackground method in AsyncTask. That is generally what you would want to do, and THEN onPostExecute will be called. I think your onPostExecute is getting called as soon as you start the AsyncTask, because you don’t do anything in doInBackground.
Try moving your HttpClient code into the doInBackground method.
From what I can tell its running like this:
Button clicked > Calls AsyncTask > Nothing Happens in Background thread > calls postExecute which tries to .setText(NETWORK CALL) … which is back on your UI thread.
Correct me if I am wrong. Maybe I am seeing this wrong?