Home » Java » Android – Final int field inside onCreate() method

Android – Final int field inside onCreate() method

Posted by: admin December 28, 2021 Leave a comment

Questions:

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

Answers:

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.

###

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;
    }
}

###

simply define your id on top of activity like this: public final static int id = 5. That should do.