How can I return the value of a method that is within another method

5

I am making a request with Okhttp and in the onResponse() method I am storing in variable myResponse the result of that request, my question is, how can I make the method peticion() return the value of the Variable myResponse , I would appreciate example of code since I am still not very good programming, thanks in advance

 public String peticion(){
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(url)
                .build();


            client.newCall(request).enqueue(new Callback() {

                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()){
                       String myResponse = response.body().string();

                    }
                }
             });
        return
    }
    
asked by Yop 27.04.2018 в 12:41
source

1 answer

5

After the call to the request method, if you immediately return the value responsePeticion it is normal that it is "". Note that you are inside a CallBack and that the onResponse method will be executed asynchronously by the server when generating the response.

What you can do is create a class to manage the onResponse of the CallBack .

A class, called EventHandler, for example, and having a String responseReceived(String response) method that was called from within onResponse of CallBack .

Something like this:

public void peticion(EventHandler eventHandler){
    OkHttpClient client = new OkHttpClient();
    String responsePeticion = "";

    Request request = new Request.Builder()
            .url(url)
            .build();


        client.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                responsePeticion = "Error in request";
                Log.e("Error", "Request error", e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()){
                   eventHandler.responseReceived(response.body().string())

                }
            }
         });
}

The EventHandler class in prinpio should be very simple.

    
answered by 27.04.2018 / 14:01
source