android cursor.getBlob not working

大兔子大兔子 提交于 2019-12-20 04:34:30

问题


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:


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.



来源:https://stackoverflow.com/questions/28811674/android-cursor-getblob-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!