我正在使用 android studio - java 编写一个 Android 应用程序,当从图库中选取 10 多个图像并将它们插入到 Sqlitedatabase
表中时,我遇到了一个问题,当插入第 10 个图像时,需要花费很多时间比最后 9 张图像的时间更长,并且从表中选择所有图像 (10) 时,应用程序因错误而崩溃
E/SQLiteCursor: onMove() return false. RequiredPos: 9 WindowStartPos: 9 WindowRowCount: 0(original count of query: 10)
Caused by: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 10
代码
Picking and inserting images code
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode== 1 && resultCode == RESULT_OK) {
try {
ClipData clipData = data.getClipData();
if (clipData == null)
return;
for (int i = 0; i < clipData.getItemCount(); i++) {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), clipData.getItemAt(i).getUri());
byte[] myImg = getBitmapAsByteArray(bitmap);
DatabaseHelper databaseHelper = new DatabaseHelper(this);
SQLiteDatabase db = databaseHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("myImage",myImg);
db.insert("myTable",null,contentValues);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
getBitmapAsByteArray()
private static byte[] getBitmapAsByteArray(Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, outputStream);
return outputStream.toByteArray();
}
Selecting images from database
public void showImages(View view) {
DatabaseHelper databaseHelper = new DatabaseHelper(this);
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from myTable",null);
cursor.moveToFirst();
Toast.makeText(this, ""+cursor.getCount(), Toast.LENGTH_SHORT).show();
ArrayList<Bitmap> bitmaps = new ArrayList<>();
if (cursor.getCount()>0)
while (!cursor.isAfterLast())
{
bitmaps.add(BitmapFactory.decodeByteArray(cursor.getBlob(0), 0, cursor.getBlob(0).length));
cursor.moveToNext();
}
ViewPagerAdapter adapter = new ViewPagerAdapter(this,bitmaps);
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(0);
cursor.close();
}
有什么建议吗?
最佳答案
不确定代码,但我不会直接将图像存储在数据库中。图像可能非常巨大,写入和读取多个图像可能需要一些时间。
相反,就像后端开发人员所做的那样,我会将图像作为文件存储在文件系统上( app private directory )。当应用程序被删除时,它们也会被删除。将图像另存为文件并将其路径或名称存储到数据库中。因此,每当您需要图像时,只需执行以下操作:
-
List<String> getImageNamesFromDb()
-
List<File> getImageFiles(List<String>)
-
processYourImageFiles(List<File>)
关于java - 选择超过 10 张图像时应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53931301/