共享股票:写东西并保存,一切都消失了

  • 本文关键字:保存 消失了 共享 java android
  • 更新时间 :
  • 英文 :


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

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

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

代码:init方法()

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);

最新更新