我是安卓开发的新手。目前我在 inserting/retrieving
image to SQLite database
using android 时遇到问题。
//code for inserting image
InputStream in = OpenHttpConnection(imgurl);
byte[] bb = new byte[in.available()];
in.read(bb);//here the length of bb is 2040
//update query
myDataBase.execSQL("Update Product SET Image='"+bb+"' Where CatPID='"+pcpid+"'");
//function OpenHttpConnection
private InputStream OpenHttpConnection(String urlString) throws IOException
{
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}
catch (Exception ex)
{
throw new IOException("Error connecting");
}
return in;
}
//code for retrieve image from database
byte[] bb = cursor.getBlob(cursor.getColumnIndex("Image"));//here length is only 12
ByteArrayInputStream imageStream = new ByteArrayInputStream(bb);
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
img.setImageBitmap(theImage);
但是没有显示图片,日志显示“Factory returned null”
谁能帮我找出我错在哪里并提供有效解决方案的代码 fragment ?
提前致谢
最佳答案
你可以使用 decodeByteArray:
final byte[] image_byte = c.getBlob(0);
Bitmap image_bitmap = BitmapFactory.decodeByteArray(image_byte, 0, image_byte.length);
如果需要,可能还有 Bitmap.createScaledBitmap() 来重新缩放它。
关于android - 使用android在sqlite数据库中插入和检索图像数据的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4034700/