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.
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.
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);
}
}
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)
精彩评论