Search code examples
androidmultithreadinghandler

calling Handler from a Thread leads to NullPointerException


I need to call the Handler from a Thread, Here is my Thread:

new Thread(){
    public void run(){
        try{
            Thread.sleep(2000); 
        }
        catch(Exception ex){}

        actHandler.sendEmptyMessage(0);
    }}.start();

I'm calling the Handler like this

actHandler=new Handler(){
    public void handleMessage(android.os.Message msg){

    }
};

Some times its working fine and some times it leads to a NullPointerException at the line actHandler.sendEmptyMessage(0);

Here is all my code:

public class Casinos extends Activity {
    ProgressDialog pd;
    Handler actHandler;

    @Override
    public void onCreate(Bundle bundle){
        super.onCreate(bundle);
        pd=ProgressDialog.show(this,"","Please wait...");
        new Thread(){
            public void run(){
            try{
                Thread.sleep(2000); 
            }
            catch(Exception ex){}

            actHandler.sendEmptyMessage(0);
        }}.start();

        setContentView(R.layout.casinos);

        actHandler = new Handler(){
        public void handleMessage(android.os.Message msg){
            super.handleMessage(msg);
                pd.dismiss();
        }};

    }

}

What to do?

Thanks in advance.


Solution

  • You may have instantiated actHandler after the new Thread() statement.

    actHandler = new Handler();
    

    Please show us some more code to verify but this is probably the case.

    SOLUTION

    You have initialised actHandler after the Thread declaration

    public class Casinos extends Activity {
        ProgressDialog pd;
        Handler actHandler;
        @Override
        public void onCreate(Bundle bundle){
            super.onCreate(bundle);
            pd=ProgressDialog.show(this,"","Please wait...");
            //move this HERE!!
            actHandler=new Handler(){
                public void handleMessage(android.os.Message msg)
                {
                    super.handleMessage(msg);
                    pd.dismiss();
                }
            };
    
            new Thread(){
                public void run(){
                    try{
                        Thread.sleep(2000); 
                    }
                    catch(Exception ex){}
                    actHandler.sendEmptyMessage(0);
                }
            }.start();
            setContentView(R.layout.casinos);
        }
    }