0

java.sql.Blob在 MySql 数据库中使用图像类型。当我尝试在数据库中插入对象时,出现异常“Java.lang.NullPointerException”

@Override
protected Object doInBackground(Object...arg0) {

    try {
        Bitmap photo = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
        Users user = new Users();
        user.setName("haris");

        try {
            Blob blo = null;
            blo.setBytes(1, getBytes(photo));

        } catch (Exception e) {
            System.out.println("Error:" + e.toString());
        }


        if (UserService.register(user)) {
            System.out.println("Successful registrationl");
        } else {
            System.out.println("API call wasn't successful");
        }


    } catch (Exception e) {
        System.out.println("Error:" + e.toString());
    }

    return null;
}

 public static byte[] getBytes(Bitmap bitmap) {
     ByteArrayOutputStream stream = new ByteArrayOutputStream();
     bitmap.compress(CompressFormat.PNG, 0, stream);
     return stream.toByteArray();
 }
4

2 回答 2

1

我正在使用这段代码将位图存储在 blob 中(从 drawable 转换而来):

db = this.getWDB();
    ContentValues values = new ContentValues();

         Drawable d = model.getAppIcon();
    BitmapDrawable bitDw = ((BitmapDrawable) d);
    Bitmap bitmap = bitDw.getBitmap();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
    byte[] imageInByte = stream.toByteArray();

    values.put(COLUMN_ICON_BLOB, imageInByte); 

    db.insert(TABLE_APPS, null, values);
    db.close();

并使用此方法从数据库中检索它

    public static Drawable convertByteArrayToDrawable( byte[] byteArrayToBeCOnvertedIntoBitMap) {

    Bitmap bitMapImage = BitmapFactory.decodeByteArray(
            byteArrayToBeCOnvertedIntoBitMap, 0,
            byteArrayToBeCOnvertedIntoBitMap.length);

    return new  BitmapDrawable(bitMapImage);
}
于 2013-01-30T15:33:21.577 回答
1

您有例外,因为 Blob 是一个接口,而 setBytes 是一个抽象方法。检查此链接如何在 Sqlite 中将图像存储为 blob 以及如何检索它?

于 2013-01-30T15:39:15.540 回答