NullPointerExcetion after Json deserialisation

I have an Android App who save some data when user click on a button, those data is serialized to JSON then saved into SharedPreferences via putString. Those data are retrievable from another activity via Json de-serialization. Logs tell me that serialization is doing correctly but when i call my method who return de-serialized Json Object I’ve got a NullPointerException. My Object (HistoryItem) have 2 attributs : a Date and a Mood.(an enum who can be sad, happy, etc) with corresponding getters and setters

I’ve put Log.e at Serialization, de-serialization, before and after, even in my second activity just before the method who create exception, and they tell me that everything is doing well, i’m surely not looking at the right place…

   public void savemood2(Date date, HistoryItem historyItem) {
    Gson gson = new Gson();
    String jsonHistoryItem;
    // HistoryItem --> Json String
    if (historyItem.getComment() != null || historyItem.getComment() != PREF_KEY_EMPTY_COMMENT) {
        jsonHistoryItem = gson.toJson(historyItem, HistoryItem.class);
    }
    //If there's no comment, save PREF_KEY_EMPTY_COMMENT as comment
    else {
        historyItem.setComment(PREF_KEY_EMPTY_COMMENT);
        jsonHistoryItem = gson.toJson(historyItem, HistoryItem.class);
    }

then method to get my HistoryItem Object

 public HistoryItem getMood2(Date date) {
    Gson gson = new Gson();
    String json = mPreferences.getString(getMoodDate(date), null);
    historyItem = gson.fromJson(json, HistoryItem.class);
    Log.e("TAGOUTPUT", json);
    return historyItem;
}

Exception :

   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.matt.android.moodtracker_v2.models.MoodEnum com.matt.android.moodtracker_v2.models.HistoryItem.getMood()' on a null object reference
    at com.matt.android.moodtracker_v2.controllers.MoodHistoryActivity.displayMood(MoodHistoryActivity.java:116)
    at com.matt.android.moodtracker_v2.controllers.MoodHistoryActivity.onCreate(MoodHistoryActivity.java:96)

displayMood(java:116) :

  if (todayHistoryItem.getMood() == null) {
        relativeLayout.setBackgroundColor(0);
    }  else {
        // Set background color and fraction for each mood case
        switch (todayHistoryItem.getMood()) {
            case Sad:
                relativeLayout.setLayoutParams(new LinearLayout.LayoutParams(width / 5,
                        LinearLayout.LayoutParams.MATCH_PARENT, 1));
                relativeLayout.setBackgroundColor(getResources().getColor(R.color.faded_red));
                break;
            case Disappointed: etc....

I’m calling displayMood here (java :96):

  // Loop to display last 7 moods
    Calendar calendar = Calendar.getInstance();
    for (int i = 0; i < 7; i++) {
        calendar.add(Calendar.DAY_OF_WEEK, -1); //Subtract one day from calendar (yesterday)
        this.displayMood(calendar.getTime(), layouts[i]);
        this.displayComment(calendar.getTime(), buttons[i]);
    }

todayHistoryItem.getMood() is supposed to return a Mood. saveMood2() is called at OnLickListener of MainActivity.

EDIT: full error stack :

 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.matt.android.moodtracker_v2/com.matt.android.moodtracker_v2.controllers.MoodHistoryActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.matt.android.moodtracker_v2.models.MoodEnum com.matt.android.moodtracker_v2.models.HistoryItem.getMood()' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2721)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2782)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1521)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:163)
    at android.app.ActivityThread.main(ActivityThread.java:6228)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.matt.android.moodtracker_v2.models.MoodEnum com.matt.android.moodtracker_v2.models.HistoryItem.getMood()' on a null object reference
    at com.matt.android.moodtracker_v2.controllers.MoodHistoryActivity.displayMood(MoodHistoryActivity.java:116)
    at com.matt.android.moodtracker_v2.controllers.MoodHistoryActivity.onCreate(MoodHistoryActivity.java:96)
    at android.app.Activity.performCreate(Activity.java:6860)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2674)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2782) 
    at android.app.ActivityThread.-wrap12(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1521) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:163) 
    at android.app.ActivityThread.main(ActivityThread.java:6228) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794) 

Answer

Looking at your error

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘com.matt.android.moodtracker_v2.models.MoodEnum com.matt.android.moodtracker_v2.models.HistoryItem.getMood()’ on a null object reference

Looks like the problem is that you are calling .getMood() on a null object. This means that your todayHistoryItem is null.

You should probably edit your code to be like that:

//add todayHistoryItem == null check
if (todayHistoryItem == null || todayHistoryItem.getMood() == null) {
        relativeLayout.setBackgroundColor(0);
    }  else {
        // Set background color and fraction for each mood case
        switch (todayHistoryItem.getMood()) {
            case Sad:
                relativeLayout.setLayoutParams(new LinearLayout.LayoutParams(width / 5,
                        LinearLayout.LayoutParams.MATCH_PARENT, 1));
                relativeLayout.setBackgroundColor(getResources().getColor(R.color.faded_red));
                break;
        case Disappointed: etc....

Another point

I don’t see anywhere in your code where you are saving your serialized object into your mPreferences object.

Maybe you forgot it?

Let me know if it fixes your problem!

Leave a Reply

Your email address will not be published. Required fields are marked *