在共享首选项中存储一维字符串数组

时间:2018-11-15 15:14:37

标签: java android

我有两个数组,第一个包含9个按钮。第二个可以容纳9个字符串。我有一个名为getPlayerChoiceText的方法,用于使用playerchoice数组中每个按钮上设置的文本填充String数组。如何使用SharedPreferences保存此文本?

private String[] getPlayerChoiceText()
{
    playerchoiceText[0] = playerchoice[0].getText().toString();
    playerchoiceText[1] = playerchoice[1].getText().toString();
    playerchoiceText[2] = playerchoice[2].getText().toString();
    playerchoiceText[3] = playerchoice[3].getText().toString();
    playerchoiceText[4] = playerchoice[4].getText().toString();
    playerchoiceText[5] = playerchoice[5].getText().toString();
    playerchoiceText[6] = playerchoice[6].getText().toString();
    playerchoiceText[7] = playerchoice[7].getText().toString();
    playerchoiceText[8] = playerchoice[8].getText().toString();

    return playerchoiceText;
}

   private void saveData()
   {
      SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
      SharedPreferences.Editor editor = sharedPreferences.edit();
      playerchoiceText = getPlayerChoiceText();
   }

3 个答案:

答案 0 :(得分:2)

我有同样的问题。我使用JSONArray解决了这个问题。

JSONArray choices = new JSONArray();
choices.put("1");
choices.put("2");
choices.put("3");

// Save
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("choices", choices.toString());

// Retrieve
choices = new JSONArray(sharedPreferences.getString("choices", "[]"));

通过这种方式,您可以轻松执行InsertDelete操作。我希望这会有所帮助。

答案 1 :(得分:0)

Android的SharedPreferences用作键值存储,并且不允许您直接存储Java对象。因此,如果您要使用共享的首选项存储它们,则将玩家选择的文本值表示为地图会更有意义。

如果要继续将选择的文本表示为数组,可以在这里使用一个技巧。您可以使用分隔符来存储文本,例如管道:

String choices = String.join("|", playerchoiceText);
SharedPreferences prefs = getSharedPreferences(YOUR_PREFS_KEY, Context.MODE_PRIVATE);
prefs.edit().putString("choices", choices).apply();

然后,在出路:

SharedPreferences prefs = getSharedPreferences(YOUR_PREFS_KEY, Context.MODE_PRIVATE);
String[] playerchoiceText = prefs.getString("choices", "").split("\\|");

答案 2 :(得分:0)

使用put/getStringSet()

private void saveData()
   {
      SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
      SharedPreferences.Editor editor = sharedPreferences.edit();
      String[] playerchoiceText = getPlayerChoiceText();
      editor.putStringSet("player_choice", new HashSet<T>(Arrays.asList(playerchoiceText)); 
      editor.commit();
   }