好的,在多次尝试后,我终于有了一个可行的示例,并且我想分享它。我的示例查询图像MediaStore,然后获取每个图像的缩略图以在视图中显示。我将我的图像加载到一个Gallery对象中,但这并不是此代码工作的要求:
确保您在类级别上定义了Cursor和int列索引,以便Gallery的ImageAdapter可以访问它们:
private Cursor cursor;
private int columnIndex;
首先,获取位于文件夹中的图像ID的光标:
Gallery g = (Gallery) findViewById(R.id.gallery);
String[] projection = {MediaStore.Images.Media._ID};
cursor = managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection,
MediaStore.Images.Media.DATA + " like ? ",
new String[] {"%myimagesfolder%"},
null);
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
g.setAdapter(new ImageAdapter(this));
然后,在Gallery的ImageAdapter中获取要显示的缩略图:
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(context);
cursor.moveToPosition(position);
int imageID = cursor.getInt(columnIndex);
Uri uri = Uri.withAppendedPath( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, Integer.toString(imageID) );
String url = uri.toString();
int originalImageId = Integer.parseInt(url.substring(url.lastIndexOf("/") + 1, url.length()));
Bitmap b = MediaStore.Images.Thumbnails.getThumbnail(getContentResolver(),
originalImageId, MediaStore.Images.Thumbnails.MINI_KIND, null);
i.setImageBitmap(b);
i.setLayoutParams(new Gallery.LayoutParams(150, 100));
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setBackgroundResource(mGalleryItemBackground);
return i;
}
我猜这段代码最重要的部分是managedQuery,它演示了如何使用MediaStore查询来过滤特定文件夹中的图像文件列表。
columnIndex
是0,而且cursor
不为空。这看起来有些不对劲,你知道为什么吗?请告诉我。谢谢。 - Huy TowerimageID
为空。android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
。 - Huy Tower