Created
May 5, 2015 07:54
-
-
Save blackdev1l/139fe5af6868db9daa7e to your computer and use it in GitHub Desktop.
AsyncTask for GET request and parse on a custom adapter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private class CallAPI extends AsyncTask<String, String, JSONArray> { | |
JSONArray jArray; | |
@Override | |
protected JSONArray doInBackground(String... urls) { | |
try { | |
URL url = new URL(getString(R.string.api_url)); | |
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); | |
httpCon.setRequestMethod("GET"); | |
if(httpCon.getResponseCode() == 200) { | |
BufferedReader br = new BufferedReader(new InputStreamReader(httpCon.getInputStream())); | |
StringBuilder sb = new StringBuilder(); | |
String line; | |
while ((line = br.readLine()) != null) { | |
sb.append(line).append("\n"); | |
} | |
br.close(); | |
jArray = new JSONArray(sb.toString()); | |
return jArray; | |
} | |
else { | |
Log.d("ERR REQEST","Bad Response code" ); | |
} | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} catch (JSONException e) { | |
e.printStackTrace(); | |
} | |
return null; | |
} | |
protected void onPostExecute(JSONArray result) { | |
ArrayList<Kid> kids = new ArrayList<Kid>(); | |
for (int i = 0; i < jArray.length(); i++) { | |
try { | |
JSONObject jobj = jArray.getJSONObject(i); | |
String id = jobj.getString("id"); | |
String name = jobj.getString("name"); | |
String stop = jobj.getString("stop"); | |
Kid kid = new Kid(id,name,stop); | |
kids.add(kid); | |
} catch (JSONException e) { | |
e.printStackTrace(); | |
} | |
} | |
KidAdapter kidAdapter = new KidAdapter(getActivity(),kids); | |
// Set the adapter | |
mListView = (AbsListView) getActivity().findViewById(android.R.id.list); | |
mListView.setAdapter(kidAdapter); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment