如何在android中的sqlite数据库中存储带有列表的自定义对象 [英] how to store custom object with list in sqlite database in android

查看:185
本文介绍了如何在android中的sqlite数据库中存储带有列表的自定义对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为包含这样的列表的自定义对象创建表

how to create table for a custom object that contain a list of like this

public class Mobel implements Parcelable {
    int thumbnail;
    List<Integer> pics;
    int price;
    String joziat;
    String code;
}

您知道int和string列没有问题,但是我应该如何存储我的整数列表?我当时在想为它创建一个单独的表,但是由于我不知道我对特定对象有多少照片,我不知道该如何加入他们

as you know there is no problem with int and string columns but how should i store my list of integer ? i was thinking to make a separate table for it but as i don't know ho many pic i have for particular object have no idea how should i join them

推荐答案

虽然确实不能在sqlite中存储对象,但是可以序列化并存储序列化的对象:

While indeed you can not store objects in sqlite, you can serialize it and store the serialized object:

Gson gson = new Gson();
String toStoreObject = gson.toJson(modelObject, Model.class);

当您取回字符串时,只需执行以下操作:

And when you get the string back just do:

Model modelObject = gson.fromJson(storedObjectString, Model.class);

或者只是序列化对象的属性(在您的情况下为列表)。

Or just serialize the property of the object (in your case the List).

我会做的其他事情:


  1. 为图像创建另一个表并将其链接表到存储模型对象的表(n对1关系)

  1. Create another table for the images and link that table to the table in which you store your Model object (n to 1 relationship)

不要在sqlite中存储图像。将它们存储在内部存储器中,并在sqlite中仅保存文件的路径。

Don't store images in sqlite. Store them in the internal storage and in sqlite save just the path to the file.

如果您真的想将图像存储在sqlite中,请将图像转换为base64字符串并存储该字符串。

If you really really want to store the images in sqlite, convert the image to a base64 string and store that one.

这篇关于如何在android中的sqlite数据库中存储带有列表的自定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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