androidandroid-sharedpreferences

How to getSharedPreferences in Application?


I tried to call getSharedPreferences in Application...

public class App extends Application{
    public App() {
        SharedPreferences prefs = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
    }
}

...but I got a NullPointerException:

java.lang.NullPointerException: Attempt to invoke virtual method
  'android.content.SharedPreferences
  android.content.Context.getSharedPreferences(java.lang.String, int)' 
  on a null object reference

I also tried this and got same exception:

Context con = getApplicationContext();

How can I call getSharedPreferences?


Solution

  • Override onCreate(), in your app,

    @Override
    public void onCreate() {
        super.onCreate();
    

    and do it there. Don't forget to declare your Application subclass in the AndroidManifest as well. E.g.

      <application
            android:name="App"