How to store object in sqlite database?

后端 未结 3 460
南方客
南方客 2020-12-01 00:24

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.

相关标签:
3条回答
  • 2020-12-01 00:54

    Use this code to convert your object to byte array and store it in your database as "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;
    }
    
    0 讨论(0)
  • 2020-12-01 00:59

    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 article to 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.

    0 讨论(0)
  • 2020-12-01 00:59

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

    0 讨论(0)
提交回复
热议问题