Last active
August 29, 2015 14:03
-
-
Save bearprada/530e0a7fc9695f3c1df0 to your computer and use it in GitHub Desktop.
Restful API Integration on Android
This file contains hidden or 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
... | |
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 | |
} | |
... |
This file contains hidden or 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
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