My public var is invisible to my cousin

Inspired by Magenta's book Learning Android, I created an application class for my application:

public class KITAppClass extends Application implements OnSharedPreferenceChangeListener { private static final String TAG = KITAppClass.class.getSimpleName(); //private SharedPreferences KITPrefs; public SharedPreferences KITPrefs; . . . 

However, now I get "KITPrefs cannot be resolved" on this line in another class file that references SharedPreferences:

 allContacts.setSelected(KITPrefs.getBoolean("allContacts", false)); 

I am wondering: if shared privileges are used, why were they marked “private” in the sample code? Why is this not yet visible, even after I designated it as "publicly available"?

If I add "import KITAppClass;" I get literally "paddled" with "Import KITAppClass cannot be resolved"

+4
source share
2 answers

Try ...

 public class KITAppClass extends Application implements OnSharedPreferenceChangeListener { ... protected static SharedPreferences kitPrefs; ... } 

Then open kitPrefs from the Activity (or other) classes in the application (if they occupy the same namespace), using, for example ...

 KITAppClass.kitPrefs.getBoolean(...); 

Saying that storing an instance of SharedPreferences at the Application class level is optional, as you can get SharedPreferences from any Activity at any time. See Using General Settings .

Also, think twice about actually expanding the Application if you really don't need to, and if you really don't know what you are doing with it. In most cases (for simple applications, at least) this is optional. Just because they show you how to do this in a book does not mean that you need to do this.

+1
source

To access KITPrefs from another Activity class, you can use getApplicationContext() and apply the Application class.

 ((KITAppClass)getApplicationContext()).KITPrefs.getBoolean("allContacts", false); 
+1
source

Source: https://habr.com/ru/post/1387498/


All Articles