我试图在 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++;
}
}
}
最佳答案
使用下面的类。这将帮助您摆脱所有令人困惑的代码
public class PlayersData {
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
private static final String PLAYERS_DATA = "PLAYERS_DATA";
private static final String PLAYERS = "PLAYERS";
public PlayersData(Context context) {
sharedPreferences = context.getSharedPreferences(PLAYERS_DATA, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
}
public void savePlayers(Players players) {
Gson gson = new Gson();
String json = gson.toJson(players);
editor.putString(PLAYERS, json);
editor.commit();
}
public Players getPlayers() {
Gson gson = new Gson();
String json = sharedPreferences.getString(PLAYERS, null);
return gson.fromJson(json, Players.class);
}
public class Players{
private String one;
private String two;
public Players() {
}
public Players(String one, String two) {
this.one = one;
this.two = two;
}
public String getOne() {
return one;
}
public void setOne(String one) {
this.one = one;
}
public String getTwo() {
return two;
}
public void setTwo(String two) {
this.two = two;
}
}
}
要获取/保存数据,只需初始化类并执行操作:
PlayersData playersData = new PlayersData(this); //this is the context
有一件事我忘了提,我使用了 gson lib,所以将这一行添加到您的应用级 Gradle 文件并构建您的 Gradle:
implementation 'com.google.code.gson:gson:2.8.5'
关于java - 未使用 SharedPreferences 存储的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53366015/