Android:存储在SQLite中时,图像的字节数组为null

时间:2018-04-14 21:34:48

标签: java android android-sqlite

我非常接近这项工作。我从相机中获取了一张照片并将其存储在我的SQLite数据库中。但是,当我存储它时,我收到此错误。存储时,图像的字节数组为空。为什么?我该如何解决?

  

E / AndroidRuntime:致命异常:主要                     处理:com.example.psa.stepbystep,PID:16363                     java.lang.NullPointerException:尝试获取null数组的长度                         at com.example.psa.stepbystep.Walk.writeToParcel(Walk.java:161)                         在android.os.Parcel.writeParcelable(Parcel.java:1730)                         在android.os.Parcel.writeValue(Parcel.java:1636)                         在android.os.Parcel.writeArrayMapInternal(Parcel.java:777)                         在android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1506)

步行活动包含地块

public Walk(Parcel in) {
        this._photo = new byte[in.readInt()];
        in.readByteArray(_photo);
    }

public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(_photo.length);
        dest.writeByteArray(_photo);
    }

WalkPhoto有此转换

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

    //Convert from byte array to bitmap
    public static Bitmap getImage(byte[] image) {
        return BitmapFactory.decodeByteArray(image, 0, image.length);
    }

WalkPhoto还将此图像存储在数据库中

     if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            ImageView imageview = findViewById(R.id.imageView);
            imageview.setImageBitmap(imageBitmap);

            //Bitmap to bytes for database
            byte[] photo = getBytes(imageBitmap);

             DatabaseHandler mydb = new DatabaseHandler(getApplicationContext());

            Walk walk = new Walk(photo);

            mydb.addWalk(walk);
}

1 个答案:

答案 0 :(得分:0)

您可以使用“blob”存储图片,如本文所述:https://stackoverflow.com/a/9357943/5455940

在上面的帖子中,“insertStatement_logo”是SQLiteStatement类的实例。 SQLiteStatementSQLiteProgram类的子类。

请参阅链接以供参考。 https://developer.android.com/reference/android/database/sqlite/SQLiteStatement.html

https://developer.android.com/reference/android/database/sqlite/SQLiteProgram.html