Why should I “Transform myVariable to final one element array”?

◇◆丶佛笑我妖孽 提交于 2020-12-30 07:44:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!