Search code examples
androidkotlinstatic-analysiskotlin-null-safety

Kotlin Null safety issue for Nullable return from Java method in Android


I have Handler which will process Message in Background Thread. When creating Handler, i have to pass Looper in constructor and its not Nullable. To get the Looper from background Thread i have to call Looper.myLooper() api and its return type is Nullable. So here issue arise as return type is Nullable i have to forcefully use Not-Null Assertion (!!) Operator.

This will create some static analysis issue in my project.Is there any way i can get rid from !! operator.

I want to know how others handle this issue.

Here is my sample code

private lateinit var myHandler : MyHandler 
............................................

val executor = Executors.newSingleThreadExecutor()
executor.execute {
    Looper.prepare()
    myHandler = MyHandler(Looper.myLooper()!!)
    Looper.loop()
}

private inner class MyHandler(looper: Looper) : Handler(looper) {
    override fun handleMessage(msg: Message) {
        super.handleMessage(msg)
        //..................
    }
}

Thanks in advance.


Solution

  • I really wouldn't be using a SingleThreadExecutor with a looper like that. Just use a Thread, or better yet a HandlerThread. You gain no benefit from making it an executor here. You also won't have this problem because the setup is done for you in HandlerThread. And using a Looper would interfere with the scheduling logic of the Executor, because its never returning to the executor- its stopping in the looper.

    Ignoring that- the answer here is to turn off the static analysis for this function. Sometimes they bring up false positives. That's why annotations like @SuppressWarnings exist, to tell tools that a particular usage is ok. You're in a situation where you know that a null can't actually happen, but the compiler doesn't have that knowledge of the functions. This is exactly where those annotations are meant to be used.

    The other thing you can do is just put an if statement and throw an exception if it ever returns null. But I find that not only pointless, but less clear- you're adding extra code to check for a condition you know can't occur. I'd rather have the suppress annotation with possibly a comment on it as to why.