Search code examples
androidandroid-sqlite

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


Solution

  • 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