You need to enable JavaScript to run this app. 如何使用SharedPreference存储EditText数据并在另一Activity的ListView中展示
优惠活动
大模型
产品
解决方案
定价
更多

如何使用SharedPreference存储EditText数据并在另一Activity的ListView中展示

问题根源

你的代码存在两个核心问题:

  1. EditorActivity返回时主动启动了新的MainActivity实例,而非复用返回栈中已有的实例,每次新页面都会初始化空的笔记列表,仅能读取到SharedPreferences中存储的最新一条数据,历史数据全部丢失。
  2. SharedPreferences每次都覆盖写入同一个key的标题和内容,只能保留最新一条笔记,没有做全量历史数据的持久化。

修复方案

1. 修改EditorActivity回退逻辑

删掉主动启动MainActivity的代码,将输入内容通过回传Intent返回给上层页面后直接关闭当前页面即可:

@Override
public void onBackPressed() {
    String title = edit_title.getText().toString().trim();
    String content = edit_note.getText().toString().trim();
    // 过滤空内容的笔记
    if (!title.isEmpty() || !content.isEmpty()) {
        Intent resultIntent = new Intent();
        resultIntent.putExtra("note_title", title);
        resultIntent.putExtra("note_content", content);
        setResult(RESULT_OK, resultIntent);
    }
    super.onBackPressed();
}

2. 修改MainActivity,用带返回值的方式启动EditorActivity

使用Activity Result API接收返回的笔记内容,更新列表:
首先在MainActivity中注册返回结果监听:

private ActivityResultLauncher<Intent> editorLauncher = registerForActivityResult(
    new ActivityResultContracts.StartActivityForResult(),
    result -> {
        if (result.getResultCode() == RESULT_OK && result.getData() != null) {
            String title = result.getData().getStringExtra("note_title");
            String content = result.getData().getStringExtra("note_content");
            // 新增笔记到当前列表
            notes.add(new NoteItem(title, content));
            adapter.notifyDataSetChanged();
            // 持久化存储全量笔记
            saveNotesToSp();
        }
    }
);

修改悬浮按钮的点击逻辑,用上述注册的launcher启动EditorActivity:

addNoteFab.setOnClickListener(view -> {
    Intent intent = new Intent(MainActivity.this, EditorActivity.class);
    editorLauncher.launch(intent);
});

3. 实现全量笔记持久化,重启应用不丢失数据

我们用Gson将笔记列表序列化为字符串存储到SharedPreferences,首先在app模块build.gradle中引入依赖:

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

在MainActivity中新增读写笔记的工具方法:

// 存储所有笔记到SharedPreferences
private void saveNotesToSp() {
    SharedPreferences sp = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();
    editor.putString("all_notes", new Gson().toJson(notes));
    editor.apply();
}

// 启动时读取所有历史笔记
private void loadNotesFromSp() {
    SharedPreferences sp = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
    String notesJson = sp.getString("all_notes", null);
    if (notesJson != null) {
        Type listType = new TypeToken<ArrayList<NoteItem>>() {}.getType();
        ArrayList<NoteItem> savedNotes = new Gson().fromJson(notesJson, listType);
        if (savedNotes != null) {
            notes.addAll(savedNotes);
        }
    }
}

最后调整onCreate逻辑,删掉原有的单条笔记读取代码,替换为全量读取:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    addNoteFab = findViewById(R.id.add_note);
    notes = new ArrayList<>();
    adapter = new NoteAdapter(this, notes);
    ListView listView = findViewById(R.id.list_view);
    listView.setAdapter(adapter);

    // 先加载历史笔记
    loadNotesFromSp();
    adapter.notifyDataSetChanged();

    addNoteFab.setOnClickListener(view -> {
        Intent intent = new Intent(MainActivity.this, EditorActivity.class);
        editorLauncher.launch(intent);
    });
}

可选优化

你可以将note_list_item.xml中两个TextView的初始visibility属性从invisible改为gone,避免空内容时占用多余的空白位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 05:15:05