Media Gallery ContentProvider - android

My app will display the complete list of images in my custom gallery .For this, I'm using ContentProvider of Image Thumbnails. Upon selecting the thumbnail's I need to display the actual image.According to my understanding Gallery's image do have same unique ID in Thumb and Media Table.
Here is the code. Firstly I queried Thumbnail's ContentProvider and saved URL and ID.
String pictureThumbTemp[] = { MediaStore.Images.Thumbnails._ID, MediaStore.Images.Thumbnails.DATA };
Cursor imagecursor = context.getContentResolver().query (MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
pictureThumbTemp,null, null, null);
Later I am displaying thumbs in Grid.
Upon selection of thumbnail, I have to display original image. I'm trying to retrieve the original image like
String pictureImageTemp[] = { MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA };
Cursor imagecursor = context.getContentResolver().query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
pictureImageTemp, MediaStore.Images.Media._ID + " = " + mediaID + "", null,
MediaStore.Images.Media._ID);
Overall, I'm showing thumbnail through it's url and upon click I'm querying the thumbnail's media ID in Original image table.
But it is returning a cursor with 0 results.
Please help me out.
Thanks,
sha.

I cracked out a way which worked out.
Retrieved the cursor for Original Images.
From that I pulled the ID for every image and Queried the Thumbnails for the ID which returns a cursor containing paths.
Find the code snippet below.
String pictureCols[] = { MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA };
Cursor imagecursor = mContext.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, pictureCols,
null, null, null);
imagecursor.moveToFirst();
mImageUrls = new ArrayList<String>();
try {
// Iterate the cursor for Image urls
for (int index = 0; index < imagecursor.getCount(); index++) {
imagecursor.moveToPosition(index);
preparePicture(imagecursor);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
imagecursor.close();
}
}
Here is the code for preparePicture method
private void preparePicture(Cursor imageCursor) {
// get the ID for the original image
int idColumnIndex = imageCursor.getColumnIndex(mSelectedImage.mediaID);
Long id = imageCursor.getLong(idColumnIndex);
// Thumbnail image Cursor for this specific image.
String thumbCols[] = { MediaStore.Images.Thumbnails._ID, MediaStore.Images.Thumbnails.DATA };
Cursor thumbCursor = MediaStore.Images.Thumbnails.queryMiniThumbnail(mContext.getContentResolver(), id,
Thumbnails.MINI_KIND, thumbCols);
thumbCursor.moveToFirst();
// Save thumbnail URL in MediaInfo
dataColumnIndex = thumbCursor.getColumnIndex(mSelectedThumb.data);
String thumbURL = thumbCursor.getString(dataColumnIndex);
thumbCursor.close();
mImageUrls.add(url);
}
Finally, I will have all my Thumbnail urls in the ArrayList.
The same logic is not working for video thumbnails. Of course that is a different question :)
Regards,
Sha.

try this one
final String[] pictureImageTemp= { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
Cursor imagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, pictureImageTemp, null,
null, MediaStore.Images.Media._ID);

Related

How share images/videos in custom folders using ContentResolver/ or other way in Android ? Getting FileUriExposedException Exception

