Greetings to all!
Tell me if you can access the commandMap variable in this situation:

public class MainSettingsActivity extends PreferenceActivity { //Та самая переменная private final Map<String,String> commandMap = new HashMap<String, String>(); private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object value) { //Необходимо получить доступ здесь } } } 

Tried: MainSettingsActivity.this.commandMap.put() but gives the error No enclosing instance of the type MainSettingsActivity is accessible in scope

  • one
    The problem is that in the class method you can not access one of the fields of the same class? - Stas0n

2 answers 2

A static variable is initialized when the class is loaded. You have sBindPreferenceSummaryToValueListener - a static class field, and commandMap is not, commandMap is initialized when an instance of the object of the MainSettingsActivity class is created , that is, when you will exist and live in sBindPreferenceSummaryToValueListener memory, the program may not even know that you can create commandMap .

There are two ways out:
1 - make commandMap static
2 - remove from sBindPreferenceSummaryToValueListener static

  • Thank you for chewing in detail. Explained simple and clear! - imholynx

Try adding the static keyword to the commandMap definition.

Perhaps the whole thing in the access modifier, try to declare commandMap as protected

  • Thanks, changing to static solved the problem. Now I can access both the MainSettingsActivity.this.commandMap variable and the MainSettingsActivity.commandMap variable . - imholynx
  • @imholynx: Uh ... would you first think you need one common commandMap for all instances of a class, or for each object its own? So easily change the semantics of the program, you know, very boldly. - VladD
  • I don't need one commandMap for all instances. I will not have them. It confuses me. Is there a suggestion? - imholynx
  • Hmm, who will not be? MainSettingsActivity your MainSettingsActivity class a singleton? - VladD
  • Yes, he will be alone. - imholynx