We will need to handle and detect the offline error in Retrofit call, It is a basic requirement when we are implementing Offline Application or visible network error view.
How can it be possible?
Essentially, we will create a class that implements Interceptor so that we can perform a network connectivity and checks before executing the request.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
public class NetworkConnectionInterceptor implements Interceptor { private Context mContext; public NetworkConnectionInterceptor(Context context) { mContext = context; } @Override public Response intercept(Chain chain) throws IOException { if (!isOnline()) { throw new NoConnectivityException(); } Request.Builder builder = chain.request().newBuilder(); return chain.proceed(builder.build()); } public boolean isOnline(){ ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo(); return (netInfo != null && netInfo.isConnected()); } } |
NetworkConnectionInterceptor interceptor will handle every API call, when, if no network is found then it interrupts the normal flow of execution so we will create our own NoConnectivityException Exception class. that throws an Exception.
1 2 3 4 5 6 7 8 |
public class NoConnectivityException extends IOException { @Override public String getMessage() { return "Network Connection exception"; } } |
Add NetworkConnectionInterceptor with our retrofit Service client.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
public class RetrofitClient { private static Retrofit retrofit = null; public static Retrofit getClient(Context mContext) { if (retrofit == null) { CookieManager cookieManager = new CookieManager(); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient.Builder oktHttpClient = new OkHttpClient.Builder() .connectTimeout(DEFAULT_CONNECT_TIMEOUT_IN_MIN, TimeUnit.MINUTES) .writeTimeout(DEFAULT_WRITE_TIMEOUT_IN_MIN, TimeUnit.MINUTES) .readTimeout(DEFAULT_READ_TIMEOUT_IN_MIN, TimeUnit.MINUTES) .addInterceptor(new NetworkConnectionInterceptor(mContext)) .cookieJar(new JavaNetCookieJar(cookieManager)); oktHttpClient.addInterceptor(logging); retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(oktHttpClient.build()) .build(); } return retrofit; } } |
Finally, Detect Offline connection Exception in our Activity, Handler or Fragment.
1 2 3 4 5 6 7 8 |
@Override public void onFailure(Call<BaseModel> call, Throwable t) { Log.d(TAG, "onResponse: 3"); if(t instanceof NoConnectivityException) { t.printStackTrace(); returnResponseFromOffLineDB((Activity) mContext); } } |