You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

App尝试保存SharedPreferences时崩溃问题求助

Hey there, let's figure out why your app crashes when those two save buttons are clicked! Based on what you described—saving a custom StudentArray class (with four ArrayList<String>) to SharedPreferences via Gson—and the code snippet you shared, here are the most likely issues and fixes:

Troubleshooting Your Crash Issue

1. Check Your StudentArray Class Structure

Gson needs specific rules to serialize/deserialize custom classes properly, and missing these often causes crashes:

  • Make sure your StudentArray has a no-argument constructor (Gson relies on this to create instances)
  • Ensure the four ArrayList<String> fields are either public, or have valid getter/setter methods (Gson needs access to read/write these fields)
  • Don't mark the ArrayList fields with transient unless you intentionally want Gson to skip them

Here's a compliant example of the class:

public class StudentArray {
    public ArrayList<String> studentList1;
    public ArrayList<String> studentList2;
    public ArrayList<String> studentList3;
    public ArrayList<String> studentList4;

    // Required: no-arg constructor
    public StudentArray() {}

    // Optional: parameterized constructor for easier initialization
    public StudentArray(ArrayList<String> list1, ArrayList<String> list2, ArrayList<String> list3, ArrayList<String> list4) {
        this.studentList1 = list1;
        this.studentList2 = list2;
        this.studentList3 = list3;
        this.studentList4 = list4;
    }
}

2. Fix the Save Logic in Your Button Click Listeners

Most button-click crashes here come from incomplete SharedPreferences operations. Double-check your save code matches this pattern:

private void saveStudentArrayToPrefs() {
    // First, make sure your StudentArray instance and its lists are properly initialized
    StudentArray studentData = new StudentArray();
    studentData.studentList1 = new ArrayList<>(); // Initialize to avoid nulls
    // ... add data to your lists as needed

    SharedPreferences myPrefs = getPreferences(MODE_PRIVATE);
    SharedPreferences.Editor editor = myPrefs.edit(); // Don't forget to get the editor!
    Gson gson = new Gson();
    String json = gson.toJson(studentData);
    
    editor.putString("MyObject", json);
    editor.apply(); // Always commit/apply to save changes!
}

Common mistakes here:

  • Forgetting to retrieve the SharedPreferences.Editor before trying to save
  • Skipping apply()/commit() after calling putString()
  • Trying to serialize a StudentArray instance with null ArrayList fields (Gson can handle nulls, but it's risky for later operations)

3. Fix the onResume Deserialization Logic

Your current onResume code has a critical flaw: when there's no saved data, you pass an empty string to gson.fromJson(), which throws a JsonSyntaxException and crashes the app. Here's the fixed version:

@Override 
protected void onResume() { 
    super.onResume(); 
    SharedPreferences myPrefs = getPreferences(MODE_PRIVATE); 
    Gson gson = new Gson(); 
    String json = myPrefs.getString("MyObject", null); // Use null as default instead of empty string
    StudentArray obj;

    if (json == null || json.isEmpty()) {
        // Initialize a fresh StudentArray with empty lists if no saved data exists
        obj = new StudentArray();
        obj.studentList1 = new ArrayList<>();
        obj.studentList2 = new ArrayList<>();
        obj.studentList3 = new ArrayList<>();
        obj.studentList4 = new ArrayList<>();
    } else {
        obj = gson.fromJson(json, StudentArray.class);
        // Add a safety check: if any list deserialized to null, reinitialize it
        if (obj.studentList1 == null) obj.studentList1 = new ArrayList<>();
        if (obj.studentList2 == null) obj.studentList2 = new ArrayList<>();
        if (obj.studentList3 == null) obj.studentList3 = new ArrayList<>();
        if (obj.studentList4 == null) obj.studentList4 = new ArrayList<>();
    }
    // Proceed with using your obj instance...
}

4. Use Logcat to Pinpoint the Exact Crash

For the most accurate diagnosis, check the crash stack trace in Android Studio's Logcat. Look for the Caused by: line—it will tell you exactly what's wrong:

  • JsonSyntaxException: Problem with deserialization (empty string, invalid class structure)
  • NullPointerException: You're calling methods on a null ArrayList
  • ClassCastException: Incorrect type casting when using the deserialized object

内容的提问来源于stack exchange,提问作者Adam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:34:37