I want to fetch a picture, if present, from the gallery without having user to select picture from the gallery. I want to do this programmatically. I have tried following approach:
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);
I'am calling this piece of code from a worker thread and not main UI thread. Is this approach correct? if not then what can be a better approach to get an image from gallery without user interaction?
Thanks.
I think that there are two parts to this question: getting the image from the phone gallery and updating the UI.
It seems that your method is correct for getting the images from the gallery. Another method is detailed here: http://developer.android.com/guide/topics/data/data-storage.html#filesExternal.
The RuntimeException you're seeing is because you're trying to update the UI on a worker thread. The Android framework requires all UI changes happen on the UI thread. You'll have to call Activity.runOnUiThread()
after running the query to update the UI.