无法从 Handler 类型对非静态方法 sendEmptyMessage(int) 进行静态引用
我遇到错误“无法从 Handler 类型对非静态方法 sendEmptyMessage(int) 进行静态引用”
如何修复?我认为这是一个问题,我所做的这门课不是一个活动?
new Thread() {
public void run() {
try {
List<Sail> sails = searchSails();
selectSailIntent.putParcelableArrayListExtra(
Constant.SAILS, new ArrayList<Sail>(sails));
getContext().startActivity(selectSailIntent);
Handler.sendEmptyMessage(0);
} catch (Exception e) {
alertDialog.setMessage(e.getMessage());
Handler.sendEmptyMessage(1);
}
}
}.start();
}
};
I have an error "Cannot make a static reference to the non-static method sendEmptyMessage(int) from the type Handler"
How to fix it? As I think this is a problem that this class where I do this is not an activity?
new Thread() {
public void run() {
try {
List<Sail> sails = searchSails();
selectSailIntent.putParcelableArrayListExtra(
Constant.SAILS, new ArrayList<Sail>(sails));
getContext().startActivity(selectSailIntent);
Handler.sendEmptyMessage(0);
} catch (Exception e) {
alertDialog.setMessage(e.getMessage());
Handler.sendEmptyMessage(1);
}
}
}.start();
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为
Handler
引用一个类,但sendEmptyMessage
不是静态方法(应该在对象上调用,而不是在类上调用)。为了能够调用
sendEmptyMessage
方法,您将需要实例化一个
Handler
,即执行类似的操作或
将
static
修饰符添加到sendEmptyMessage
方法:This is due to the fact that
Handler
refers to a class, butsendEmptyMessage
is not a static method (should be called on an object, and not on a class).To be able to call the
sendEmptyMessage
method you will eitherNeed to instantiate a
Handler
, i.e., do something likeor
Add the
static
modifier to thesendEmptyMessage
method:为了调用非静态方法(也称为实例方法),您必须引用特定对象(实例)。您无法引用该类。
静态方法可以通过仅引用类来调用(也可以通过对该类的对象的引用来调用它们,但这被认为是不好的做法)。
关于用法:当您创建实例(对象)时,该对象具有一些内部数据(状态)。非静态方法利用所引用对象的状态,静态方法不需要该数据)。
In order to invoke a non-static method (aka instance methods) you must refer to a particular object (instance). You cannot refer to the class.
Static methods can be invoked by referencing only the class (they can also be called from a reference to an object of that class, but that is considered bad practice).
About usage: when you create an instance (object), that object has some inner data (state). Non static methods make use of the state of the object that is referenced, static methods do not need that data).