Search code examples
androidimagebitmapcrop

Large BLOB getting from SQLiteDatabase in android


Here, I am currently working in a project which is include Image getting from Gallery or Camera & Crop this image after store in database. It's work perfectly. But When image size is large then it's store in database perfectly but when getting this image from database it's give s error.

java.lang.IllegalStateException: Couldn't read row 0, col 0 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it. 

Convert Bitmap to byte Array

public byte[] bitmpToByte(Bitmap bmp)
 {
     ByteArrayOutputStream stream = new ByteArrayOutputStream();
     bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
     byte[] imgarray = stream.toByteArray();
     return  imgarray;
 }

Store this byte array in database.

values.put("blob_image", imgArray); // byte[] imgArray;

Getting from database & convert to bitmap & display.

    Record helper = new Record getActivity());
    Database database = helper.getReadableDatabase();

    Cursor cursor = database.query(Const.TABLE_NAME1, null, null, null, null, null, null);

    if(cursor.getCount() > 0 && cursor != null) {

        cursor.moveToFirst();

        id = String.valueOf(cursor.getString(0));
        com_name.setText(cursor.getString(1));
        byte[] imgArray= cursor.getBlob(2);
        Bitmap bitmap = BitmapFactory.decodeByteArray(imgArray , 0, imgArray.length);
        displayImage.setImageBitmap(bitmap);
    }

    try {
        cursor.close();
        helper.close();
    } catch (Exception e) {
        // TODO: handle exception
    }

So, How to store & retrieve large size image from database?


Solution

  • You need to check cursor.moveToFirst() then only you access the Cursor Data.like

     Cursor cursor = database.query(Const.TABLE_NAME1, null, null, null, null, null, null);
    
    do{
      if(cursor.moveToFirst()) {
    
      //Do your job
    
     }
    }while(cursor.moveToNext());
    
     cursor.close();