【发布时间】:2018-11-18 22:18:05
【问题描述】:
我正在尝试在 SharedPreferences 中保存两个字符串。当我第一次运行应用程序时,它们会按预期显示。当我关闭应用程序并重新打开应用程序时,字符串不再设置为关闭应用程序之前的值,而是使用默认的字符串值。为什么是这样?以下是我保存和检索两个字符串的方法。
这是两个字符串
Intent intent = getIntent();
playerName1 = intent.getStringExtra("PLAYER_ONE");
playerName2 = intent.getStringExtra("PLAYER_TWO");
这是存储字符串的方法
private void savePlayerNames()
{
SharedPreferences sharedPreferences = getSharedPreferences("playerNames", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("playerOne", playerName1);
editor.putString("playerTwo", playerName2);
editor.commit();
}
这是检索它们的位置
private void displayPlayerNames(int current)
{
SharedPreferences sharedPreferences = getSharedPreferences("playerNames", Context.MODE_PRIVATE);
String playerOne = sharedPreferences.getString("playerOne","Player 1");
String playerTwo = sharedPreferences.getString("playerTwo","Player 2");
if(playerchoice[current].getText().toString().equals(""))
{
if (savedTracker % 2 == 0)
{
playerchoice[current].setText(x);
playerNameDisplay.setText(playerTwo + "'s Go!");
savedTracker++;
}
}
}
【问题讨论】:
-
也许额外内容不包含您认为的内容。也许你没有打电话给
savePlayerNames()。在调试器中逐步检查您的代码以找出或添加足够的日志记录语句以确定 Logcat 中发生了什么。顺便说一句,最好将"playerNames"和"playerOne"之类的值定义为常量,而不是重复字符串。 -
额外的 defo 包含预期的内容,因为当应用程序首次运行时字符串正确显示,只有当应用程序关闭并再次打开时,它们才会切换到默认值。
-
我建议您在 Android Studio 中查看设备的文件资源管理器。所以文件资源管理器 -> 你的应用程序 -> shared_prefs 然后你应该看到你的 XML。打开它,看看它是否包含你提交的值
标签: java android sharedpreferences