简体   繁体   中英

How to insert an Image to sqlite database

Whenever I try to add an Image to sqlite table it shows null although words are inserted successfully.

Code:

if (resultCode == RESULT_OK && requestCode == PICK_IMAGE) {
        Uri imageUri = data.getData();
        try {
            Bitmap bmp = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
            ByteArrayOutputStream bos=new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.PNG,100,bos);
            byte[] img=bos.toByteArray();
            ContentValues cv=new ContentValues();
            cv.put("image", img);
            db.insertImage(cv,editword,editcategory);
            Toast.makeText(this, "Image Uploaded", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

Database Scheme:

    `String sql = "Insert Into Images (Images, Name, Category) Values ("+cv+", '"+name+"', '"+category+"')";
mDb.execSQL(sql);`    

Image datatype in that table is Blob

I solved the problem by placing:

Bitmap bmp = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);

alone in the try-catch clause. I also replaced the:

db.insertImage(cv,editword,editcategory);
Toast.makeText(this, "Image Uploaded", Toast.LENGTH_SHORT).show();

in a new function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM