将大型列表存储到SQLite
问题描述:
我正在开发一个应用程序,我在其中持续下载大量数据。将大型列表存储到SQLite
json格式的数据和我使用Gson反序列化它。现在我将它存储在SQLite数据库中。我必须计算关系并将它们存储到关系数据库中。然而这需要太多时间。
将类对象保存到db会更加方便。
的数据看起来是这样的反序列化后:
Class A{
private String name;
private List<B> subItems;
}
Class B{
private String name;
private List<C> subItems
}
我能坚持这样一个更简单的方法,例如通过使它们可序列化的?如何才能做到这一点?
答
是的,序列化是一种更好的解决方案,它适用于Android。下面的例子是从http://www.jondev.net/articles/Android_Serialization_Example_%28Java%29
序列化方法采取:
public static byte[] serializeObject(Object o) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(o);
out.close();
// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
return buf;
} catch(IOException ioe) {
Log.e("serializeObject", "error", ioe);
return null;
}
反序列化方法:
public static Object deserializeObject(byte[] b) {
try {
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(b));
Object object = in.readObject();
in.close();
return object;
} catch(ClassNotFoundException cnfe) {
Log.e("deserializeObject", "class not found error", cnfe);
return null;
} catch(IOException ioe) {
Log.e("deserializeObject", "io error", ioe);
return null;
}
非常感谢!你现在是我如何处理类之间的关系。 A类拥有B类列表。我是序列化每个还是仅仅是“顶级”类? – johan
使这两个类可序列化。我想你只是序列化A级。 – Caner
好的。我将它们保存为一个blob? – johan