我想从图库中获取图片(如果存在),而无需用户从图库中选择图片。我想以编程方式执行此操作。我尝试了以下方法:
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = new Activity().managedQuery( MediaStore.Images.Media.INTERNAL_CONTENT_URI, projection, null, null, null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
BitmapFactory.Options options = new BitmapFactory.Options();;
options.inSampleSize = 1;
Bitmap bm = BitmapFactory.decodeFile(
cursor.getString(column_index),options);
remoteView.setImageViewBitmap(R.id.image,bm);
我从工作线程而不是主UI线程调用这段代码。这种方法是否正确?如果没有,那么在没有用户互动的情况下从画廊获取图像的更好方法是什么?
感谢。
答案 0 :(得分:1)
我认为这个问题有两个部分:从手机图库中获取图像并更新用户界面。
似乎您的方法对于从图库中获取图像是正确的。另一种方法详述如下:http://developer.android.com/guide/topics/data/data-storage.html#filesExternal。
您看到的RuntimeException是因为您正在尝试更新工作线程上的UI。 Android框架要求在UI线程上进行所有UI更改。运行查询后,您必须调用Activity.runOnUiThread()
来更新UI。