存储 ArrayList<CustomClass>进入共享首选项 [英] Store ArrayList&lt;CustomClass&gt; into SharedPreferences

查看:25
本文介绍了存储 ArrayList<CustomClass>进入共享首选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ArrayList 的自定义类 Task

I have an ArrayList of custom class Task

public class Task {

    String name,desc;
    Date date;
    Context context;

    public Task(String name, String desc, Date date, Context context) {
        this.name = name;
        this.desc = desc;
        this.date = date;
        this.context = context;

    }
}

我想将它保存在 SharedPreferences .. 我读到可以通过将其转换为 Set 来完成.. 但我不知道该怎么做..

I want to save it in SharedPreferences.. I read that can be done by converting it to Set.. But I don't know how to do this..

有没有办法做到这一点?或者任何其他方式来存储数据而不是 SharedPreferences?

Is there a way to do this? Or any other way to store data rather than SharedPreferences?

谢谢:)

String s = prefs.getString("tasks", null);

    if (tasks.size() == 0 && s != null) {
        tasks = new Gson().fromJson(s, listOfObjects);
        Toast.makeText(MainActivity.this, "Got Tasks: " + tasks, Toast.LENGTH_LONG)
                .show();
    }

protected void onPause() {
    super.onPause();
    Editor editPrefs = prefs.edit();
    Gson gson = new Gson();
    String s = null;
    if(tasks.size() > 0) {
        s = gson.toJson(tasks, Task.class);
        Toast.makeText(MainActivity.this, "Tasks: " + s, Toast.LENGTH_LONG)
                .show();
    }
    editPrefs.putString("tasks", s);
    editPrefs.commit();

推荐答案

您无法确定保存 Context 对象,保存它也没有意义.我的建议是覆盖 toString 以返回一个 JSONObject,该对象包含要存储在 SharedPreference 中的信息.

You can't save for sure the Context object, and it does not make sense to save it. My suggestion would be to override toString to return a JSONObject that holds the information you want to store in the SharedPreference.

public String toString() {
   JSONObject obj = new JSONObject();
   try {
      obj.put("name", name);
      obj.put("desc", desc);
      obj.put("date", date.getTime());
  catch (JSONException e) {
        Log.e(getClass().getSimpleName(), e.toString());
   }
   return obj.toString();
}

并在 SharedPreference 中写入这个 json 对象.当你读回它时,你必须解析和构造你的 Task 对象

and write this json object in the SharedPreference. When you read it back you have to parse and construct your Task objects

这篇关于存储 ArrayList<CustomClass>进入共享首选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