Handler post is not working in Kotlin Android
Asked Answered
C

3

9

Could someone show me what is wrong?

I try to use a Handler post a Runnable but it's not execute

var mHandler: Handler? = null

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    mHandler = Handler()
    var runnable = Runnable {
        Log.d("TEST", "++++ runable")
        Log.d("TEST", "++++ come end")
    }
    Log.d("TEST", "++++ runnable" + runnable)
    Log.d("TEST", "++++ handle" + mHandler)
    mHandler!!.post { runnable }
}

This is output

09-21 00:56:04.067 4419-4419/? D/TEST: ++++ runnablecom.vpioneer.activity.MainActivity$onCreate$runnable$1@529b8fb4 09-21 00:56:04.067 4419-4419/? D/TEST: ++++ handleHandler (android.os.Handler) {529b8cb4}

Cassicassia answered 21/9, 2017 at 8:25 Comment(1)
I would recommend changing your first line to lateinit var mHandler: Handler since you are creating it onCreate. Then you don't need to worry about the nullability concerns.Axinomancy
W
23

First at all, don't use !! operator, it is a very bad practice (from the doc). With ? you will reach the same behaviour but checking if the instance became null before executing it.

Saying this, using:

mHandler?.post { runnable }

You are actually creating a new lambda containing runnable line. see here below in a more readable way:

mHandler?.post { 
   runnable 
}

This is the equivalent in Java:

mHandler.post(new Runnable(){
    public void run(){
        runnable;
    }
});

To solve this:

Option 1: getting rid of the runnable declaration

mHandler?.post { /*the content of your runnable*/ }

Option 2: using your runnable instance

mHandler?.post(runnable) // normal parentheses

Option 3: crazy way

mHandler?.post { runnable.run() }
Windowlight answered 21/9, 2017 at 8:34 Comment(3)
Thank you very much, My big mistakeCassicassia
I made the same mistake. Thank you sir for pointing that out.Irrespirable
!! is not necessarily bad practice if something absolutely shouldn't be null. Otherwise problem might be masked. On the other hand ?. will suffice and be preferred for most situations.Oceanid
R
3

Try this code, I hope this is working

   Handler().postDelayed({
            // You code and delay time
   }, 1000L)
Rilda answered 17/4, 2018 at 8:31 Comment(1)
Thx @NajibAhmedPuthawala , Upvoted for saving my dayRhombus
M
1

You are not starting runnbale. Try this:

mHandler!!.post { runnable.run() }

This is also valid:

mHandler!!.post { 
    Log.d("TEST", "++++ runable")
    Log.d("TEST", "++++ come end")
}
Minutiae answered 21/9, 2017 at 8:26 Comment(1)
I get an error: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()Mohock

© 2022 - 2024 — McMap. All rights reserved.