为什么在Android Studio中没有使用共享流程来保存数据?

发布于 2025-01-24 17:36:24 字数 1153 浏览 3 评论 0原文

我遇到了这样的问题,以至于文件中的锁定数据来自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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

望她远 2025-01-31 17:36:24

因为您在调用loadText()之前立即覆盖它。这会导致旧价值丢失。

Because you're overwriting it right before calling LoadText(). This causes the old value to be lost.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文