Saving ArrayList in SQLite database in Android

后端 未结 7 1713
臣服心动
臣服心动 2020-12-04 18:11

I\'ve been working with SQLite on android and I would like to add an arraylist to a column in a table, and then fetch the data back as an arraylist. The arraylist is a list

7条回答
  •  天涯浪人
    2020-12-04 18:52

    Please forgive me for savagely plagiarizing my previous answer to BLOB vs. VARCHAR for storing arrays in a MySQL table. The other answers over there are also very pertinent.

    I think Con's approach is probably better than using java serialization since java's builtin serialization will need additional bytes, and non-java applications will have a harder time dealing with the data.

    public static void storeInDB(ArrayList longs) throws IOException, SQLException {
    
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        DataOutputStream dout = new DataOutputStream(bout);
        for (long l : longs) {
            dout.writeLong(l);
        }
        dout.close();
        byte[] asBytes = bout.toByteArray();
    
        PreparedStatement stmt = null;  // however you get this...
        stmt.setBytes(1, asBytes);
        stmt.executeUpdate();
        stmt.close();
    }
    
    public static ArrayList readFromDB() throws IOException, SQLException {
    
        ArrayList longs = new ArrayList();
        ResultSet rs = null;  // however you get this...
        while (rs.next()) {
            byte[] asBytes = rs.getBytes("myLongs");
            ByteArrayInputStream bin = new ByteArrayInputStream(asBytes);
            DataInputStream din = new DataInputStream(bin);
            for (int i = 0; i < asBytes.length/8; i++) {
                longs.add(din.readLong());
            }
            return longs;
        }
    
    }
    

    Note: If your lists will sometimes contain more than 31 longs (248 bytes), then you'll need to use BLOB. You cannot use BINARY() or VARBINARY() in MySQL. I realize you're asking about SQLite, but in the spirit of completely plagiarizing my previous answer, I will pretend you're asking about MySQL:

    mysql> CREATE TABLE t (a VARBINARY(2400)) ;
    ERROR 1074 (42000): Column length too big for column 'a' (max = 255);
    use BLOB or TEXT instead
    

提交回复
热议问题