【问题标题】:storing data to sharedpreferences using json使用 json 将数据存储到 sharedpreferences
【发布时间】:2012-03-20 20:31:52
【问题描述】:

我正在开发一个小型 Android 应用程序!
我有一个班级 MyPref

public class MyPref{
{
java.util.Calendar cal;
int id;
String name;
//some more methods and constructor
}

我需要将一组 MyPref 对象存储到 sharedpreferences...

java.util.ArrayList<MyPref> array=new java.util.ArrayList<MyPref>();
array.add(//MyPref object);
array.add(//MyPref object);

现在如何将这个 ArrayList 对象存储到 sharedpreferences..
我试过了。。

JSONObject o=new JSONObject();
o.put("list",array);
SharedPreferences s=PreferenceManager.getDefaultSharedPreferences(this);
Editor edt=s.edit();
edt.putString("mylist",o.toString());
edt.commit();

但这不起作用!
还有其他选择吗??
请帮助我..
提前谢谢..

【问题讨论】:

  • 您需要比“它不起作用”更具体。是否存在 logcat 错误、ANR、某种可见错误,或者您什么都看不到,发生了什么...
  • 它在字符串上得到 java.lang.ClassCasteException
  • 你不是说错误在哪一行。人们可以尝试从您的代码中找出答案,但如果您指定错误发生的位置,您将获得更多帮助。

标签: android json arraylist android-preferences


【解决方案1】:
JSONObject o=new JSONObject();
o.put("list",array);

我可能错了,但我很确定您不能使用JSONObject.put(...) 将任意Java 对象放入JSONObject。来自文档...

public JSONObject put(字符串名称,对象值)

JSONObject、JSONArray、String、Boolean、Integer、Long、Double、NULL 或 null。可能不是 NaN 或无穷大。

没有提到能够放置任何其他类型的 Java 对象,而您正在尝试放置 ArrayList&lt;MyPref&gt;

【讨论】:

    猜你喜欢
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2019-09-23
    • 1970-01-01
    • 2015-02-13
    • 2013-09-11
    • 1970-01-01
    • 2021-11-15
    相关资源
    最近更新 更多