如何在Android中将Raw java.lang.Bytes []保存到SQLite BLOB?

时间:2013-07-14 18:59:23

标签: java android android-sqlite

我在Android中有一个java.lang.Bytes[]数组,我想将它保存到SQLLite表中的BLOB列中。

我创建了表和列等。我不确定如何将数组保存为BLOB。

public void AddUpdateKeys(int deviceID, String key, Boolean learned, Byte[] rawKey)
    {   
    ... // other code
    ContentValues cv = new ContentValues();
    cv.put(colKeyDevID, deviceID);
    cv.put(colKeyLearned, key);
    cv.put(colKeyLearned, learned ? 1 : 0 );        
    cv.put(colKeyData, rawKey); <-- Here is the issue, how to convert Type Byte[] to byte[]

如何将java.lang.Byte[]中的原始数据转换为byte[],我试过了

private byte[] getBytes(Byte[] learnedKey) {

    byte[] result = new byte[learnedKey.length];
    for(int i=0; i<learnedKey.length; i++){
        result[i] = learnedKey[i].byteValue();
    }
    return result;
}

但是只是“崩溃”,我还检查了rawKey包含的数据?我是Android SQLLite Java的新手。我想将Byte[]的原始数据保存到Blob中,稍后再读取并再次使用。

1 个答案:

答案 0 :(得分:0)

实际上,SQL BLOB类型将大量二进制数据(字节)存储为数据库列中的值。 所以使用列值类型应该指定为blob而不是table。然后将你的byte []保存到那里。你应该在那里执行这些步骤(例如图片):

将图像转换为位图。

2 - 将位图转换为字节数组。

 public static byte[] getBytesFromBitmap(Bitmap bitmap) {
    if (bitmap!=null) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
        return stream.toByteArray();
    }
    return null;
}

3-make column type as blob。 4 - 将此字节数组保存到该列。