I have a custom folder in the Pictures directory, like this Pictures/MyFolder. It has images in MyFolder. Here is how to share the images using ContentResolver on MyFolder only. Or is any alternative ways to share the image. It is on android 11.
I queried images using the following snippets
String[] projection = new String[]{
MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
MediaStore.Images.Media.DATE_TAKEN};
Uri images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
Cursor cur = context.getContentResolver().query(images,
projection, // Which
// columns
// to return
null, // Which rows to return (all rows)
null, // Selection arguments (none)
orderBy + " DESC" // Ordering
);
int bucketColumn = cur.getColumnIndex(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
int dateColumn = cur.getColumnIndex(MediaStore.Images.Media.DATE_TAKEN);
do {
bucket = cur.getString(bucketColumn);
if (bucket.equals(context.getString(R.string.app_name))) {
date = cur.getString(dateColumn);
imagePath = listImageByFolder.get(bucket);
if (imagePath == null) {
imagePath = new ArrayList<String>();
}
imagePath.add(cur.getString(cur.getColumnIndex(MediaStore.Images.Media.DATA)));
Uri x = Uri.withAppendedPath(MediaStore.Images.Media.INTERNAL_CONTENT_URI, String.valueOf(cur.getString(cur.getColumnIndex(MediaStore.Images.Media.DATA))));
listImageByFolder.put(bucket, imagePath);
} ;
} while (cur.moveToNext());
While I try to share the image, Getting android.os.FileUriExposedException: file:///storage/emulated/0/Pictures/WhatsTouch/1628090801008.jpg exposed beyond app through ClipData.Item.getUri() exception. Is any way to correct it or is any alternative way?

import gallery images which are stored in phone/memory card into recyclerview

I am trying to populate recyclerview from gallery images as instagram imports gallery images while you select images from the list to upload. I want to implement similar type of thing. Any suggestions on how to access the gallery images on phone/memory card and populate the recyclerview. Also please do suggest any way to implement instagram like interface for selecting images to upload.
you can use Android media store to pick pictures,Videos and Audios
example code for images:
private void imageMediaQuery() {
String[] projection = new String[]{
MediaStore.MediaColumns.DATA,
//MediaStore.Images.Media._ID,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
MediaStore.Images.Media.DATE_TAKEN
};
Uri images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String BUCKET_GROUP_BY =
"1) GROUP BY 1,(1";
String BUCKET_ORDER_BY = MediaStore.Images.Media.DATE_TAKEN + " DESC";
Cursor cur = this.getContentResolver().query(images,
projection, // Which columns to return
BUCKET_GROUP_BY, // Which rows to return (all rows)
null, // Selection arguments (none)
BUCKET_ORDER_BY // Ordering
);
if(cur!=null){
Log.i("ListingImages", " query count=" + cur.getCount());
}
if (cur!=null&&cur.moveToFirst()) {
String bucket;
String path;
int bucketColumn = cur.getColumnIndex(
MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
int pathColumn = cur.getColumnIndex(
MediaStore.MediaColumns.DATA);
do {
bucket = cur.getString(bucketColumn);
path = cur.getString(pathColumn);
} while (cur.moveToNext());
cur.close();
}
}
In the above code you get path for each image and simply use that path in your onBindViewHolder of recyclerview adapter to display images.hope this helps.

How to load images from the phone taken in last hour?

I want to load and display all images that are taken by my phone in last hour. I am using Content Resolver query with some parameters to get images list. I can use this to display just last 10 images:
String sortOrder = String.format("%s limit 50 ", MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC");
And that is working with code from below, but I want to modify my cursor query to just display images taken in last hour.
Here is the code:
String orderBy = MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC LIMIT 10";
//Current time in millis and hour ago
int now = Calendar.getInstance().get(Calendar.MILLISECOND);
long hourAgo = now - 60*60000;
String[] columns = new String[]{
MediaStore.Images.Media._ID, // get the image
};
ContentResolver contentResolver = getContentResolver();
// Set up an array of the Thumbnail Image ID column we want
String[] projection = {MediaStore.Images.Thumbnails._ID};
// Create the cursor pointing to the SDCard
cursor = contentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
columns, // Which columns to return
null, // Return all rows
null,
orderBy);
// Get the column index of the Thumbnails Image ID
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
How I can only get list of images taken in last hour?
I tried to write this also, but it does not work:
final String[] selectionArgs = { MediaStore.Images.ImageColumns.DATE_TAKEN + "<"+ Long.toString(hourAgo) };
cursor = contentResolver.query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
cols, // Which columns to return
null, // Return all rows
selectionArgs ,
orderBy);

How to make sort gallery thumbnails image by date

I am developing an android applicaiton. This application get all thumbnail images from gallery. I want to sort these thumbnails by date, but I can't do it.
Please help me.
Get all images
// Set up an array of the Thumbnail Image ID column we want
String[] columns = {MediaStore.Images.Media._ID};
String orderBy = MediaStore.Images.Thumbnails._ID + " DESC LIMIT 10";
// Create the cursor pointing to the SDCard
cursor = getActivity().managedQuery(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
columns, // Which columns to return
null, // Return all rows
null,
orderBy);
// Get the column index of the Thumbnails Image ID
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
myGalleryImages = (GridView) view.findViewById(R.id.my_gallery);
myGalleryImages.setAdapter(new ImageAdapter(getActivity()));
set images
// Move cursor to current position
cursor.moveToPosition(position);
// Get the current value for the requested column
int imageID = cursor.getInt(columnIndex);
// Set the content of the image based on the provided URI
holder.image.setImageURI(Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID));
Update columns and orderBy like this:
String[] columns = {MediaStore.Images.Media._ID, MediaStore.Images.ImageColumns.DATE_TAKEN};
String orderBy = MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC";
and see if that helps.
You could also fetch real images instead of thumbnails and use image loading library that will take care of proper re-sizing. In this case replace your Thumbnails references with ImageColumns
this code will save the first 100 thumbs (SORTED by date)
Cursor cursor = this.getContentResolver().query( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
projection, // Which columns to return
null, // Return all rows
null,
"image_id DESC");
// Get the column index of the Thumbnails Image ID
int columnIndex = cursor.getColumnIndex(MediaStore.Images.Thumbnails.DATA);
for(int i =0;i<cursor.getCount();i++){
if (i==100) break;
cursor.moveToPosition(i);
mImagesFromGallery[i] = cursor.getString(columnIndex);
}
cursor.close();

