Search code examples
androidpushy

How to get better understanding of error in order to fix


I'm receiving the following error message in LogCat:

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

I'm aware of what a NullPointerException is but not 100% on how to fix this with regards to passing the correct context. The error only happens when the app is runnning in the background (multitasking) A little guidance would be much appreciated. please Logcat and offending code below. THanks

Logcat:

Process: com.app.app, PID: 17519
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
    at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:537)
    at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:526)
    at com.app.app.DatabaseHandling.UpdateData.<init>(UpdateData.java:70)
    at com.app.app.PushService.PushReceiver$1.run(PushReceiver.java:94)
    at java.lang.Thread.run(Thread.java:764)

PushReceiver

UpdateData updateData = new UpdateData(MainActivity.mainActivity);

UpdateData:

 private final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.mainActivity);

Solution

  • I assume the problem is, that you try to initialise the SharedPreferences sp at the location, where you define it. You should define it first like:

    private SharedPreferences sp;
    

    After that, set this global variable sp in a function like "onReceive(Context context)":

    sp = PreferenceManager.getDefaultSharedPreferences(context);
    

    Or like already mentioned in the Activity itself in the function "onCreate(...)":

    sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
    

    The problem might be, that you try to initialize a variable with a context (like activity), that is not available at this point, but in a later step of the lifecycle.

    And avoid to hand over a context supplied by a static variable from another class.