Android/Java中如何在Shared Preferences存储并读取Integer ArrayList
Hey there! I totally get where you’re coming from—converting an Integer list to a String set and back is clunky, error-prone, and just plain annoying. Since SharedPreferences doesn’t natively support Integer collections, the cleanest workaround is to serialize your Integer list into a JSON string, store that string, then deserialize it when you need to retrieve the list. This keeps your code clean and avoids those messy conversion bugs.
Solution 1: Using Gson (Simplest Approach)
Gson makes serialization and deserialization a breeze. Here’s how to adapt your code:
Step 1: Add Gson Dependency
If you’re using Gradle, add this to your app-level build.gradle (or build.gradle.kts):
dependencies { implementation 'com.google.code.gson:gson:2.10.1' // Use the latest available version }
Step 2: Update Your Preference Manager Methods
Replace your existing String set methods with these, which directly handle List<Integer>:
import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; // ... public List<Integer> getAppointmentStatusPosList() { String json = sharedPreferences.getString(APPOINTMENT_STATUS_ID_LIST, null); if (json == null) { return new ArrayList<>(); // Return empty list or null based on your needs } return new Gson().fromJson(json, new TypeToken<List<Integer>>(){}.getType()); } public void setAppointmentStatusPosList(List<Integer> indices) { String json = new Gson().toJson(indices); editor.putString(APPOINTMENT_STATUS_ID_LIST, json); editor.apply(); }
Step 3: Simplify Your selectedIndices Method
Now you can pass the Integer list directly without any set conversions:
@Override public void selectedIndices(List<Integer> indices) { preferenceManager.setAppointmentStatusPosList(indices); }
Solution 2: Using Built-in JSON Library (No External Dependencies)
If you don’t want to add an external library, you can use Android’s built-in org.json package:
Updated Preference Manager Methods
import org.json.JSONArray; import org.json.JSONException; // ... public List<Integer> getAppointmentStatusPosList() { String json = sharedPreferences.getString(APPOINTMENT_STATUS_ID_LIST, null); List<Integer> indices = new ArrayList<>(); if (json != null) { try { JSONArray jsonArray = new JSONArray(json); for (int i = 0; i < jsonArray.length(); i++) { indices.add(jsonArray.getInt(i)); } } catch (JSONException e) { e.printStackTrace(); // Handle parsing errors as needed (e.g., return empty list) } } return indices; } public void setAppointmentStatusPosList(List<Integer> indices) { JSONArray jsonArray = new JSONArray(); for (Integer index : indices) { jsonArray.put(index); } editor.putString(APPOINTMENT_STATUS_ID_LIST, jsonArray.toString()); editor.apply(); }
selectedIndices Method Remains the Same
Just pass the List<Integer> directly, no extra steps required.
Why This Works Better
- Less Error-Prone: No manual conversion of each Integer to String (and back), which eliminates risks like
NumberFormatExceptionif a string can’t be parsed back to an Integer. - Cleaner Code: Your methods directly handle the type you care about (
List<Integer>), so you don’t have to juggle sets or string conversions elsewhere in your app.
Both approaches strictly use SharedPreferences—they just store the list as a serialized string instead of a String set.
内容的提问来源于stack exchange,提问作者user13406877

