问题
I'm trying to access the h
variable in the inner class but an error keeps showing up "Cannot assign a value to final variable h
". I tried quick-fix and it instructed me to "Transform h to final one element array".What does that mean?
int Update ()
{
final int h;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
preferences.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key.equalsIgnoreCase("PINCODE"))
{
h = sharedPreferences.getInt(key,0);
}
}
});
return h;
}
}
回答1:
From the inner class you can't assign value to a local variable (itself) declared somewhere in the enclosing class, but you can change state (call methods, setters, ...) of the referenced object (if the variable points to some object and not to a primitive type). And array is object.
Check Java language specification - section about inner classes.
回答2:
The variable must be assigned as static in class MainActivity.
static int h;
来源:https://stackoverflow.com/questions/44990764/why-should-i-transform-myvariable-to-final-one-element-array