【问题标题】:how to add data from arraylist to shared preferences如何将数组列表中的数据添加到共享首选项
【发布时间】:2015-09-14 08:44:32
【问题描述】:

我有异步任务,我从服务器获取 JSONArray 格式的数据。我想将该数据保存在共享首选项中并在列表视图中显示。我正在使用适配器。 我试过了,但没有得到任何东西

   JSONArray arr = new JSONArray(strServerResponse);
   JSONObject jsonObj = arr.getJSONObject(0);
   for (int i = 0; i < arr.length(); i++) {
       pojo = new Pojo();
       JSONObject jobj2 = arr.getJSONObject(i);
       String tipoftheday = jobj2.optString("tipsoftheday");
       ArrayList<String> tii = new ArrayList<String>();
       tii.add(tipoftheday);
   }

今天的这个提示包含多个数据,我想将它们保存在共享首选项中,然后显示在列表视图中。 pojo 是一个我定义了 setter 和 getter 的类。

  ArrayList<Pojo> tips;
  tips = new ArrayList<Pojo>();
  pojo.setTip(mydatafromsharedprefernces);
  tips.add(pojo);
  tipsAdapter = new TipsAdapter(TipsActivity.this, tips);
  listTips.setAdapter(tipsAdapter);

如何在共享首选项中添加数据。谁能帮帮我。

【问题讨论】:

标签: android sharedpreferences


【解决方案1】:

我们在“SharedPreferences.Editor”中有方法“putStringSet”。

putStringSet(String key, Set<String> values)

您必须将ArrayList&lt;Pojo&gt; 转换为Set。 但是 Pojo 必须是可序列化的。

Set<String> set = new HashSet<String>(list);

并使用上述方法。

检查以下链接。

http://developer.android.com/reference/android/content/SharedPreferences.Editor.html

【讨论】:

    【解决方案2】:

    希望你知道如何声明 sharedPreference 的对象以及如何使用 Editor 对象。

    将您的数组列表转换为列表

    List<String> listTemp=tii ;
    

    在 sharedPreference 中添加整个列表:

    editor.putStringSet("key", listTemp);
    editor.commit();
    

    检索列表:

    Set<String> set = editor.getStringSet("key", null);
    

    【讨论】:

    • 收到错误错误的第二个参数类型。找到:'java.util.List',需要:'java.util.Set
    • 列表 listTemp=tii ; Set temp = new HashSet(listTemp); SharedPreferences.Editor editor = getSharedPreferences("MyPref",MODE_PRIVATE).edit(); editor.putStringSet("tipoftheday", temp); editor.commit();现在我如何在 pojo 类中设置值
    • 我用过 pojo.setTip(set.toString());但我只得到一个值
    【解决方案3】:

    您提到您在 json 中获取数据。将该 json 字符串存储在共享首选项中。当您从共享偏好中返回时对其进行解码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 2012-08-22
      • 1970-01-01
      相关资源
      最近更新 更多