2

I am developing an android app with kotlin MVVM pattern, the problem is I am fetching data from net and even I put an exception for times with no internet connection, even though the app always crashes with LOGCAT : Illegal exception : can not connect to ..... Any help with that please? I tried to add interceptor and after that catch this :

class NoConnectivityException () : IOException()
class ApiException() : IOException()

//and inside reopistory 
//

try {
            val fetchData =
                retrofitInterface
                    .getAll()
                    .await()
            _downloadedResponse.postValue(fetchData)
        } catch (e: NoConnectivityException) {

        } catch (a: ApiException) {

        }


//my interceptor interface :
interface ConnectivityInteceptor : Interceptor
//my interceptor implementation :

class ConnectivityInteceptorImpl(
    context: Context
) : ConnectivityInteceptor {
    private val appContext = context.applicationContext
    override fun intercept(chain: Interceptor.Chain): Response {
        if (!isOnLine())
            throw NoConnectivityException()
        return chain.proceed(chain.request())
    }

    private fun isOnLine(): Boolean {
        val connectivityManager = appContext.getSystemService(Context.CONNECTIVITY_SERVICE)
                as ConnectivityManager
        val networkInfo  = connectivityManager.activeNetworkInfo
        return networkInfo != null && networkInfo.isConnected

    }
}
Ali Ahmed
  • 2,425
  • 2
  • 8
  • 13

2 Answers2

0

To detect internet connection on a device, in addition to your above code, you need to add permission in your manifest.

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Madhura
  • 61
  • 3
0

You can use this library for all request.

RetrofitHelper library written in kotlin, will let you make API calls, using a few lines of code.

Add headers in your application class like this :

class Application : Application() {

    override fun onCreate() {
    super.onCreate()

        retrofitClient = RetrofitClient.instance
                    //api url
                .setBaseUrl("https://reqres.in/")
                    //you can set multiple urls
        //                .setUrl("example","http://ngrok.io/api/")
                    //set timeouts
                .setConnectionTimeout(4)
                .setReadingTimeout(15)
                    //enable cache
                .enableCaching(this)
                    //add Headers
                .addHeader("Content-Type", "application/json")
                .addHeader("client", "android")
                .addHeader("language", Locale.getDefault().language)
                .addHeader("os", android.os.Build.VERSION.RELEASE)
            }

        companion object {
        lateinit var retrofitClient: RetrofitClient

        }
    }  

And then make your call:

retrofitClient.Get<GetResponseModel>()
            //set path
            .setPath("api/users/2")
            //set url params Key-Value or HashMap
            .setUrlParams("KEY","Value")
            // you can add header here
            .addHeaders("key","value")
            .setResponseHandler(GetResponseModel::class.java,
                object : ResponseHandler<GetResponseModel>() {
                    override fun onSuccess(response: Response<GetResponseModel>) {
                        super.onSuccess(response)
                        //handle response
                    }
                }).run(this)

For more information see the documentation

Aryan Moradi
  • 127
  • 5
  • I did not hear about this library before and actually I don't know how to use it.... any code you have tried? according to what you have written above, I need to put the url in each call? is that right ? – Ali Ahmed Oct 01 '19 at 12:32
  • No you put base URL in application > retrofitClient one time, and you can use retrofitClient everywhere. You can configuration [configuration](https://github.com/G-Corporation/RetrofitHelper/wiki/Configuration) first "one time". And use library everywhere like [this](https://github.com/G-Corporation/RetrofitHelper/wiki/API-calls). You can see [example application](https://github.com/G-Corporation/RetrofitHelper/tree/master/app/src) – Aryan Moradi Oct 03 '19 at 07:19