skip to Main Content

Why the lines are crossed out and the error where the dot is I don’t understand

package com.ggenius.whattowearkotlin.data.network

import android.content.Context
import android.net.ConnectivityManager
import com.ggenius.whattowearkotlin.internal.NoConnectivityException
import okhttp3.Interceptor
import okhttp3.Response

class ConnectivityInterceptorImpl(
    context: Context?
) : ConnectivityInterceptor {

    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
    }
}

Check screenshot
enter image description here

2

Answers


  1. This line is crossed out

    val networkInfo = connectivityManager.activeNetworkInfo
    

    Because the getActiveNetworkInfo() method is deprecated according to their API

    https://developer.android.com/reference/android/net/ConnectivityManager#getActiveNetworkInfo()

    Login or Signup to reply.
  2. Why the lines are crossed out?

    The lines are crossed out because they are Deprecated. In Android Studio by default the deprecated use of functions, classes, variables etc. are styled as strikeout. You want to know why? It’s because by default settings it’s set as so. Here is Screenshot enter image description here

    Why the error where the dot is I don’t understand?

    The context.applicationContext is showing error because your context is nullable. Whenever you define your variable with Type followed by ? is nullable in Kotlin.

    As you passing context: Context?, so context is nullable. To access nullable objects properties or methods you need to use objectName followed by ?. This prevents the NullPointerException that makes Kotlin null safe.

    In you example you need to do;

    private val appContext = context?.applicationContext 
    // Note that appContext will also be nullable.
    

    Further Reading

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search