android cursor.getBlob无法正常工作 [英] android cursor.getBlob not working
问题描述
我试图在sqlite数据库中存储图像并从中检索图像.我的以下代码无法正常工作.我不确定我做错了什么.请帮忙. 我创建了数据库表,如下所示:
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);");
然后我插入字段
db.execSQL("INSERT INTO student VALUES('"
+ editRollno.getText() + "','"
+ editName.getText() + "','"
+ imageInByte + "','"
+ editMarks.getText()
+ "');");
db.execSQL("INSERT INTO student VALUES('"
+ editRollno.getText() + "','"
+ editName.getText() + "','"
+ imageInByte + "','"
+ editMarks.getText()
+ "');");
其中imageInByte是一个byte []变量,它是从画廊之前分配的,如下所示:
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);
}
推荐答案
您不能简单地将字节数组视为文本. (要将blob与execSQL一起使用,则必须使用blob文字.)
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.
这篇关于android cursor.getBlob无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!