每当试图保存SharedPreferences时,应用程序都会崩溃

时间:2018-04-26 00:29:51

标签: android json android-sharedpreferences gson

我有一个应用程序可以正常工作,直到我按下两个按钮之一,这两个按钮都保存了我当前的自定义类,它将四个ArrayList<String>存储为JSON文件。

以下是我的JSON文件加载和保存到SharedPreferences的代码:

@Override
protected void onResume() {
    super.onResume();
    SharedPreferences myPrefs = getPreferences(MODE_PRIVATE);
    Gson gson = new Gson();
    String json = myPrefs.getString("MyObject", "");
    StudentArray obj = gson.fromJson(json, StudentArray.class);

    studentsFirstNames = obj.studentFirstName;
    studentsLastNames = obj.studentLastName;
    studentsCourses = obj.studentCourse;
    studentsYearsOfStudy = obj.studentYearOfStudy;
}

@Override
protected void onPause() {
    super.onPause();
    SharedPreferences myPrefs = getPreferences(MODE_PRIVATE);
    Editor prefsEditor = myPrefs.edit();
    Gson gson = new Gson();
    StudentArray example = new StudentArray(studentsFirstNames, studentsLastNames, studentsCourses, studentsYearsOfStudy);
    String json = gson.toJson(example);
    prefsEditor.putString("MyObject", json);
    prefsEditor.commit();
}       

Logcat崩溃日志

04-26 21:58:38.985 14971-14971/com.adam_smedley.moduleenrollment E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.adam_smedley.moduleenrollment, PID: 14971
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=0, data=null} to activity {com.adam_smedley.moduleenrollment/com.adam_smedley.moduleenrollment.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
    at android.app.ActivityThread.deliverResults(ActivityThread.java:4089)
    at android.app.ActivityThread.handleSendResult(ActivityThread.java:4132)
    at android.app.ActivityThread.-wrap20(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1533)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6119)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
 Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
    at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:344)
    at android.widget.ListView.setAdapter(ListView.java:493)
    at com.adam_smedley.moduleenrollment.MainActivity.onActivityResult(MainActivity.java:89)
    at android.app.Activity.dispatchActivityResult(Activity.java:6932)
    at android.app.ActivityThread.deliverResults(ActivityThread.java:4085)
    at android.app.ActivityThread.handleSendResult(ActivityThread.java:4132) 
    at android.app.ActivityThread.-wrap20(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1533) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:154) 
    at android.app.ActivityThread.main(ActivityThread.java:6119) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 

好吧,所以似乎我的ArrayList是空对象引用,因为我无法向它们添加另一个字符串或得到.size()

任何人都可以看到下面声明的任何问题

static ArrayList<String> studentsFirstNames;
studentsFirstNames = new ArrayList<String>();
studentsFirstNames.add("John");

并在我的AddNewStudent活动中调用

    MainActivity.studentsFirstNames.add(firstName);   

应访问Main Activity中的静态ArrayList studentsFirstNames,并将单个字符串firstName添加到ArrayList。

onActivityResult代码

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    ListAdapter enrollmentAdapter = new CustomAdapter(this, studentsFirstNames, studentsLastNames, studentsCourses, studentsYearsOfStudy);
    ListView studentsListView = (ListView) findViewById(R.id.StudentsListView);
    studentsListView.setAdapter(enrollmentAdapter);
}

它肯定是由上面的onResume()和onPause()代码引起的,因为我已经评论过它并且我的应用程序有效,但它没有保存任何东西所以我没有任何数据持久性。

1 个答案:

答案 0 :(得分:0)

您的StudentArray方法可能会导致onResume无效。因此,当您使用gson获取对象时,需要检查null或异常。像这样:

@Override
protected void onResume() {
  super.onResume();
  SharedPreferences myPrefs = getPreferences(MODE_PRIVATE);
  Gson gson = new Gson();
  String json = myPrefs.getString("MyObject", "");
  try {
    StudentArray obj = gson.fromJson(json, StudentArray.class);
    if (obj != null) {
      studentsFirstNames = obj.studentFirstName;
      studentsLastNames = obj.studentLastName;
      studentsCourses = obj.studentCourse;
      studentsYearsOfStudy = obj.studentYearOfStudy;
    } else {
      // obj is null. You need to do something here.
    }
  } catch (IllegalStateException | JsonSyntaxException exception) {
    // there is something wrong when parsing the json
    // do something
  }
}