【问题标题】:Android: Byte array for the image is null when stored in SQLiteAndroid:存储在 SQLite 中时,图像的字节数组为空
【发布时间】:2018-04-14 21:34:48
【问题描述】:

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

E/AndroidRuntime: 致命异常: main 进程:com.example.psa.stepbystep,PID:16363 java.lang.NullPointerException:尝试获取空数组的长度 在 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);
}

【问题讨论】:

标签: java android android-sqlite


【解决方案1】:

您可以使用“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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-22
    • 1970-01-01
    • 1970-01-01
    • 2011-05-10
    • 2013-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多