Hiren Dabhi
Hiren Dabhi

Reputation: 3713

Displaying image from the sqlite database using cursor in android

i want to display image in imageview from sqlite database using cursor. i used below code to retrieve image but i am not able to display image in imageview.

Cursor c=this.db.query(TABLE_NAME, new String[] { "name","price","image" },
                null, null, null, null, null);
name.setText(c.getString(0));
price.setText(c.getString(1));
byte b[]=c.getBlob(2);
Bitmap bp=BitmapFactory.decodeByteArray(b, 0, b.length);
ImageView image=(ImageView)findViewById(R.id.ImageView);
//ByteArrayInputStream imageStream = new ByteArrayInputStream(b);               
//Bitmap theImage = BitmapFactory.decodeStream(imageStream);
//image.setImageBitmap(theImage);               
image.setImageBitmap(bp); 

other than image, name and price will display but image will not display. any suggestion or code that will help me to solve this problem.

Please help me.

Thanks in advance..

Upvotes: 14

Views: 24676

Answers (3)

Sameer Zinzuwadia
Sameer Zinzuwadia

Reputation: 3285

First of all please did not store the images in database because sqlite will not support more then 1 mb,i may be wrong, images should be store in assets or drawble folder and the name of images should be store in database then you can get it from name to resource conversion by code

 String videoFileName= c.getString(c.getColumnIndex(TB_SETTING_VIDEOFILENAME));
        int dot = videoFileName.lastIndexOf(".");
        videoFileName=videoFileName.substring(0,dot);
        Log.d("VIDEOFILENAME", videoFileName);

        int videoFileRId = getResources().getIdentifier(videoFileName , "raw", getPackageName());   

I hope this will help you.

Upvotes: 2

Niranj Patel
Niranj Patel

Reputation: 33238

try this cursor object; // your cursor

   mImageView.setImageBitmap(getImageFromBLOB(object.getBlob(object.getColumnIndex("book_thumb"))));

    public static Bitmap getImageFromBLOB(byte[] mBlob)
    {
        byte[] bb = mBlob;
        return BitmapFactory.decodeByteArray(bb, 0, bb.length);
    }

Upvotes: 1

acm0x
acm0x

Reputation: 775

I've tried to use Stream instead of byte array, mine example simply works for me. Also try to use Cursor.getColumnIndex()

    byte[] blob = c.getBlob(c.getColumnIndex(YourDB.IMAGE));
    ByteArrayInputStream inputStream = new ByteArrayInputStream(blob);
    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

Here's my "create table" statement, pls double check yours

    create table datatable(_id INTEGER PRIMARY KEY AUTOINCREMENT, image BLOB, price INTEGER);

Upvotes: 19

Related Questions