Android - onCreate() 方法中的 Final int 字段

发布于 2024-10-28 03:05:35 字数 569 浏览 0 评论 0原文

是否可以在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

命硬 2024-11-04 03:05:35

最后必须明确分配一个空白的最终实例变量
声明它的类的每个构造函数;否则会出现编译时错误。

onCreate() 是创建 Activity 时从操作系统调用的特定方法,因此它是在 Activity 的构造函数之后调用的。您必须在调用 onCreate() 之前分配最终字段。

A blank final instance variable must be definitely assigned at the end
of every constructor of the class in which it is declared; otherwise a compile-time error occurs.

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.

芸娘子的小脾气 2024-11-04 03:05:35

不,你不能在onCreate中初始化它。在声明

private final int id = 5;

或类构造函数中初始化它

public class MyClass extends Activity {
    private final int id;

    public MyClass() {
        id = 10;
    }
}

No, you can't initialize it in onCreate. Initialize it on declaration

private final int id = 5;

or in class constructor

public class MyClass extends Activity {
    private final int id;

    public MyClass() {
        id = 10;
    }
}
秋凉 2024-11-04 03:05:35

只需在 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文