从线程调用 Handler 会导致 NullPointerException
我需要从 Thread
调用 Handler
,这是我的 Thread
:
new Thread(){
public void run(){
try{
Thread.sleep(2000);
}
catch(Exception ex){}
actHandler.sendEmptyMessage(0);
}}.start();
我像这样调用 Handler
有时
actHandler=new Handler(){
public void handleMessage(android.os.Message msg){
}
};
它工作正常,有时它会导致该行出现 NullPointerException
actHandler.sendEmptyMessage(0);
这是我的所有代码:
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();
}};
}
}
该怎么办?
提前致谢。
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 lineactHandler.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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试这样:
在您的情况下,如果处理消息队列的循环器正在退出,那么它将返回失败。
try like this:
In your case if the looper processing the messsage queue is exiting then it will return failure.
您可能在
new Thread()
语句之后实例化了actHandler
。请向我们展示更多代码来验证,但情况可能就是这样。
解决方案
您已在线程声明后初始化了
actHandler
You may have instantiated
actHandler
after thenew Thread()
statement.Please show us some more code to verify but this is probably the case.
SOLUTION
You have initialised
actHandler
after the Thread declaration在哪里初始化
actHandler
?如果是在其他线程中,请确保之前调用了初始化。 (最好的办法可能是尽快初始化)
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)