为什么在Android Studio中没有使用共享流程来保存数据?
我遇到了这样的问题,以至于文件中的锁定数据来自shared_prefs文件夹,并且也从中加载了。但是,当我退出应用程序时,文本视图中的文本消失了。
在下面,我从ongreate,loadText和onpause()附加了代码
String result_1 = edit.getText().toString();
if(result_1.isEmpty()){
result_2 = 0;
} else {
result_2 = Integer.parseInt(result_1);
}
result_products += result_2;
String result_full = Integer.toString(result_products);
sharedPreferences = getSharedPreferences("SAVE", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("TEXT", result_full);
editor.apply();
LoadText();
...
protected void LoadText() {
sharedPreferences = getSharedPreferences("SAVE", MODE_PRIVATE);
TextView textView_products = findViewById(R.id.textView_products);
String savedText = sharedPreferences.getString("TEXT", result_full);
textView_products.setText(savedText);
}
@Override
protected void onPause() {
super.onPause();
sharedPreferences = getSharedPreferences("SAVE", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("TEXT", result_full);
editor.apply();
}
I faced such problem that lock data in file is from shared_prefs folder and also loaded from it. However, when I exit the application, the text from my TextView disappears.
Below I am attaching the code from onCreate, LoadText and onPause()
String result_1 = edit.getText().toString();
if(result_1.isEmpty()){
result_2 = 0;
} else {
result_2 = Integer.parseInt(result_1);
}
result_products += result_2;
String result_full = Integer.toString(result_products);
sharedPreferences = getSharedPreferences("SAVE", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("TEXT", result_full);
editor.apply();
LoadText();
...
protected void LoadText() {
sharedPreferences = getSharedPreferences("SAVE", MODE_PRIVATE);
TextView textView_products = findViewById(R.id.textView_products);
String savedText = sharedPreferences.getString("TEXT", result_full);
textView_products.setText(savedText);
}
@Override
protected void onPause() {
super.onPause();
sharedPreferences = getSharedPreferences("SAVE", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("TEXT", result_full);
editor.apply();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为您在调用loadText()之前立即覆盖它。这会导致旧价值丢失。
Because you're overwriting it right before calling LoadText(). This causes the old value to be lost.