Android 如何在sqlite数据库中存储对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1243181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:49:51  来源:igfitidea点击:

How to store object in sqlite database?

android

提问by Kumar

Is it possible to store user defined objects in a SQLite database from Android? For example: I am creating one class and I want to store that class object in the database. Is it possible? If it is, how to proceed? On the Blackberry platform, I am able to store objects directly in persistent objects. Is it possible to do this with SQLite and Android?

是否可以将用户定义的对象存储在 Android 的 SQLite 数据库中?例如:我正在创建一个类,我想将该类对象存储在数据库中。是否可以?如果是,如何进行?在 Blackberry 平台上,我能够将对象直接存储在持久对象中。是否可以使用 SQLite 和 Android 来做到这一点?

回答by Prashast

You'll need to be able to serialize your object into a byte stream and then recreate your object from a byte stream.

您需要能够将对象序列化为字节流,然后从字节流重新创建对象。

Then, just store that byte stream in your db.

然后,只需将该字节流存储在您的数据库中。

EDIT: Read this articleto learn about serialization in Java. It caters to the subject in a much better way than I would be able to by just giving some code snippets.

编辑:阅读本文以了解 Java 中的序列化。它以比我仅提供一些代码片段更好的方式迎合了这个主题。

回答by SohailAziz

Instead of storing them in SQLite why not store them in db4o, which is specifically designed for storing objects. A simple tutorialfor sotring objects using db4o.

与其将它们存储在 SQLite 中,为什么不将它们存储在db4o 中,它专为存储对象而设计。使用 db4o 对对象进行排序的简单教程

回答by Praveen

Use this code to convert your object to byte array and store it in your database as "BLOB"

使用此代码将您的对象转换为字节数组并将其作为“BLOB”存储在您的数据库中

public byte[] makebyte(Dataobject modeldata) {
            try {

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(baos);
                oos.writeObject(modeldata);
                byte[] employeeAsBytes = baos.toByteArray();
                ByteArrayInputStream bais = new ByteArrayInputStream(employeeAsBytes);
                return employeeAsBytes;
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

Use this code to convert your byte array to your object again

使用此代码再次将您的字节数组转换为您的对象

public Dataobject read(byte[] data) {
    try {


        ByteArrayInputStream baip = new ByteArrayInputStream(data);
        ObjectInputStream ois = new ObjectInputStream(baip);
        Dataobject dataobj = (Dataobject ) ois.readObject();
        return dataobj ;

    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}