Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Final int field inside onCreate() method

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

like image 225
PinoSan Avatar asked Mar 28 '11 18:03

PinoSan


2 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.

like image 75
Mojo Risin Avatar answered Oct 10 '22 01:10

Mojo Risin


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;
    }
}
like image 31
Olegas Avatar answered Oct 10 '22 01:10

Olegas