7

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

}

OLIVER.KOO
  • 5,654
  • 3
  • 30
  • 62
  • 1
    Why do you think the listener has been called (to set `h`) before the program reaches `return h`? I don't see the logic in your code here. – Tom Jul 08 '17 at 21:10
  • Possible duplicate of [Why lambda forces me to use single element array instead of final object?](https://stackoverflow.com/questions/28961578/why-lambda-forces-me-to-use-single-element-array-instead-of-final-object) – DaveNOTDavid Jul 08 '17 at 21:56

2 Answers2

4

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.

manicka
  • 204
  • 2
  • 8
1

The variable must be assigned as static in class MainActivity.

static int h;
Utkarsh Gupta
  • 111
  • 1
  • 2
  • 8