Skip to content

Instantly share code, notes, and snippets.

@adriantache
Created July 14, 2019 12:54
Show Gist options
  • Save adriantache/e04db59e88ae29c189b4a13d3b7aed7d to your computer and use it in GitHub Desktop.
Save adriantache/e04db59e88ae29c189b4a13d3b7aed7d to your computer and use it in GitHub Desktop.
//First we build the URI and pass it to the AsyncTask
private static final String GIT_HUB_API = "api.github.com";
private static final String USERS_ENDPOINT = "users";
private static final String REPOS_ENDPOINT = "repos";
private static final String ERROR = "error";
//(...)
Uri.Builder builder = new Uri.Builder();
builder.scheme("https")
.authority(GIT_HUB_API)
.appendPath(USERS_ENDPOINT)
.appendPath(user)
.appendPath(REPOS_ENDPOINT);
new NetworkWork().execute(builder.build().toString());
//(...)
//Then we build the actual AsyncTask
class NetworkWork extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... url) {
if (url == null || url[0] == null) return ERROR;
OkHttpClient client = new OkHttpClient();
Request.Builder builder = new Request.Builder().url(url[0]);
try (Response response = client.newCall(builder.build()).execute()) {
if(!response.isSuccessful()) return ERROR
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
return ERROR;
}
}
@Override
protected void onPostExecute(String s) {
if (s.equals(ERROR)) {
Toast.makeText(MainActivity.this, "Cannot fetch data from GitHub!", Toast.LENGTH_SHORT).show();
} else decodeJson(s);
}
}
//Finally we decode the JSON
private ArrayList<String> decodeJson(String s) {
if (TextUtils.isEmpty(s))
Toast.makeText(MainActivity.this, "Empty response!", Toast.LENGTH_SHORT).show();
ArrayList<String> repos = new ArrayList<>();
try {
JSONArray jsonRoot = new JSONArray(s);
for (int i = 0; i < jsonRoot.length(); i++) {
JSONObject child = jsonRoot.optJSONObject(i);
String repoName = child.optString("name");
if (!TextUtils.isEmpty(repoName)) repos.add(repoName);
}
if (!repos.isEmpty()) {
return repos;
} else {
Toast.makeText(this, "Cannot extract repos from JSON!", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Toast.makeText(this, "Cannot decode JSON!", Toast.LENGTH_SHORT).show();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment