【问题标题】:How to store ArrayList of my class in shared preference?如何将我的班级的 ArrayList 存储在共享偏好中?
【发布时间】:2018-07-03 13:15:03
【问题描述】:

我想以共享首选项存储多边形对象的 ArrayList。有人可以帮我解决这个问题吗?

要保存列表:

public void savePolygonObjects(Context context){
    SharedPreferences mPrefs = context.getSharedPreferences("MyPref", context.MODE_PRIVATE);
    SharedPreferences.Editor prefsEditor = mPrefs.edit();
    Gson gson = new Gson();
    String json = gson.toJson(polygonArrayList);
    prefsEditor.putString("myJson", json);
    prefsEditor.commit();
}

检索列表:

SharedPreferences mPrefs = getSharedPreferences("MyPref", 
                                     getApplicationContext().MODE_PRIVATE);
Gson gson = new Gson();
String json = mPrefs.getString("myJson", "");
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(json).getAsJsonArray();

for(int i=0; i< array.size(); i++){
    polygonArrayList.add(gson.fromJson(array.get(i), Polygon.class));
}

【问题讨论】:

  • 显示到目前为止你尝试过的代码。
  • 唯一的方法是将你的数组转换成 JSON 字符串并保存在共享首选项中。
  • 它给了我错误:java.lang.IllegalArgumentException: class gs declarations multiple JSON fields named d @LucaNicoletti
  • 发布你的做法
  • 上面的代码给了我一个异常,说不能将对象转换为 json。它在 gson.toJson(list) @LucaNicoletti 处给出错误

标签: java android


【解决方案1】:

您可以将您的ArrayList 作为序列化对象添加到SharedPreferences,然后在从 SharedPreferences 中读取它时对其进行反序列化。 这是一个代码示例:

ArrayList<Polygon> polygonList = new ArrayList<Polygon>();

// Add the data to the list

// Serializing and adding the ArrayList to the SharedPreferences
SharedPreferences prefs = getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
  Editor editor = prefs.edit();
  try {
    editor.putString(POLYGONS, ObjectSerializer.serialize(polygonList));
  } catch (IOException e) {
    e.printStackTrace();
  }
  editor.commit();

然后稍后通过反序列化来检索ArrayList,如下所示:

 SharedPreferences prefs = getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);

  try {
    polygonList = (ArrayList<POLYGON>) ObjectSerializer.deserialize(prefs.getString(POLYGONS, ObjectSerializer.serialize(new ArrayList<POLYGON>())));
  } catch (IOException e) {
    e.printStackTrace();
  } catch (ClassNotFoundException e) {
    e.printStackTrace();
  }

您还需要将 ObjectSerializer 类添加到您的项目中,您可以从这里获取它:ObjectSerializer.java

我提到了this answer,还有一种替代方法,所以你也可以检查一下

【讨论】:

  • 我应该为 org.apache.pig 添加哪些依赖项? @Sudhanshu Vohra
  • @BhushanBorole 将类复制到您的项目中即可,注意:删除依赖项:import org.apache.commons.logging.Log;导入 org.apache.commons.logging.LogFactory;和私有静态最终日志日志 = LogFactory.getLog(ObjectSerializer.class);因为它们并不重要。同时更新包名。
  • 我做了所有的事情,但仍然无法正常工作,没有例外,但我仍然没有获得所需的数据。 @Sudhanshu Vohra
  • 当您从 SharedPreferences 获取它时返回“null”吗?
  • 是的@Sudhanshu Vohra
【解决方案2】:
List<Person> customer = new ArrayList<Person>();
Person p = .....;
customer.add(person);

【讨论】:

    猜你喜欢
    • 2012-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多