2
\$\begingroup\$

I often use a similar scheme work with an API project. Can it be made easier, or is there a standard approach?

This class creates an API request:

public class ApiRequestCreator {
 private static String TEST_API_REQUEST = "http://jsonplaceholder.typicode.com/posts";
 public static Request createTestApiRequest(){
 return new Request.Builder()
 .url(TEST_API_REQUEST)
 .build();
 }
}

This class execute the request:

 public class ApiRequestExecutor {
 private final OkHttpClient client = new OkHttpClient();
 public void run(final Request request, final ApiMethodListener apiMethodListener) {
 new AsyncTask<Void, Void, String>() {
 @Override
 protected String doInBackground(Void ...voids) {
 try {
 Response response = client.newCall(request).execute();
 if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
 return response.body().string();
 } catch (IOException e) {
 e.printStackTrace();
 return null;
 }
 }
 @Override
 protected void onPostExecute(String result) {
 super.onPostExecute(result);
 apiMethodListener.result(result);
 }
 }.execute();
 }
}

For all of this to start:

new ApiRequestExecutor().run(ApiRequestCreator.createTestApiRequest(), call_back_interface_here);
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jul 6, 2016 at 7:24
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Your code looks good, but in my opinion AsyncTasks are good for single operations - it's not pleasant to make AsyncTask reusable. In my projects I use Ion to download some JSON data from API. This (and similar) library is prepared for making API calls, so it's easier and more ellegant to use for network requests.

answered Jul 17, 2016 at 19:29
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.