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

问题描述

我有一个自定义类 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();
}

并将此json对象写入SharedPreference.当您读回它时,您必须解析并构造您的 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>进入SharedPreferences的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 06:51