将图像blob类型插入sqlite并插入查询

时间:2018-03-20 22:56:27

标签: android sqlite android-studio imageview

我想将用户选择的图像存储到Android中的数据库中。我使用 INSERT INTO 查询 ,但我无法存储图片 !!

在我的班级模型中我有一个blob图像:private Blob photo;

AddBook类:

 private byte[] Myphoto;

 private void initViews() {
     imageView = (ImageView) findViewById(R.id.imageViewCheckImage);
}

  private void addBook() {

  Myphoto = profileImage(bitmap);

 String insertSQL = "INSERT INTO books \n" +
                "(name, photoBook)\n" +
                "VALUES \n" +
                "(?, ?);";

        mDatabase.execSQL(insertSQL, new Object[]{title, Myphoto});
        Toast.makeText(this, "Book Added Successfully", Toast.LENGTH_SHORT).show();
}

这是将位图转换为字节的profileImage方法:

 //Convert bitmap to bytes
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
    private byte[] profileImage(Bitmap b){

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        b.compress(Bitmap.CompressFormat.PNG, 0, bos);
        return bos.toByteArray();

    }


 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == request_get_photo_code && resultCode == RESULT_OK) {
            Uri photoUri = data.getData();
            ContentResolver cr = this.getContentResolver();
             bitmap = null;
           try {

               bitmap = BitmapFactory.decodeStream(cr.openInputStream(photoUri));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            imageView.setImageBitmap(bitmap);
        }

    }

我可以从画廊中选择图像但我无法存储它,我不知道问题出在哪里但我认为是在这一行:

 mDatabase.execSQL(insertSQL, new Object[]{title, Myphoto});

将Myphoto对象放在execSQL中是对的吗?

3 个答案:

答案 0 :(得分:0)

而不是: -

 String insertSQL = "INSERT INTO books \n" +
                "(name, photoBook)\n" +
                "VALUES \n" +
                "(?, ?);";

        mDatabase.execSQL(insertSQL, new Object[]{title, Myphoto});

尝试: -

ContentValues cv = new ContentValues();
cv.put("name",title);
cv.put("photo",Myphoto);
mDatabase.insert("books",null,cv);

如果您想通过SQL插入,那么您必须将byte []转换为x' 0001020304'等字符串。 (5个字节)。

答案 1 :(得分:0)

在您的情况下,您可以避免使用BLOB类型。 只需将图像URI存储为数据库中的字符串,并将其设置为图像视图,如下所示:  imageView.setImageURI(photoUri);

答案 2 :(得分:0)

如果您使用BLOB,应用程序可能会崩溃。图片字节值可能太大。您应该在数据库中使用uri作为字符串并通过uri检索。然后,设置您的imageView。

func datesFor(day: Int, year: Int) -> [Date] {
    var res = [Date]()
    var components = DateComponents(year: year, day: day)
    for month in 1...12 {
        components.month = month
        if let date = Calendar.current.date(from: components) {
            // Feb 29, 2018 results in Mar 1, 2018. This check skips such dates
            if Calendar.current.date(date, matchesComponents: components) {
                res.append(date)
            }
        }
    }

    return res
}

print(datesFor(day: 29, year: 2018))