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
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With