gpt4 book ai didi

java - 如何保存字符串?

转载 作者:行者123 更新时间:2023-12-02 03:36:25 25 4
gpt4 key购买 nike

我正在编写一个简单的应用程序,它有两个 Activity 。我可以通过单击 OptionMenu 中的项目来切换到 Activity。

现在,我想保存实例。当我在 Activity 1 的 EditText 中写入内容并更改为 Activity 2,然后再次切换回 Activity 1 时,我希望在 EditText 中恢复数据(字符串)。

我该怎么做?

这是 Activity 1 的代码:

public class ActivityA extends Activity {

private String txt1;
private String txt2;
private String txt3;
private String txt4;

private EditText edText1;
private EditText edText2;
private EditText edText3;
private EditText edText4;

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
setTitle(R.string.activity1_title);

txt1 = "-";
txt2 = "-";
txt3 = "-";
txt4 = "-";

if (savedInstanceState != null){
txt1 = savedInstanceState.getString("Value1");
txt2 = savedInstanceState.getString("Value2");
txt3 = savedInstanceState.getString("Value3");
txt4 = savedInstanceState.getString("Value4");
}

edText1 = (EditText) findViewById(R.id.editText);
edText1.setText(""+txt1);

edText2 = (EditText) findViewById(R.id.editText2);
edText2.setText(""+txt2);

edText3 = (EditText) findViewById(R.id.editText3);
edText3.setText(""+txt3);

edText4 = (EditText) findViewById(R.id.editText4);
edText4.setText(""+txt4);
}

public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("Value1",txt1);
savedInstanceState.putString("Value2",txt2);
savedInstanceState.putString("Value3",txt3);
savedInstanceState.putString("Value4",txt4);

}

public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
txt1 = savedInstanceState.getString("Value1");
txt2 = savedInstanceState.getString("Value2");
txt3 = savedInstanceState.getString("Value3");
txt4 = savedInstanceState.getString("Value4");

}
}

问题是它不保存字符串,我不知道为什么。
有人有想法吗?

最佳答案

共享首选项是存储和检索简单数据的方法。当您离开第一个 Activity 时存储它,并在用户返回该 Activity 时在 onCreate 中恢复它。

关于java - 如何保存字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37392298/

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