humayoon siddique
humayoon siddique

Reputation: 730

How return response using okhttp library from class method in activity method

I want to get response using enque process in okhttp but did not get exact solution here is my code Activity Code

 public void homeFragmentDataImplementation() {
 Notification notification = new Notification();
 kProgressHUD = notification.activityIndicator(mActivity);
 new Thread(new Runnable() {
     @Override
     public void run() {
         OkHttpRequest okHttpRequest = new OkHttpRequest();
         homeApiResponse = okHttpRequest.getOkHttpRequest(URLS.HOMESCREEN_API +Utility.getDeviceId(mFragment.getContext()));                     handler.sendEmptyMessage(1);
     }}).start();
}
 private Handler handler = new Handler(){
     @Override
     public void handleMessage(Message msg) {
         if(msg.what==1) {

             Notification notification = new Notification();
             notification.scheduleDismiss(kProgressHUD);
             swipeContainer.setRefreshing(false);
             new JsonReadingModel(mActivity,homeApiResponse);
             homeScreenBusinessAdapter.notifyDataSetChanged();
         }
     }
 };

here is my okhttp class method for getting response and i get response in onResponse method but its give me null in activity code

 OkHttpClient client = new OkHttpClient();
    String mResponse;
    public String getOkHttpRequest(String url) {
        try {

            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 {
                    mResponse=response.body().string();


                }
            });

            return mResponse;


        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

Upvotes: 0

Views: 5247

Answers (1)

Robert Estivill
Robert Estivill

Reputation: 12487

You are returning mResponse before the callback gets executed due to async nature of the callback.

Option 1) Make your request sync

// Instead of 
client.newCall(request).enqueue( )

// Use 
String body = client.newCall(request).execute( ).body().toString();

Option 2) Make the method async and return when the callback is called

// Instead of 
public String getOkHttpRequest(String url) { }

// Change method to 
public void getOkHttpRequest(String url) { }

// And have your callback continue your logic
client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
               // TODO handle error correctly, instead of try/catch
            }

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

                // TODO call method that uses the response values
            }
        });

Upvotes: 3

Related Questions