gpt4 book ai didi

java - 访问 SharedPreference 在 Android 中不起作用

转载 作者:行者123 更新时间:2023-11-29 21:51:31 25 4
gpt4 key购买 nike

我有两个 Activity 。在第一个 Activity 中,我将一个字符串放入共享首选项中。然后我记录 getString 并看到它出现了。然后我转到第二个 Activity ,我 Toast getString 并获得显示的默认值。

第一个 Activity 代码:

SharedPreferences.Editor pref_editor = mcontext.getSharedPreferences("Prefs", Context.MODE_PRIVATE).edit();
SharedPreferences pref = mcontext.getSharedPreferences("Prefs", Context.MODE_PRIVATE);
pref_editor.putString("test", "It works!").commit();
Log.d("XXX", pref.getString("test", "ERRRROR"));

第二个 Activity 代码:

SharedPreferences pref = mcontext.getSharedPreferences("Prefs", Context.MODE_PRIVATE);
String current = pref.getString("test", "ERROR");
Toast.makeText(getApplicationContext(), current,
Toast.LENGTH_SHORT).show();

知道为什么我在 toast 时得到默认值“ERROR”吗?

最佳答案

请试试这个:-

SharedPreferences pref = mcontext.getSharedPreferences("Prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor pref_editor = pref.edit();
pref_editor.putString("test", "It works!")
pref_editor.commit();

关于java - 访问 SharedPreference 在 Android 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14300494/

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