我创建了一个简单的应用程序,其中图像存储从ImageView到数据库。 但是当点击retrive按钮时,显示索引1请求大小为3。 我不知道出了什么问题。 数据库类:
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_IMAGE_TABLE = "CREATE TABLE " +TABLE_NAME + "("
+ IMAGE_KEY + " BLOB )";
db.execSQL(CREATE_IMAGE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(byte[]image )throws SQLiteException
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(IMAGE_KEY,image);
long result= db.insert(TABLE_NAME,null,cv);
if(result==-1)
return false;
else
return true;
}
public Cursor getAllData()
{
SQLiteDatabase db=this.getReadableDatabase();
Cursor res=db.rawQuery("select * from "+TABLE_NAME,null);
byte[]img=res.getBlob(0);
return res;
}
这是活动类:
public void button2(View view)
{
try {
Cursor res = myDb.getAllData();
if (res ==null) {
showMessage("error", "no data found");
} else {
StringBuffer buffer = new StringBuffer();
while (res.moveToNext()) {
buffer.append("id:" + res.getBlob(0) + "\n");
byte[] image = res.getBlob(0);
Bitmap bmp = BitmapFactory.decodeByteArray(image, 0,
image.length);
imagee.setImageBitmap(bmp);
}
// showMessage("DATA", buffer.toString());
}
}
catch (Exception e)
{
Toast.makeText(getBaseContext(),e.getMessage(),
Toast.LENGTH_LONG).show();
}}
public void buttonn(View view)
{
Bitmap bitmap = ((BitmapDrawable) imagee.getDrawable()).getBitmap();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, outputStream);
byte[] data = outputStream.toByteArray();
boolean isInserted = myDb.insertData(data);
if (isInserted == true)
Toast.makeText(getBaseContext(), "Registration Succes!",
Toast.LENGTH_SHORT).show();
else
Toast.makeText(getBaseContext(), "No Record Registered!",
Toast.LENGTH_SHORT).show();
}
}
我尝试了最多但不能做的事情。我从res.movetoNext更改它但显示相同的错误并使用res.movetoFirst它也显示相同的错误
答案 0 :(得分:2)
Android sqlite CursorWindow
在大多数配置中都有一个固定大小的缓冲区,大小为2MB。你不能移动任何大于那的行。
不要在Android sqlite中存储大型二进制数据,如图像。请改用外部存储,只需在数据库中保存路径即可。
答案 1 :(得分:0)
检查此代码,了解如何在android中保存图像:
private String saveToInternalStorage(Bitmap bitmapImage){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,"profile.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
fos.close();
}
return directory.getAbsolutePath();
}
您只需将图像的路径添加到数据库中,而不是blob图像。
参考:Saving and Reading Bitmaps/Images from Internal memory in Android