android cursor.getBlob not working

2020-04-26 05:27发布

Hi I tried to store and retrieve image to and from sqlite database. My following codes is not working. I'm not sure what wrong I did. Please help. I created the database table as follows:

db = openOrCreateDatabase("StudentDB", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS student(rollno VARCHAR,
 name VARCHAR,photo BLOB,marks VARCHAR);");

then I inserted the fields

db.execSQL("INSERT INTO student VALUES('" + editRollno.getText() + "','" + editName.getText() + "','" + imageInByte + "','" + editMarks.getText() + "');");

where imageInByte is a byte[] variable which was assigned before from gallery as follows:

ByteArrayOutputStream stream = new ByteArrayOutputStream();
            yourImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
            imageInByte = stream.toByteArray();

when I tried to retrieve an image from db it fails:

Cursor c = db.rawQuery("SELECT * FROM student WHERE rollno='"
                + editRollno.getText() + "'", null);
        if (c.moveToFirst()) {
            editName.setText(c.getString(1));
            editMarks.setText(c.getString(2));

            byte[] image = c.getBlob(3);
            ByteArrayInputStream imageStream = new ByteArrayInputStream(image);
            theImage = BitmapFactory.decodeStream(imageStream);     
            imageView2.setImageBitmap(theImage);

        }

1条回答
萌系小妹纸
2楼-- · 2020-04-26 05:33

You cannot simply treat byte arrays as text. (To use blobs with execSQL, you would have to use blob literals.)

To insert a row, use the insert method, which has support for byte arrays.

查看更多
登录 后发表回答