Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I "Transform myVariable to final one element array"?

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

}

like image 952
jazz chakraborty Avatar asked Jul 08 '17 21:07

jazz chakraborty


2 Answers

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.

like image 165
manicka Avatar answered Oct 28 '22 00:10

manicka


The variable must be assigned as static in class MainActivity.

static int h;
like image 1
Utkarsh Gupta Avatar answered Oct 27 '22 23:10

Utkarsh Gupta