gpt4 book ai didi

java - sharedPreference : write something and save it, 一切都消失了

转载 作者:行者123 更新时间:2023-11-30 03:56:43 25 4
gpt4 key购买 nike

我正在开发这个应用程序,其中有一个 EditText 字段,您可以在其中编写内容,然后将其保存并添加到列表 (TextView)。我以这种方式保存 EditText 的内容:

saved += "*" + editTextFelt.getText().toString() + ". \n";

saved 是一个 String。一切正常,我什至可以重新加载应用程序,它仍然显示在 TextView 中,但是如果我尝试写一些东西并保存它,那里的所有内容现在都消失了。为什么?

代码:初始化方法()

sp = getSharedPreferences(fileName, 0);
betaView = (TextView)findViewById(R.id.betaTextView);

我有一个发送文本的按钮,就像这样:

public void onClick(View v) {
switch(v.getId()){
case R.id.btnSend:
saved += "*" + editTextFelt.getText().toString() + ". \n";
SharedPreferences.Editor editor = sp.edit();
editor.putString("SAVED", saved);
editor.commit();

betaView.setText(sp.getString("SAVED", "Empty"));

最佳答案

你是如何保存它的?因为当您针对变量保存文本时,它会替换前一个。

因此您需要获取前一个,然后附加新的,然后再次将其保存到 SharedPreferences,如下所示:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String saved = sp.getString("YourVariable", "");
saved += "*" + editTextFelt.getText().toString() + ". \n"; //appending previous
//Editor to edit
SharedPreferences.Editor editor = preferences.edit();
editor.putString("YourVariable",saved);
editor.commit(); //don't forget to commit.

现在将此附加文本设置到您的 TextView 中,如下所示:

betaView.setText(saved);

关于java - sharedPreference : write something and save it, 一切都消失了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13220560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com