Dan Hunter
Dan Hunter

Reputation: 1

Error when using handlers Attempt to invoke virtual method 'boolean android.os.Handler.sendMessage

I am getting a

E/AndroidRuntime: FATAL EXCEPTION

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.os.Handler.sendMessage(android.os.Message)' on a null object reference at com.example.android.slidenerd180handler.MainActivity$MyThread.run(MainActivity.java:37)

I am not sure why it is not working, I did everything that it said in this tutorial video on youtube for android handler, but it still doesn't work.

the line 37 is handler.sendMessage(message);

    class MyThread implements Runnable {


    @Override
    public void run() {
        for(int i =0;i<100;i++){
            Message message = Message.obtain();
            message.arg1=i;
            handler.sendMessage(message);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

Upvotes: 0

Views: 7177

Answers (3)

Mohamed Rmadan
Mohamed Rmadan

Reputation: 11

It does not work if you do not make sure that the Handler is initialized before you send a message.

For that, you can make your thread sleep for a few ms (like 2 ms) before sending the message. The fact is that when the UIThread is running thread.start(), the secondary thread (the one implementing Runnable) starts.

The loop in the run() method starts and the instruction handler.sendMessage(message) is executed by the secondary thread before the instruction handler = new Handler() can be read by the UIThread.

You can't be sure that it will always happens this way so you have to make sure the Handler is initialized first. You can put Thread.sleep(100); into the run() section of the secondary thread.

Upvotes: 1

Bertram Gilfoyle
Bertram Gilfoyle

Reputation: 10235

You are starting MyThread before handler is initialized(I guess from onCreate() of activity). Initialize handler before it MyThread executes.

Upvotes: 0

Appafly
Appafly

Reputation: 666

This error means that you are trying to send a message that is null. In other words, the message is empty. Check where you are obtaining the message and make sure that there is not a chance that the message will be null.

Before sending the message, you should add an if statement. Try replacing your code with this:

class MyThread implements Runnable {

@Override
public void run() {
    for(int i =0;i<100;i++){
        Message message = Message.obtain();
        if(message != null){
            message.arg1=i;
            handler.sendMessage(message);
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

Hope this helps!

Upvotes: 0

Related Questions