Trying to understand the AsyncTask
I'm doing some revision as I am a noob programmer- currently trying to
understand the AsyncTask. I have this example of how it is used to
download and display the contents of a webpage but I'm struggling to get
my head around which bits do what. My notes are unfortunately rubbish. Can
anyone help out explaining it?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.async);
textView = (TextView) findViewById(R.id.text_view);
DownloadWebpageTask task = new DownloadWebpageTask();
task.execute(new String[] { URL });
}
private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
textView.setText(response);
}
@Override
protected void onPostExecute(String result) {
}
}
No comments:
Post a Comment