字符串未使用SharedPreferences存储

时间:2018-11-18 22:18:05

标签: java android sharedpreferences

我正在尝试在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++;
        }
     }
 }

2 个答案:

答案 0 :(得分:1)

使用以下类 这将帮助您摆脱所有令人困惑的代码

x

}

获取/保存数据的简单初始化类并执行操作

len(x)

希望有帮助

快乐的编码:)

我忘记提及的一件事是我使用了gson lib,因此将此行添加到您的应用程序lebvel gradle文件中并构建您的gradle

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;
    }
}

答案 1 :(得分:0)

替换

editor.commit();

使用

editor.apply();

commit()将其首选项写到持久性存储synchronously中,由于各种原因,它可能会失败。 apply()立即将其更改写入内存SharedPreferences,但开始向磁盘提交asynchronous提交。

apply()是完全安全的。您可以放心使用它,因为它将获得更新的首选项值。