如何在SharedPreferences中以列表形式保存、展示数据并实现内容追加
实现方案
SharedPreferences本身不直接支持列表类型存储,你可以通过将列表序列化为JSON字符串的方式实现追加存储,具体操作如下:
核心思路
- 把多条笑话数据封装为JSON数组,每个笑话对应数组里的一个JSONObject,包含setup和punchline两个字段
- 每次保存新数据时,先读取SharedPreferences中已存储的JSON数组字符串,反序列化为JSONArray对象
- 把新的笑话数据追加到JSONArray末尾,再序列化为字符串重新存入SharedPreferences即可,不会覆盖原有数据
修改后的保存代码
public void saveButton(View v) throws JSONException { String newSetup = ((TextView) findViewById(R.id.randomJokeSetup)).getText().toString(); String newPunchline = ((TextView) findViewById(R.id.randomJoke)).getText().toString(); SharedPreferences datafile = getSharedPreferences("my_data_file", MODE_PRIVATE); SharedPreferences.Editor editor = datafile.edit(); // 1. 读取已存储的笑话列表,没有的话初始化空数组 String jokeListStr = datafile.getString("joke_list", "[]"); JSONArray jokeArray = new JSONArray(jokeListStr); // 2. 把新笑话封装为JSONObject加入数组 JSONObject newJoke = new JSONObject(); newJoke.put("setup", newSetup); newJoke.put("punchline", newPunchline); jokeArray.put(newJoke); // 3. 序列化后存入SharedPreferences editor.putString("joke_list", jokeArray.toString()); editor.apply(); // apply比commit更适合UI线程操作,不会阻塞 Snackbar.make(findViewById(R.id.save), "Joke saved!", Snackbar.LENGTH_SHORT).show(); }
修改后的加载代码
下面的示例默认加载最后一条保存的笑话,如果你需要加载全部笑话遍历jokeArray即可:
public void loadButton(View v) throws JSONException { SharedPreferences datafile = getSharedPreferences("my_data_file", MODE_PRIVATE); String jokeListStr = datafile.getString("joke_list", "[]"); JSONArray jokeArray = new JSONArray(jokeListStr); // 示例:加载最新的一条笑话,数组为空的话显示空内容 String setup = ""; String punchline = ""; if (jokeArray.length() > 0) { JSONObject latestJoke = jokeArray.getJSONObject(jokeArray.length() - 1); setup = latestJoke.optString("setup", ""); punchline = latestJoke.optString("punchline", ""); } ((TextView) findViewById(R.id.loadJokeSetup)).setText(setup); ((TextView) findViewById(R.id.loadJoke)).setText(punchline); }
注意事项
- 该方案仅适合存储小体量的列表数据,如果你的笑话数量超过100条,更推荐使用Room数据库等本地存储方案,读写效率更高
- 可以根据需求调整加载逻辑,比如实现加载所有历史笑话展示在列表控件中
内容的提问来源于stack exchange,提问作者First Last
相关产品推荐
相关产品推荐

