我有一个Android应用程序,当用户单击按钮时,该应用程序会保存一些数据,这些数据会序列化为JSON,然后通过putString保存到SharedPreferences中。
这些数据可通过Json de-serialization从另一个活动中检索。日志告诉我serialization正常运行,但是当我调用返回反序列化Json对象的方法时,得到了NullPointerException
我的对象(HistoryItem)具有2个属性:日期和心情。(可能会感到悲伤,快乐等的枚举)带有相应的获取器和设置器

我将Log.e放在Serializationde-serialization之前和之后,甚至在我创建异常的方法之前的第二个活动中,它们告诉我一切都很好,我肯定不在意正确的地方...

   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);
    }


然后方法来获取我的HistoryItem对象

 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;
}


例外情况:

   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....


我在这里叫displayMood(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()应该返回心情。
saveMood2()在MainActivity的OnLickListener处调用。

编辑:完整的错误堆栈:

 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) 

最佳答案

看着你的错误


  原因:java.lang.NullPointerException:尝试调用
  虚拟方法'com.matt.android.moodtracker_v2.models.MoodEnum
  com.matt.android.moodtracker_v2.models.HistoryItem.getMood()'
  空对象引用


看起来问题在于您在.getMood()对象上调用null。这意味着您的todayHistoryItem为空。

您可能应该将代码编辑为:

//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....


另一点

我看不到代码中将serialized object保存到mPreferences对象中的任何地方。

也许你忘了吗?

让我知道它是否可以解决您的问题!

09-25 21:06