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

Android/Java中如何在Shared Preferences存储并读取Integer ArrayList

Storing Integer ArrayList in SharedPreferences Without String Set Conversion

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 NumberFormatException if 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 08:17:28