Android - onCreate() 方法中的 Final int 字段
是否可以在 Service 类中声明一个 Final int 字段,并使用 onCreate() 方法中从数据库查询中获得的一些整数来初始化它?
public class MyService extends Service
{
private int id;
@Override
public void onCreate()
{
... calculate id value ...
id = <id value derived>;
}
}
我在 Eclipse 中的字段赋值行上的方法 onCreate() 内收到此错误:
"The final field cannot be id cannot be assigned"
在类定义行上收到此错误:
"The blank final field id may not have been inizialized"
就我而言,这是定义只想初始化一次的字段的正确方法。谁能帮助我吗?谢谢
Is is possible to declare an final int field in a Service class and initialize it with some integer I get from a query to database in the onCreate() method?
public class MyService extends Service
{
private int id;
@Override
public void onCreate()
{
... calculate id value ...
id = <id value derived>;
}
}
I got this error in Eclipse inside the method onCreate() on the field assignment line:
"The final field cannot be id cannot be assigned"
and this error on the class definition line:
"The blank final field id may not have been inizialized"
As far as I now, this is the right way to define a field that you want to initialize only once. Can anyone help me? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
onCreate() 是创建 Activity 时从操作系统调用的特定方法,因此它是在 Activity 的构造函数之后调用的。您必须在调用 onCreate() 之前分配最终字段。
onCreate() is specific method called from the OS when your activity is created so it's called after the constructor of the Activity. You have to assign your final fields before onCreate() is called.
不,你不能在onCreate中初始化它。在声明
或类构造函数中初始化它
No, you can't initialize it in onCreate. Initialize it on declaration
or in class constructor
只需在 Activity 之上定义您的 ID,如下所示:
public Final static int id = 5
。应该这样做。simply define your id on top of activity like this:
public final static int id = 5
. That should do.