I'm using following code :
public void addConditions(){
final String arriveHourse, departHourse, arriveMinutes, departMinutes;
TimePickerDialog.OnTimeSetListener departOnTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int selectedHours, int selectedMinutes) {
departHourse = String.valueOf(selectedHours);
departMinutes = String.valueOf(selectedMinutes);
}
};
...
}
Why the IDE asked me to transform departHourse
into final array ?
Why this happened, and how i can avoid that ?
Also if i moved variable outside class, it's work like :
String arriveHourse, departHourse, arriveMinutes, departMinutes;
public void addConditions(){
TimePickerDialog.OnTimeSetListener departOnTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int selectedHours, int selectedMinutes) {
departHourse = String.valueOf(selectedHours);
departMinutes = String.valueOf(selectedMinutes);
}
};
...
}
departHourse
is a final variable. It has to be, in order to be used within the anonymous inner class. That means you can't assign a new value to it in the anonymous inner class.
One way around that is to create a single-element array instead:
final String[] valueHolder = new String[1];
...
Foo foo = new Foo() {
@Override public void bar() {
valueHolder[0] = "Set in bar";
}
}
An alternative is to use AtomicReference
:
final AtomicReference<String> valueHolder = new AtomicReference<String>();
...
Foo foo = new Foo() {
@Override public void bar() {
valueHolder.set("Set in bar");
}
}
In both cases, this allows you to make new information available without changing the value of the valueHolder
variable itself.
See more on this question at Stackoverflow