Shlx Shlx - 1 year ago 88
Android Question

NullPointerException on SharedPreferences (Seems to be the context)

I'm just getting started with Android Studio, currently trying to make a simple app that lets you take notes and save them, maybe some 'to do list' features. I'm trying to store them in SharedPreferences using Json / Gson. Followed some online tutorials but can't seem to get it to work. Similar questions on here didn't help either. This is my code so far:

public class MainActivity extends AppCompatActivity {

public void onCreate(Bundle savedInstanceState) {

NoteHandler noteHandler = new NoteHandler();
noteHandler.newNote("test", 1);


public class Note {

public enum State { TODO, DONE };

private String content;
private State state;
private Date date;
private int id;
private Note parent;

public Note(String content, State state, Date date, Note parent, int id) {
this.content = content;
this.state = state; = date;
this.parent = parent; = id;

/* Getters and setters */


public class NoteHandler {

NotePrefs notePrefs = new NotePrefs(ContextGetter.getAppContext());

void newNote(String content, int id) {
newNote(content, null, id);

void newNote(String content, Note parent, int id) {
Note newNote = new Note(content, Note.State.TODO, new Date(), parent, id);

Note getNote(int id) {
return notePrefs.loadNote(id);

public class NotePrefs {
private final String PREFS_NAME = "notes.NotePrefs";
private static SharedPreferences settings;
private static SharedPreferences.Editor editor;
private static Gson gson = new Gson();

public NotePrefs(Context ctx) {
if(settings == null) {
settings = ctx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);

editor = settings.edit();

public static void saveNote(Note note) {
editor.putString("" + note.getId(), gson.toJson(note));

public static Note loadNote(int id) {
String noteJson = settings.getString("" + id, "");
return gson.fromJson(noteJson, Note.class);

public static List<Note> loadAllNotes() {
return null;

public class ContextGetter extends Application {

private static Context context;

public void onCreate(){
context = getApplicationContext();

public static Context getAppContext() {
return context;

The exception:

java.lang.RuntimeException: Unable to start activity ComponentInfo{notes/notes.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference

Still can't seem to wrap my head around the context stuff. Any help is appreciated!

Also, what's a good way to implement loadAllNotes()?


Answer Source

You should add name=".ContextGetter" to manifest in <application> tag.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download