Search code examples
androidhandlerandroid-handlerandroid-handlerthread

android Handler gives Null object reference error


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


Solution

  • 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