0

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();
            }

        }
Mauker
  • 11,237
  • 7
  • 58
  • 76
Dan Hunter
  • 1
  • 1
  • 1

3 Answers3

1

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.

Daniel F
  • 13,684
  • 11
  • 87
  • 116
  • 2
    Don't write things like "Leave a like" please, it is denigrating to the purpose of the site – Mixone Jan 13 '18 at 16:51
0

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!

Appafly
  • 656
  • 2
  • 6
  • 24
0

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

Bertram Gilfoyle
  • 9,899
  • 6
  • 42
  • 67