surendra
surendra

Reputation: 2277

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.

Upvotes: 1

Views: 7310

Answers (3)

Sherif elKhatib
Sherif elKhatib

Reputation: 45942

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

Upvotes: 1

Vineet Shukla
Vineet Shukla

Reputation: 24031

try like this:

Message msg = new Message();
msg.arg1 = int value;
actHandler.sendMessage(msg);

In your case if the looper processing the messsage queue is exiting then it will return failure.

Upvotes: 2

Täg
Täg

Reputation: 431

Where do you initialize your actHandler?

If it is in another thread, be sure that the initialization is called before. (the best thing to do may be an initialization as soon as you can)

Upvotes: 1

Related Questions