For my app I need to contact our API from our server which returns some JSON.
While downloading the JSON, it should display a progressbar.
I figured I should
In my opinion the cleanest solution is to create a service that handles the dirty download logic and returns a future of your custom response class, that contains the success info and the json object.
// in e.g JsonResponse.java
public class JsonResponse() {
public boolean ok;
public JsonObject json;
}
// in Service.java
public Future getId(final String id) {
final SimpleFuture jsonFuture = new SimpleFuture<>();
String url = IPAddress.PRODUCTION + Variables.get_id + id;
Ion.with(context)
.load("GET", url)
.asJsonObject()
.withResponse()
.setCallback(new FutureCallback>() {
@Override
public void onCompleted(Exception e, Response response) {
JsonResponse jsonResponse = new JsonResponse();
if (response != null) {
if (response.getHeaders().code() != 200) {
jsonResponse.ok = false;
} else {
jsonResponse.ok = true;
jsonResponse.json = response.getResult();
}
}
jsonFuture.setComplete(jsonResponse);
}
});
return jsonFuture;
}
// in Activity.java
private void loadUser(String userId) {
mLoadingSpinner.setVisibility(View.VISIBLE);
service.getId(userId)
.setCallback(new FutureCallback() {
// onCompleted is executed on ui thread
@Override
public void onCompleted(Exception e, JsonResponse jsonResponse) {
mLoadingSpinner.setVisibility(View.GONE);
if (jsonResponse.ok) {
// Show intent using info from jsonResponse.json
} else {
// Show error toast
}
}
});
}