This is a movies sample app in Kotlin, which is part of a serie of blog posts I have written about architecting android application using different approaches.
"Unsafe" cast operator should be nullable
Extension networkInfo on context should return NetworkInfo?, otherwise causes runtime crash.
This derrives from the abstract getSystemService which is annotated as Nullable
Also, as per Kotlin documentation about "Unsafe" cast operator (can be found here) In order to match Java cast semantics we have to have nullable type at cast right hand side
Ways to reproduce, just launch the app with no network connectivity and it crashes with logcat:
Process: com.fernandocejas.sample, PID: 6453
java.lang.IllegalStateException: (this.getSystemService(C…anager).activeNetworkInfo must not be null
at com.fernandocejas.sample.core.extension.ContextKt.getNetworkInfo(Context.kt:23)
at com.fernandocejas.sample.core.platform.NetworkHandler.isConnected(NetworkHandler.kt:29)
at com.fernandocejas.sample.features.movies.MoviesRepository$Network.movies(MoviesRepository.kt:37)
at com.fernandocejas.sample.features.movies.GetMovies.run(GetMovies.kt:25)
at com.fernandocejas.sample.features.movies.GetMovies.run(GetMovies.kt:22)
at com.fernandocejas.sample.core.interactor.UseCase$execute$job$1.doResume(UseCase.kt:38)
at kotlin.coroutines.experimental.jvm.internal.CoroutineImpl.resume(CoroutineImpl.kt:54)
at kotlinx.coroutines.experimental.DispatchedTask$DefaultImpls.run(Dispatched.kt:161)
at kotlinx.coroutines.experimental.DispatchedContinuation.run(Dispatched.kt:25)
at java.util.concurrent.ForkJoinTask$RunnableExecuteAction.exec(ForkJoinTask.java:1412)
at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:285)
at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1152)
at java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1990)
at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1938)
at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)
Device used: Android Emulator API 26
Solution 1:
networkInfo extension should return a nullable type for method named networkInfo, Usages of networkHandler.isConnected should handle null case
"Unsafe" cast operator should be nullable Extension
networkInfo
oncontext
should returnNetworkInfo?
, otherwise causes runtime crash.This derrives from the abstract
getSystemService
which is annotated asNullable
Also, as per Kotlin documentation about "Unsafe" cast operator (can be found here) In order to match Java cast semantics we have to have nullable type at cast right hand side
Ways to reproduce, just launch the app with no network connectivity and it crashes with logcat:
Device used: Android Emulator API 26
Solution 1: networkInfo extension should return a nullable type for method named
networkInfo
, Usages ofnetworkHandler.isConnected
should handle null caseSolution 2: Wrap it as an Optional