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

如何用SharedPreferences保存Object[]?求完整SaveIt与LoadIt代码

Got it, let's sort this out for you! SharedPreferences doesn't support storing object arrays directly out of the box, so we'll use JSON serialization (I’m using Gson here because it’s the most straightforward approach for Android) to convert your MyClass[] into a string that can be saved, then parse it back when loading.

First, make sure you have Gson added to your project (if you haven’t already):

// For Gradle (Module level)
dependencies {
    implementation 'com.google.code.gson:gson:2.10.1'
}

SaveIt() Method

This method will convert your array to a JSON string and save it to SharedPreferences:

private void SaveIt(Context context, MyClass[] array) {
    // Get SharedPreferences instance
    SharedPreferences prefs = context.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    
    // Convert array to JSON string using Gson
    Gson gson = new Gson();
    String json = gson.toJson(array);
    
    // Save the JSON string
    editor.putString("my_class_array", json);
    editor.apply(); // Use apply() for async save, commit() for sync if needed
}

LoadIt() Method

This method will retrieve the JSON string and convert it back to your MyClass[]:

private MyClass[] LoadIt(Context context) {
    SharedPreferences prefs = context.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
    String json = prefs.getString("my_class_array", null);
    
    if (json == null) {
        // Return empty array or null if no saved data exists
        return new MyClass[0];
    }
    
    // Convert JSON string back to MyClass[]
    Gson gson = new Gson();
    Type type = new TypeToken<MyClass[]>() {}.getType();
    
    try {
        return gson.fromJson(json, type);
    } catch (JsonSyntaxException e) {
        // Handle parsing errors (e.g., corrupted data)
        e.printStackTrace();
        return new MyClass[0];
    }
}

Quick Notes:

  • Make sure your MyClass has public fields or proper getter/setter methods so Gson can serialize/deserialize it correctly. If you have private fields, you can use @SerializedName annotations to map them to JSON keys if needed.
  • Replace "MyPrefs" with your preferred SharedPreferences name, and "my_class_array" with a unique key for your array.
  • If you don’t want to use Gson, you could implement Serializable on MyClass and use ObjectOutputStream to convert the array to a byte array, but that’s more verbose and error-prone compared to Gson.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:27:53