android Handler gives Null object reference error

3.1k views Asked by At

My Process is Updated the ProgressBar in the UI thread by using Handler.but it gives an error like this.
.Handler.sendMessage(android.os.Message)' on a null object reference
Plese check my code

public class MainActivity extends AppCompatActivity {
    Handler handler;
    Thread thread;
    ProgressBar prb;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        prb=(ProgressBar) findViewById(R.id.progress);
        thread=new Thread(new MyThread());
        thread.start();
        handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                prb.setProgress(msg.arg1);
            }
        };
    }


    class MyThread implements Runnable{

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

It clearly show that error is form here,

handler.sendMessage(message);

2

There are 2 answers

1
beal On BEST ANSWER

In your code, you have your own implementation of a Thread called MyThread. In this implementation you're using a reference of your global variable handler.

The problem is: You are trying to instantiate your MyThread before intantiating your handlervariable. So handleris null when you call thread.start()

The Solution is quiet simple:

You need to start your Thread after initializing the Handler

0
Claudio Redi On

Since you're starting the new thread before handler=new Handler(), handler will be null at the beginning. Change onCreate to this

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    prb=(ProgressBar) findViewById(R.id.progress);

    // moved handler initialization
    handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            prb.setProgress(msg.arg1);
        }
    };


    thread=new Thread(new MyThread());
    thread.start();
}