Skip to content

Instantly share code, notes, and snippets.

@bearprada
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bearprada/530e0a7fc9695f3c1df0 to your computer and use it in GitHub Desktop.
Save bearprada/530e0a7fc9695f3c1df0 to your computer and use it in GitHub Desktop.
Restful API Integration on Android
...
protected onCreate(Bundle savedStateInstance) {
NetworkTask task = new NetworkTask(this);
NetworkTask.execute();
}
public void successful(List<Repo> repos) {
// do something
}
public void fail(Exception e) {
// do something
}
...
public class NetworkTask extends AsyncTask<Void, Void, String> {
private Callback callback;
public interface Callback {
public void successful(List<Repo> repos);
public void fail(Exception e);
}
public NetworkTask(Callback callback) {
this.callback = callback;
}
protected Void doInBackground (Void.. params) {
// we hard code here, because it should be re-design more interface if we want to support different type of parameter.
String url = "http://example.com/users/PRADA/repos?limit=10";
HttpGet request = new HttpGet(url);
AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
try {
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity);
} catch (Exception e) {
return null;
} finally {
client.close();
}
}
protected void onPostExecute (String result) {
if (callback != null) {
if (result == null) {
callback.fail(new Exception());
} else {
callback.successful(parseJsonString(result));
}
}
}
private List<Repo> parseJsonString(String json) {
// TODO
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment