Пожалуйста, следуйте инструкциям, которыми я делюсь с вами, это эффективный способ сделать что-то.
Убедитесь, что вы сначала внедрили ResponseHandler в свою деятельность или фрагмент.
Реализация ResponseHandler: -
public class SettingsActivity extends Activity implements ResponseHandler {}
Позвоните в API: -
//AppManager is my application class of project.
new RestCaller(SettingsActivity.this,
AppManager.getRestClient().pushNotification("auth_token", status), 1);
Ответ: -
@Override
public void onSuccess(Call call, Response response, int reqCode) {
Utility.dismissProgressDialog(progressDialog);
if (reqCode == 1) {
//call another api like I mentioned above with other request code
}
}
Это класс ApiInterface.
public interface ApiInterface {
@GET("updateNotificationClinic")
Call<UpdateClinic> pushNotification(@Query("auth_token") String token,
@Query("pushNotification") String push);
}
Создать этот класс.
public interface ResponseHandler {
void onSuccess(Call call, Response response, int reqCode);
void onFailure(Call call, GenericResponse error, int reqCode);
void onApiCrash(Call call, Throwable t, int reqCode);
}
Создать класс RestCaller.
public class RestCaller {
private int REQ_CODE = 0;
ResponseHandler handler;
public RestCaller(ResponseHandler context, Call caller, final int REQUEST_CODE) throws NumberFormatException {
if (REQUEST_CODE <= 0) {
NumberFormatException ex = new NumberFormatException();
throw ex;
}
REQ_CODE = REQUEST_CODE;
handler = context;
ENQUE(caller);
}
private void ENQUE(Call call) {
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
if (response.code() == 200 | response.code() == 201) {
handler.onSuccess(call, response, REQ_CODE);
} else if (response.code() == 403) {
Toast.makeText(AppManager.getAppContext(), "Code: 403", Toast.LENGTH_SHORT).show();
} else {
GenericResponse error = null;
Converter<ResponseBody, GenericResponse> errorConverter =
AppManager.getRetrofit().responseBodyConverter(GenericResponse.class, new Annotation[0]);
try {
error = errorConverter.convert(response.errorBody());
} catch (IOException e) {}
if (error != null)
handler.onFailure(call, error, REQ_CODE);
else
handler.onApiCrash(call, new Throwable(response.raw().message()), REQ_CODE);
}
}
@Override
public void onFailure(Call call, Throwable t) {
if (t instanceof UnknownHostException)
handler.onApiCrash(call, new Throwable("Unable to access server. Please check your connection."), REQ_CODE);
else
handler.onApiCrash(call, t, REQ_CODE);
}
});
}
}
Создание класса RetroClient.
public class RetroClient {
private Retrofit retrofit = null;
private static RetroClient object;
private RetroClient() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.readTimeout(60, TimeUnit.SECONDS);
httpClient.connectTimeout(60, TimeUnit.SECONDS);
httpClient.addInterceptor(logging.setLevel(HttpLoggingInterceptor.Level.BODY));
retrofit = new Retrofit.Builder()
.baseUrl(Config.retrofit_base_url)
.addConverterFactory(StringConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
service = retrofit.create(ApiInterface.class);
}
public static RetroClient getRetroClient() {
if (object == null) {
object = new RetroClient();
} else if (object != null && !object.getRetrofit().baseUrl().toString().equalsIgnoreCase(Config.retrofit_base_url)) {
object = new RetroClient();
}
return object;
}
//this is your class where you set your api's.
private ApiInterface service;
public ApiInterface getApiServices() {
return object.service;
}
public Retrofit getRetrofit() {
return object.retrofit;
}
}
Установите эти методы в своем классе приложения.
public static ApiInterface getRestClient() {
return RetroClient.getRetroClient().getApiServices();
}
public static Retrofit getRetrofit() {
return RetroClient.getRetroClient().getRetrofit();
}