Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullPointerException getDefaultSharedPreferences()

I keep getting NullPointerException on this line:

SharedPreferences myPreference = PreferenceManager.getDefaultSharedPreferences(this);

I ran some things through and I believe that I have the wrong context as it is in a subpackage of the main package so I don't think it can reference the XML preference files. I have used this in class's that are in the main package with no trouble but for some reason this causes an exception.

Full code:

package schoolBook.Icestone.Expandable;

import schoolBook.Icestone.Days;
import schoolBook.Icestone.Main;
import schoolBook.Icestone.SetPreference;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

public class Lesson1 extends Lessons {

    public Lesson1(String name) {
        super(name);
        // setGroup(" " + Days.getLessonarray(0) + " ");
        String key = "W" + Main.getWeek() + "_" + SetPreference.xmlday + "_L"
                + SetPreference.xmllesson + "_Lesson";
        System.out.println(key);
        try {
            SharedPreferences myPreference = PreferenceManager
                    .getDefaultSharedPreferences(this);
            String group = myPreference.getString(key, "def");
            setGroup(" " + group + " ");
        } catch (NullPointerException ex) {
            ex.printStackTrace();
            setGroup(" " + Days.getLessonarray(0) + " ");
        }
    }
}

Lessons class extends Activity so think that may be the source of my problem but im not sure.

File structure:

Icestone

  • Main.class and some other classes that use shared preference and it works fine
    • Lessons package (Lesson1 & Lesson are in this package)
  • XML folder with the preferences in it

if anyone could help shed some light on this problem it would be much appreciated

like image 435
R3MIX Avatar asked Oct 11 '22 11:10

R3MIX


1 Answers

You can't do this inside the constructor.

If it extends Activity Class it should't has a constructor, you need to handle that inside the oncreate method.

like image 117
Panthro Avatar answered Oct 27 '22 10:10

Panthro