Ayush Gupta
Ayush Gupta

Reputation: 9295

Call a method in the calling class on API success in android

I use the following class to make an API call in android using Retrofit

public Class Checkin {

    public static void checkinViaApi(CheckinSendModel checkinSendModel) {

        final ApiHandler apiHandler = new ApiHandler();
        apiHandler.setApiResponseListener(new ApiResponseListener() {

            @Override
            public void onApiResponse(ApiResponseModel apiResponse) {
                Log.i("CheckedIn","true");
            }

            @Override
            public void onApiException(Error error) {
                Log.i("fail",error.getErrorMessage());

            }
        });

        List<CheckinSendModel> checkinSendModelList = new ArrayList<CheckinSendModel>();
        checkinSendModelList.add(checkinSendModel);
        Call<ApiResponseModel> request = RetrofitRestClient.getInstance().checkinToMainEvent(checkinSendModelList,Constant.API_KEY);
        apiHandler.getData(request);
    }
}

I call that method as follows:

Checkin.checkinViaApi(checkinSendModelObject);

Now, when the API call is successful, I want to execute a function checkedInSuccessfully() in the class from where I make the call. How can I do it?

Thanks in advance

Upvotes: 0

Views: 664

Answers (2)

Samuel Robert
Samuel Robert

Reputation: 11032

Interface is your handy man. Create an interface like below.

 Interface CheckInListener {
      void onCheckIn();
 }

Change the checkinViaApi() to below signature.

public static void checkinViaApi(CheckinSendModel checkinSendModel, CheckinListener listener) {
     @Override
     public void onApiResponse(ApiResponseModel apiResponse) {
            Log.i("CheckedIn","true");
            listener.onCheckIn();
      }
}

When you call the above function you can provide an instance of the interface.

Checkin.checkinViaApi(checkinSendModelObject, new CheckInListener() {
      @Override
      void onCheckIn() {
                //Do your action here
      }
});

Upvotes: 1

OneCricketeer
OneCricketeer

Reputation: 191748

Pass in the response interface.

public class Checkin {

    public static void checkinViaApi(CheckinSendModel checkinSendModel, ApiResponseListener listener) {

        final ApiHandler apiHandler = new ApiHandler();
        apiHandler.setApiResponseListener(listener);

Other class - Call that method

CheckinSendModel model;
Checkin.checkinViaApi(model, new ApiResponseListener() {

        @Override
        public void onApiResponse(ApiResponseModel apiResponse) {
            Log.i("CheckedIn","true");
            checkedInSuccessfully();
        }

        @Override
        public void onApiException(Error error) {
            Log.i("fail",error.getErrorMessage());

        }
);

Upvotes: 2

Related Questions