【发布时间】:2023-03-23 08:25:01
【问题描述】:
我一直在为我的一些项目而苦苦挣扎。我需要保存 2 个TextView 值,以便当用户按下后退按钮或重新启动手机并稍后返回应用程序时它们在那里。到目前为止,我已经尝试了很多方法,但不知何故它不起作用...
该应用程序显示带有“目标”的TextView,用户自己输入该目标。第二个TextView 显示许多“光束”,用户自己再次输入。当用户旋转屏幕时我已经能够保存数据,但是在应用程序被杀死后保存数据更加困难。
public class MainActivity extends AppCompatActivity {
SharedPreferences preferences;
TextView showGoalTextView;
TextView showBeamsTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showGoalTextView = (TextView) findViewById(R.id.textView3);
showBeamsTextView = (TextView) findViewById(R.id.textView2);
preferences = getSharedPreferences("userData", MODE_PRIVATE);
updateGoalTextView();
}
还有updateGoalTextView() 方法:
public void updateGoalTextView() {
String goalSave = showGoalTextView.getText().toString();
String beamsSave = showBeamsTextView.getText().toString();
SharedPreferences preferences = getSharedPreferences("userData", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("goals", goalSave);
editor.putString("beam", beamsSave);
editor.apply();
// get the saved string from shared preferences
String name1 = preferences.getString("goals", "");
// set reference to the text view
showGoalTextView = (TextView) findViewById(R.id.textView3);
// set the string from sp as text of the textview
showGoalTextView.setText(name1);
}
updateGoalTextView 在onCreate 中调用。希望我使用的方法是正确的,因为如果我用AS在手机上运行它,它根本不会保存数据并重新创建它。
知道如何解决吗? 要更清楚地了解我的意思,请下载我的测试版应用程序:https://play.google.com/store/apps/details?id=jhpcoenen.connectlife.beams
谢谢你,所有的人都回答了。在查看答案并在 GOOGLE 上搜索后,我终于修复了它。
【问题讨论】:
-
SAVED_STATE_GOAL_KEY 和“SAVED_STATE_GOAL_KEY”是同一个东西(相同的字符串)吗?
-
@FWeigl 是的,它们是一样的。
-
@SandeepRandhawa 也可以用 TextViews 完成吗?
-
您尝试从 SharedPreferences 恢复字符串的位置(哪种方法)?看起来你是在 onSaveInstanceState 中做的,这是错误的。
标签: android textview save sharedpreferences state