如何用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
MyClasshas public fields or proper getter/setter methods so Gson can serialize/deserialize it correctly. If you have private fields, you can use@SerializedNameannotations 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
SerializableonMyClassand useObjectOutputStreamto convert the array to a byte array, but that’s more verbose and error-prone compared to Gson.
内容的提问来源于stack exchange,提问作者Hubizonek
相关产品推荐
相关产品推荐

