Accessing SharedPreferences through static methods

Cristian’s answer is good, but if you want to be able to access your shared preferences from everywhere the right way would be:

  1. Create a subclass of Application, e.g. public class MyApp extends Application {
  2. Set the android:name attribute of your <application> tag in the AndroidManifest.xml to point to your new class, e.g. android:name="MyApp" (so the class is recognized by Android)
  3. In the onCreate() method of your app instance, save your context (e.g. this) to a static field named app and create a static method that returns this field, e.g. getApp(). You then can use this method later to get a context of your application and therefore get your shared preferences. 🙂

Leave a Comment