Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store BLOB in Android's SQLite using SQLOpenHelper

Is there a way to store a BLOB into Android's SQLite using SQLOpenHelper?

My BLOB of type InputStream.

like image 474
mlevit Avatar asked Feb 03 '26 14:02

mlevit


1 Answers

SQLite doesn't support streaming BLOB or CLOB data. You have four options:

  • Convert the InputStream to a byte[]. This will only work if you have enough memory (see below).
  • Use FileOutputStream or an Android API that supports streaming
  • Split the data into small blocks and store then in SQLite
  • Use a database that works on Android and supports streaming. I only know the H2 database. But be aware the Android support for H2 is very new. In that case, you need to use the JDBC API, and you probably want to enable LOBs in the database, otherwise each large BLOB is stored in a separate file.

To convert an InputStream to a byte array, you could use:

public static byte[] readBytesAndClose(InputStream in) throws IOException {
    try {
        int block = 4 * 1024;
        ByteArrayOutputStream out = new ByteArrayOutputStream(block);
        byte[] buff = new byte[block];
        while (true) {
            int len = in.read(buff, 0, block);
            if (len < 0) {
                break;
            }
            out.write(buff, 0, len);
        }
        return out.toByteArray();
    } finally {
        in.close();
    }
}
like image 166
Thomas Mueller Avatar answered Feb 05 '26 02:02

Thomas Mueller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!