需要持久化保存多個名字字符串,支持增刪改查,適用於「最近搜索」、「標籤歷史」等場景。
Android API Level 11+ (Honeycomb) 引入 Set<String> 支持,不再需要手動拼接分隔符。
public void saveNames(Context context, Set<String> names) {
SharedPreferences sp = context.getSharedPreferences("name_prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putStringSet("saved_names", names); // 直接存 Set
editor.apply(); // 異步提交,不阻塞主線程
}
public Set<String> loadNames(Context context) {
SharedPreferences sp = context.getSharedPreferences("name_prefs", Context.MODE_PRIVATE);
// 返回不可修改的 Set,需拷貝後操作
return new HashSet<>(sp.getStringSet("saved_names", new HashSet<>()));
}
public void addName(Context context, String name) {
Set<String> names = loadNames(context);
names.add(name);
saveNames(context, names);
}
public void removeName(Context context, String name) {
Set<String> names = loadNames(context);
names.remove(name);
saveNames(context, names);
}
| 陷阱 | 說明 | 正確做法 |
|---|---|---|
| 直接修改 getStringSet 返回的 Set | 返回的是不可修改的集合,調用 add/remove 會拋 UnsupportedOperationException | 先拷貝:new HashSet<>(sp.getStringSet(...)) |
| 使用 MODE_APPEND | 該模式用於文件追加寫入,不適用於 SharedPreferences | 使用 MODE_PRIVATE (默認) |
| 忘記 apply()/commit() | Editor 操作必須提交才生效 | 優先用 apply() 異步寫入 |
| 存儲 null 值 | putStringSet 不接受 null | 傳空集合 new HashSet<>() |
public class NamePrefs {
private static final String PREFS_NAME = "name_prefs";
private static final String KEY_NAMES = "saved_names";
private final SharedPreferences sp;
public NamePrefs(Context context) {
sp = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
}
public Set<String> getAll() {
return new HashSet<>(sp.getStringSet(KEY_NAMES, Collections.emptySet()));
}
public void add(String name) {
Set<String> set = getAll();
set.add(name);
sp.edit().putStringSet(KEY_NAMES, set).apply();
}
public void remove(String name) {
Set<String> set = getAll();
set.remove(name);
sp.edit().putStringSet(KEY_NAMES, set).apply();
}
public void clear() {
sp.edit().remove(KEY_NAMES).apply();
}
}
掌握 getStringSet/putStringSet,輕鬆實現字符串集合持久化,告別手動拼接分隔符的繁瑣與易錯。