javaandroidandroid-handler

Handler is abstract ,cannot be instantiated


I am trying to use a Handler in my app. However, when I instantiate it like this:

Handler handler = new Handler();

I get the following error:

Gradle: error: Handler is abstract; cannot be instantiated

And when I check the solutions, it asks me to implement these methods:

Handler handler = new Handler() {
    @Override
    public void close() {
        
    }

    @Override
    public void flush() {

    }

    @Override
    public void publish(LogRecord record) {

    }
};

I have never used Handlers before and I am using it just to call a method after some delay. To achieve that, I've used:

handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            //Do something after 100ms
        }
    }, 100);

But it shows the error:

Gradle: error: cannot find symbol method postDelayed(,int)


Solution

  • It seems you have imported a wrong Handler class

    import java.util.logging.Handler;
    

    Change it to

    import android.os.Handler;