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
This line is crossed out
Because the
getActiveNetworkInfo()
method is deprecated according to their APIhttps://developer.android.com/reference/android/net/ConnectivityManager#getActiveNetworkInfo()
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
Why the error where the dot is I don’t understand?
The
context.applicationContext
is showing error because yourcontext
is nullable. Whenever you define your variable withType
followed by?
is nullable inKotlin
.As you passing
context: Context?
, so context is nullable. To access nullable objects properties or methods you need to useobjectName
followed by?
. This prevents theNullPointerException
that makes Kotlin null safe.In you example you need to do;
Further Reading