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

Android开发:修改代码实现通过Shared Preferences存储选中项的ArrayList

How to Save and Restore Selected Items with SharedPreferences in onPause()/onResume()

Hey there! Since you're new to Android development, let's walk through how to save your selectedList in onPause() and restore it in onResume() using SharedPreferences. The key thing to note is that SharedPreferences can't store object lists directly, so we'll need to serialize the list into a storable format (like a JSON string) first.

Step 1: Prepare Your Image Item Class

First, make sure your ImageItem class (the type in imageList and selectedList) implements Serializable (or Parcelable) so it can be serialized. Here's an example:

public class ImageItem implements Serializable {
    private boolean isSelected;
    private String imageId; // Use a unique identifier like image path or ID
    // Add other fields you need (e.g., imageUrl, etc.)

    // Getters and Setters
    public boolean isSelected() {
        return isSelected;
    }

    public void setSelected(boolean selected) {
        isSelected = selected;
    }

    public String getImageId() {
        return imageId;
    }

    public void setImageId(String imageId) {
        this.imageId = imageId;
    }

    // Constructor
    public ImageItem(String imageId) {
        this.imageId = imageId;
        this.isSelected = false;
    }
}

Step 2: Initialize SharedPreferences

In your Activity/Fragment, initialize SharedPreferences (do this in onCreate() or onViewCreated()):

private SharedPreferences sharedPreferences;
private static final String PREF_NAME = "ImageSelectionPrefs";
private static final String KEY_SELECTED_LIST = "selected_list";

// In onCreate() (for Activity) or onViewCreated() (for Fragment)
sharedPreferences = getContext().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);

Step 3: Save selectedList in onPause()

We'll use Gson (a popular JSON library) to convert the list to a JSON string. First, add the Gson dependency to your app-level build.gradle file:

dependencies {
    // Other dependencies
    implementation 'com.google.code.gson:gson:2.10.1'
}

Then implement onPause():

@Override
public void onPause() {
    super.onPause();
    // Serialize selectedList to JSON
    Gson gson = new Gson();
    String selectedListJson = gson.toJson(selectedList);
    // Save to SharedPreferences
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(KEY_SELECTED_LIST, selectedListJson);
    editor.apply(); // Use apply() for async save, commit() for sync
}

Step 4: Restore selectedList in onResume()

Now read the JSON string back and convert it back to a list, then update your imageList and adapter to reflect the selected state:

@Override
public void onResume() {
    super.onResume();
    // Retrieve the saved JSON string
    String selectedListJson = sharedPreferences.getString(KEY_SELECTED_LIST, null);
    
    if (selectedListJson != null) {
        Gson gson = new Gson();
        // Use TypeToken to get the type of List<ImageItem>
        Type listType = new TypeToken<List<ImageItem>>() {}.getType();
        selectedList = gson.fromJson(selectedListJson, listType);
        
        // Sync the selected state with your imageList
        // (We use imageId to match items since deserialized objects are new instances)
        for (ImageItem selectedItem : selectedList) {
            for (ImageItem item : imageList) {
                if (item.getImageId().equals(selectedItem.getImageId())) {
                    item.setSelected(true);
                    break;
                }
            }
        }
        
        // Update the RecyclerView adapter
        if (imageAdapter != null) {
            imageAdapter.notifyDataSetChanged();
        }
    } else {
        // If no saved data, initialize selectedList as empty
        selectedList = new ArrayList<>();
    }
}

Alternative: No Third-Party Libraries (Using Serializable)

If you don't want to use Gson, you can serialize the list directly using ObjectOutputStream and store it as a Base64 string:

Save in onPause():

@Override
public void onPause() {
    super.onPause();
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(selectedList);
        oos.flush();
        String encodedList = Base64.encodeToString(bos.toByteArray(), Base64.DEFAULT);
        sharedPreferences.edit().putString(KEY_SELECTED_LIST, encodedList).apply();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Restore in onResume():

@Override
public void onResume() {
    super.onResume();
    try {
        String encodedList = sharedPreferences.getString(KEY_SELECTED_LIST, null);
        if (encodedList != null) {
            ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decode(encodedList, Base64.DEFAULT));
            ObjectInputStream ois = new ObjectInputStream(bis);
            selectedList = (List<ImageItem>) ois.readObject();
            
            // Sync imageList state and update adapter (same as before)
            for (ImageItem selectedItem : selectedList) {
                for (ImageItem item : imageList) {
                    if (item.getImageId().equals(selectedItem.getImageId())) {
                        item.setSelected(true);
                        break;
                    }
                }
            }
            
            if (imageAdapter != null) {
                imageAdapter.notifyDataSetChanged();
            }
        } else {
            selectedList = new ArrayList<>();
        }
    } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
        selectedList = new ArrayList<>();
    }
}

Important Notes

  • Unique Identifier: Always use a unique field (like imageId or image path) to match restored items with your imageList—don't rely on object equality, since deserialized objects are new instances.
  • Initialize Lists: Make sure imageList is initialized before onResume() runs (e.g., load it in onCreate()).
  • Null Safety: Add checks for imageAdapter and imageList to avoid NullPointerException.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 06:49:29