How to get imagepath from thumbnail path of a image?

I am trying to get imagepath based on thumbail path , i have already tried solution from
android-getting-path-to-image-from-thumbnail, but it is based on gridview position, i am only retrieving specific images. Also i found one sample code from SO, the code is
private String getImagePathFromThumbPath(String thumbPath)
{
String imgPath=null;
// String[] projection = new String[] {MediaStore.Images.Thumbnails._ID, MediaStore.Images.Thumbnails.IMAGE_ID};
String[] imagesDataPath={ MediaStore.Images.Media.DATA ,MediaStore.Images.Media._ID};
//mResolver.query() requires android API 16
Cursor thumbnails = mResolver.query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, imagesDataPath,MediaStore.Images.Thumbnails.DATA+"=?",new String[]{thumbPath}, null, null);
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor imageCursor = mResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, filePathColumn, MediaStore.Images.Media._ID + "=?", new String[] {thumbId}, null);
if (imageCursor != null && imageCursor.moveToFirst()) {
// Your file-path will be here
imgPath= imageCursor.getString(imageCursor.getColumnIndex(filePathColumn[0]));
}
return imgPath;
}
The above method is bit modified to suit my needs and it returns nothing on Toasting, please tell how to retrieve imagepath using thumbnail path?
After a long time and relentless try, the solution is here
1. You need to find the image id which is image unique id from images table in thumbnail table, query to thumbnail provider (MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI) if you do not understand it, refer here , specifically IMAGE_ID,
Step 1 is to get retrievedImageId.
retrievedImageId = Long.parseLong(cursor.getString(imageIdInImages));
2. Now using the retrievedImageId get the image path, by again querying the content provider, only this time query the Images media provider (MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
String getImagePathFromThumbPath(String thumbPath)
{
String imagePath = null;
if(thumbPath != null )
{
String[] columns_to_return = {MediaStore.Images.Thumbnails.IMAGE_ID};
String where = MediaStore.Images.Thumbnails.DATA+" LIKE ?";
long retrievedImageId = -1;
String valuesAre[] = {"%"+thumbPath};
Cursor cursor = getContentResolver().query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, columns_to_return, where, valuesAre, null);
if(cursor != null)
{
int imageIdInImages = cursor.getColumnIndex(MediaStore.Images.Thumbnails.IMAGE_ID);
for (cursor.moveToFirst();!cursor.isAfterLast(); cursor.moveToNext())
{
//STEP 1 to retrieve image ID
retrievedImageId = Long.parseLong(cursor.getString(imageIdInImages));
}
if(retrievedImageId != -1)
{
// STEP 2 Now
Log.i(TAG, "imageId-" + retrievedImageId);
String[] columnsReturn = {MediaStore.Images.Media.DATA};
String whereimageId = MediaStore.Images.Media._ID+" LIKE ?";
String valuesIs[] = {"%" + retrievedImageId};
Cursor mCursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columnsReturn, whereimageId, valuesIs, null);
int rawDataPath= mCursor.getColumnIndex(MediaStore.Images.Media.DATA);
for (mCursor.moveToFirst();!mCursor.isAfterLast(); mCursor.moveToNext())
{
imagePath = mCursor.getString(rawDataPath);
}
}
}
}
return imagePath;
}
If you still have doubt or error/exception, leave comment!

Categories

Resources