【问题标题】:Android SharedPreferences set/retrieve checkbox with HashMap/For each loopAndroid SharedPreferences 使用 HashMap/For 每个循环设置/检索复选框
【发布时间】:2018-12-17 18:50:19
【问题描述】:

我将复选框文本和isChecked 保存到SharedPreferences 中,使用for each loop 获取复选框值,我使用HashMap 存储所有值。

我保存复选框文本和 isChecked 的代码:

 HashMap<String,Object> amenityMap = new HashMap<>();

   for(CheckBox checkBox : checkBoxes){
        if(checkBox.isChecked()){
            amenityMap.put(checkBox.getText().toString().trim(),true);
        }
    }

    saveHashMapSharedPreferences(parentActivity, amenityMap, Amenity.AMENITY_DETAILS,Amenity.AMENITY_DETAILS);

SharedPreference 方法:

public static void saveHashMapSharedPreferences(Activity parentActivity,HashMap<String,Object> amenityMap,String spType, String key) {
    SharedPreferences appSharedPrefs = parentActivity.getSharedPreferences(spType, Context.MODE_PRIVATE);

    SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();

    Gson gson = new Gson();
    String json = gson.toJson(amenityMap); //tasks is an ArrayList instance variable
    prefsEditor.putString(key, json);
    prefsEditor.apply();
}

下图是SharedPreferences.xml中保存的checkbox值:

所以它的keyamenityDetails,checkbox的值都在那里。

如何从此 SharedPreference 中检索复选框值并将其设置回 isChecked 的复选框?

【问题讨论】:

    标签: android foreach hashmap sharedpreferences


    【解决方案1】:

    首先更改以下内容:

    HashMap&lt;String,Object&gt; amenityMap = new HashMap&lt;&gt;();

    HashMap&lt;String,Boolean&gt; amenityMap = new HashMap&lt;&gt;();

    如下更改你的 for each 循环:

    for(CheckBox checkBox : checkBoxes){
         amenityMap.put(checkBox.getText().toString().trim(),checkBox.isChecked());    
    }
    

    然后您可以按如下方式检索值:

    SharedPreferences appSharedPrefs = parentActivity.getSharedPreferences(spType, Context.MODE_PRIVATE);
    Type type = new TypeToken<Map<String, Boolean>>(){}.getType();
    Map<String, Boolean> storedAmenityMap = gson.fromJson(appSharedPrefs.getString(key,""), type);
    

    那么每当你想设置复选框状态时:

    checkBoxObj.setChecked(storedAmenityMap.get(checkBoxObj.getText()));
    

    【讨论】:

    • 我在 checkBoxObj.setChecked(storedAmenityMap.get(checkBoxObj.getText())) 上使用 'java.lang.NullPointerException: cannot unbox null value' 检索错误;
    • @TommyChong 确保您已将数据正确存储在共享首选项中
    • 谢谢你,兄弟,我想我明白你的意思了哈哈,很好的编码和解决方案。我已经解决了。
    • @TommyChong 没问题。享受编码:-)
    【解决方案2】:

    首先你的HashMap 应该是HashMap&lt;String, boolean&gt;。 要恢复,您也可以使用Gson 将保存的数据再次解析为HashMap,并使用您恢复的HashMap 恢复CheckBox 状态

    Type collectionType = new TypeToken<HashMap<String, boolean>>(){}.getType();
    HashMap<String, boolean> hashMap = gson.fromJson(appSharedPrefs.getString(key,""), collectionType);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-11
      • 2021-02-27
      相关资源
      最近更新 更多