Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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..

like image 978
Hiren Dabhi Avatar asked Dec 03 '10 05:12

Hiren Dabhi


People also ask

Can we store image in SQLite Android?

Inorder to store images to android SQLite database, you need to convert the image uri to bitmap then to binary characters that is, bytes[] sequence. Then set the table column data type as BLOB data type. After retrieving the images from DB, convert the byte[] data type to bitmap in order to set it to imageview.

What is cursor in SQLite database?

Cursors are what contain the result set of a query made against a database in Android. The Cursor class has an API that allows an app to read (in a type-safe manner) the columns that were returned from the query as well as iterate over the rows of the result set.

How save and retrieve data from SQLite database in Android?

We can retrieve anything from database using an object of the Cursor class. We will call a method of this class called rawQuery and it will return a resultset with the cursor pointing to the table. We can move the cursor forward and retrieve the data. This method return the total number of columns of the table.


1 Answers

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);
like image 115
ACM64 Avatar answered Sep 24 '22 21:09

ACM64