The problem is that you are trying to return an enqueue value enqueue , but it is an asynchronous method using a callback, so you cannot do this. You have 2 options:
- You can change your
RequestGR method to accept a callback and then associate an enqueue callback with it. This is similar to mapping within frameworks such as rxJava.
It will look something like this:
public void RequestGR(LatLng start, LatLng end, final Callback<JSONArray> arrayCallback) { EndpointInterface loginService = ServiceAuthGenerator.createService(EndpointInterface.class); Call<GR> call = loginService.getroutedriver(); call.enqueue(new Callback<GR>() { @Override public void onResponse(Response<GR> response , Retrofit retrofit) { JSONArray jsonArray_GR = response.body().getRoutes(); arrayCallback.onResponse(jsonArray_GR); } @Override public void onFailure(Throwable t) {
The caveat with this approach is that it simply pushes asynchronous content to another level, which may be a problem for you.
- You can use an object similar to
BlockingQueue , Promise or Observable , or even your own container object (be careful to be thread safe), which allows you to check and set the value.
It will look like this:
public BlockingQueue<JSONArray> RequestGR(LatLng start, LatLng end) { // You can create a final container object outside of your callback and then pass in your value to it from inside the callback. final BlockingQueue<JSONArray> blockingQueue = new ArrayBlockingQueue<>(1); EndpointInterface loginService = ServiceAuthGenerator.createService(EndpointInterface.class); Call<GR> call = loginService.getroutedriver(); call.enqueue(new Callback<GR>() { @Override public void onResponse(Response<GR> response , Retrofit retrofit) { JSONArray jsonArray_GR = response.body().getRoutes(); blockingQueue.add(jsonArray_GR); } @Override public void onFailure(Throwable t) { } }); return blockingQueue; }
Then you can synchronously wait for the result in your calling method as follows:
BlockingQueue<JSONArray> result = RequestGR(42,42); JSONArray value = result.take();
I would highly recommend reading in a framework like rxJava, for example.
source share