AsyncHttpTask java public class AsyncHttpTask extends AsyncTask String

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
AsyncHttpTask.java
public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {
@Override
protected Integer doInBackground(String... params) {
InputStream inputStream = null;
Integer result = 0;
try {
/* create Apache HttpClient */
HttpClient httpclient = new DefaultHttpClient();
/* HttpGet Method */
HttpGet httpGet = new HttpGet(params[0]);
/* optional request header */
httpGet.setHeader("Content-Type", "application/json");
/* optional request header */
httpGet.setHeader("Accept", "application/json");
/* Make http request call */
HttpResponse httpResponse = httpclient.execute(httpGet);
int statusCode = httpResponse.getStatusLine().getStatusCode();
/* 200 represents HTTP OK */
if (statusCode == 200) {
/* receive response as inputStream */
inputStream = httpResponse.getEntity().getContent();
String response = convertInputStreamToString(inputStream);
parseResult(response);
result = 1; // Successful
} else{
result = 0; //"Failed to fetch data!";
}
} catch (Exception e) {
Log.d(TAG, e.getLocalizedMessage());
}
return result; //"Failed to fetch data!";
}\
@Override
protected void onPostExecute(Integer result) {
/* Download complete. Lets update UI */
if(result == 1){
arrayAdapter = new ArrayAdapter(MyActivity.this, android.R.layout.simple_list_item_1, blogTitles);
listView.setAdapter(arrayAdapter);
}else{
Log.e(TAG, "Failed to fetch data!");
}
}
}