I have a custom folder in the Pictures directory, like thisPictures/MyFolder. It has images in MyFolder. Here is how to query the images using ContentResolver on MyFolder folder only.
I tried this
Cursor mediaCursor = context.getContentResolver().query(
MediaStore.Files.getContentUri("external"),
null,
MediaStore.MediaColumns.RELATIVE_PATH + " like ? ",
new String[]{"%MyFolder%"},
null);
But it contains other files also. Or is any alternate to content resolver?
You can use the below function to get the images from the folder.
private void getImageFolderList() {
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 = getContentResolver().query(images, projection, // Which
// columns
// to return
null, // Which rows to return (all rows)
null, // Selection arguments (none)
orderBy + " DESC" // Ordering
);
ArrayList<String> imagePath;
if (cur.moveToFirst()) {
String bucket, date;
int bucketColumn = cur.getColumnIndex(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
int dateColumn = cur.getColumnIndex(MediaStore.Images.Media.DATE_TAKEN);
do {
bucket = cur.getString(bucketColumn);
date = cur.getString(dateColumn);
if (!allFolder.contains(bucket)) {
allFolder.add(bucket);
}
imagePath = listImageByFolder.get(bucket);
if (imagePath == null) {
imagePath = new ArrayList<String>();
}
imagePath.add(cur.getString(cur
.getColumnIndex(MediaStore.Images.Media.DATA)));
listImageByFolder.put(bucket, imagePath);
} while (cur.moveToNext());
}
}
Related
I would like to replace function below because DATA is deprecated
It's necessary to list only path in the base directory
If I using "MediaStore.Files.FileColumns._ID", I can return Uri Lists, but I lost external storage path
The goal is to open the PDF viewer on a PDF file that is in "Documents" (in external storage)
Can you help me please?
public static Vector<String> getFilesListInExternalStorage(Context context, String mimeType, String baseDirectory) {
Vector<String> list = new Vector<>();
Uri collection;
String selection = "";
String[] selectionArgs = {""};
final String[] projection = new String[]{
MediaStore.Files.FileColumns.DISPLAY_NAME,
MediaStore.Files.FileColumns.DATE_ADDED,
MediaStore.Files.FileColumns.DATA,
MediaStore.Files.FileColumns.MIME_TYPE,
};
final String sortOrder = MediaStore.Files.FileColumns.DATE_ADDED + " DESC";
if(baseDirectory==null || baseDirectory.isEmpty())
{
selection = MediaStore.Files.FileColumns.MIME_TYPE + " = ?";
selectionArgs = new String[]{mimeType};
}
else
{
selection = MediaStore.Files.FileColumns.MIME_TYPE + " = ? AND "+ MediaStore.Files.FileColumns.DATA + " like ? ";
selectionArgs = new String[]{mimeType, "%"+baseDirectory+"%"};
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
collection = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL);
}else{
collection = MediaStore.Files.getContentUri("external");
}
try (Cursor cursor = Objects.requireNonNull(context).getContentResolver().query(collection, projection, selection, selectionArgs, sortOrder)) {
assert cursor != null;
if (cursor.moveToFirst()) {
int columnData = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);
do {
list.add((cursor.getString(columnData)));
} while (cursor.moveToNext());
}
}
return list;
}
Thank you very much
Have a nice day
Loïc
try (Cursor cursor = context.getContentResolver().query(collection, Constants.FILE_PROJECTION, sb.toString(), strArr2, sort)) {
if (cursor.moveToFirst()) {
int columnData = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);
do {
String path = cursor.getString(columnData);
File file = new File(path);
if (file.exists()) {
fileList.add(new File(cursor.getString(columnData)));
}
} while (cursor.moveToNext());
cursor.close();
}
}
return fileList;
try this
I had many query and it was taking lot of time to fetch contact data.
So need to convert all query in into one.
I got all other info like display name, mobile number, label, email in one query
but finding prob only with getting pics
Help me to Convert below photo query into single query and get uri of pics :
ContentResolver KntRslverVar = getContentResolver();
Cursor ContctKsrVar = KntRslverVar.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[] {
ContactsContract.CommonDataKinds.Phone._ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER},
null, null, null);
while (ContctKsrVar.moveToNext())
{
String ContctUidVar = ContctKsrVar.getString(ContctKsrVar.getColumnIndex(ContactsContract.Contacts._ID));
String ContctNamVar = ContctKsrVar.getString(ContctKsrVar.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String ContctMobVar = ContctKsrVar.getString(ContctKsrVar.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Cursor ContctPflPicKsrVar = KntRslverVar.query(
ContactsContract.Data.CONTENT_URI,
null,
ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?",
new String[]{ContctUidVar, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE},
null);
if (ContctPflPicKsrVar != null && ContctPflPicKsrVar.getCount() > 0)
{
while(ContctPflPicKsrVar.moveToNext())
{
Uri ContctPflPicUriVar = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(ContctUidVar));
PflPicUriVar = Uri.withAppendedPath(ContctPflPicUriVar, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
}
ContctPflPicKsrVar.close();
}
}
Try 1 :
Cursor ContctKsrVar = KntRslverVar.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[] {
ContactsContract.CommonDataKinds.Phone._ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE},
null, null, null);
Try 2 :
Cursor ContctKsrVar = KntRslverVar.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[] {
ContactsContract.CommonDataKinds.Phone._ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER
ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI},
null, null, null);
Also need help on getting uri from fetched query :
Uri KctPflPicUriVar = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(KctUidVar));
PflPicUriVar = Uri.withAppendedPath(KctPflPicUriVar, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
|*| Optimised : Get Display Name and Number with label and Photo Thumbnail in one query : Gets result query in less than 4 sec.
ContentResolver contntRslverVar = getContentResolver();
Cursor contctKsrVar = contntRslverVar.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[] {
ContactsContract.CommonDataKinds.Phone._ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.LABEL,
ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI},
null, null, null);
while (contctKsrVar.moveToNext())
{
String contctUidVar = contctKsrVar.getString(contctKsrVar.getColumnIndex(ContactsContract.Contacts._ID));
String contctNamVar = contctKsrVar.getString(contctKsrVar.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String contctMobVar = contctKsrVar.getString(contctKsrVar.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
int MobLblTypVar = contctKsrVar.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
int MobLblTipVar = contctKsrVar.getColumnIndex(ContactsContract.CommonDataKinds.Phone.LABEL);
MobLblTypVar = contctKsrVar.getInt(MobLblTypVar);
String contctMobLblVar;
if(MobLblTypVar == ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM)
{
contctMobLblVar = contctKsrVar.getString(MobLblTipVar);
}
else
{
CharSequence MobLblSrgVar = ContactsContract.CommonDataKinds.Phone.getTypeLabel(getResources(), MobLblTypVar, "Mobile");
contctMobLblVar = MobLblSrgVar.toString();
}
String PflPicSrgVar = contctKsrVar.getString(contctKsrVar.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI));
if(PflPicSrgVar != null) Uri PflPicUriVar = Uri.parse(PflPicSrgVar);
}
I'm saving an image loaded with Picasso to be shared afterwards. This is the code I'm using to save it:
String path = MediaStore.Images.Media.insertImage(
mContext.getContentResolver(), mImageBitmap, "Shared image", null);
return Uri.parse(path);
Now, when the image has been shared, I have to delete it using the URI. I've tried some answers I've seen here but none of them has worked. The image still appears in the gallery. These are the methods I have used:
// Set up the projection (we only need the ID)
String[] projection = { MediaStore.Images.Media._ID };
// Match on the file path
String selection = MediaStore.Images.Media.DATA + " = ?";
String[] selectionArgs = new String[] { new File(mImageUri.toString()).getAbsolutePath() };
// Query for the ID of the media matching the file path
Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
ContentResolver contentResolver = getContentResolver();
Cursor c = contentResolver.query(queryUri, projection, selection, selectionArgs, null);
if (c.moveToFirst())
{
// We found the ID. Deleting the item via the content provider will also remove the file
long id = c.getLong(c.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
Uri deleteUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
contentResolver.delete(deleteUri, null, null);
}
c.close();
File file = new File(mImageUri.toString());
// This returns false
file.delete();
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(mImageUri.toString()))));
Any idea of what i've done wrong?
Thanks,
Try this for deletion
String[] retCol = { MediaStore.Audio.Media._ID };
Cursor cur = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
retCol,
MediaStore.Images.Media.TITLE + "='"+TEMP_FILE_TITLE+"'", null, null
);
try {
if (cur.getCount() == 0) {
return;
}
cur.moveToFirst();
int id = cur.getInt(cur.getColumnIndex(MediaStore.MediaColumns._ID));
Uri uri = ContentUris.withAppendedId(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id
);
int cnt = context.getContentResolver().delete(uri, null, null);
}finally {
cur.close();
}
In your case replace TEMP_FILE_TITLE = "Shared image"
I can use the following code to query Media._ID, Media.BUCKET_DISPLAY_NAME and DATE_TAKEN of every photo,
but I only hope to get MediaStore.Images.Media.BUCKET_DISPLAY_NAME, how can I do ? Thanks!
// which image properties are we querying
String[] projection = new String[]{
MediaStore.Images.Media._ID,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
MediaStore.Images.Media.DATE_TAKEN
};
// Get the base URI for the People table in the Contacts content provider.
Uri images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
// Make the query.
Cursor cur = managedQuery(images,
projection, // Which columns to return
"", // Which rows to return (all rows)
null, // Selection arguments (none)
"" // Ordering
);
Log.i("ListingImages"," query count="+cur.getCount());
if (cur.moveToFirst()) {
String bucket;
String date;
int bucketColumn = cur.getColumnIndex(
MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
int dateColumn = cur.getColumnIndex(
MediaStore.Images.Media.DATE_TAKEN);
do {
// Get the field values
bucket = cur.getString(bucketColumn);
date = cur.getString(dateColumn);
// Do something with the values.
Log.i("ListingImages", " bucket=" + bucket
+ " date_taken=" + date);
} while (cur.moveToNext());
}
String[] projection = new String[]{
MediaStore.Images.Media.BUCKET_DISPLAY_NAME
};
instead of
String[] projection = new String[]{
MediaStore.Images.Media._ID,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
MediaStore.Images.Media.DATE_TAKEN
};
???
The playlist names can be found by a query on MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI
and then look at the MediaStore.Audio.PlaylistsColumns.NAME column.
There is a data column too, MediaStore.Audio.PlaylistsColumns._DATA, but it is returning null.
The list of songs (MediaStore.Audio.Media.EXTERNAL_CONTENT_URI/id) do not seem to show any playlist affiliation.
Here is a bit from my program:
The gist is that you need the id for the playlist to grab the songs.
Basically you can take my code and change the where statement to .NAME +" = '"+name+"'",
private Cursor getPlaylists(String playlistId){
Cursor cursor = null;
String[] projection1 = {
MediaStore.Audio.Playlists._ID,
MediaStore.Audio.Playlists.NAME
};
cursor = this.managedQuery(
MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
projection1,
MediaStore.Audio.Playlists._ID+ " = "+playlistId+"",
null,
null);
startManagingCursor(cursor);
cursor.moveToFirst();
playlist_id = cursor.getString(0);
playlist_id2 = cursor.getLong(0);
if(playlist_id2 > 0){
String[] projection = {
MediaStore.Audio.Playlists.Members.AUDIO_ID,
MediaStore.Audio.Playlists.Members.ARTIST,
MediaStore.Audio.Playlists.Members.TITLE,
MediaStore.Audio.Playlists.Members._ID
};
cursor = null;
cursor = this.managedQuery(
MediaStore.Audio.Playlists.Members.getContentUri("external",playlist_id2 ),
projection,
MediaStore.Audio.Media.IS_MUSIC +" != 0 ",
null,
null);
}
cManager(cursor,2,1);
return cursor;
}
Here is a working way to get tracks from a play list. Basically it loops the cursor through all the of the playlist query, and each time it gets the id of a member (track) and using that id of the track we can get other data such as path, artist, duration, album etc.
ContentResolver contentResolver = getContentResolver();
Uri playListUri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistID); //playlistID is the _ID of the given playlist
MediaMetadataRetriever mr = new MediaMetadataRetriever();
Cursor cursor = contentResolver.query(playListUri, null, null, null, null);
if(cursor != null)
{
if(cursor.moveToNext()) {
do {
String track_id = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Playlists.Members.AUDIO_ID));
Uri mediaContentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String[] trackProjection = new String[]{MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.DATA};
String selection = MediaStore.Audio.Media._ID + "=?";
String[] selectionArgs = new String[]{"" + track_id};
Cursor mediaCursor = contentResolver.query(mediaContentUri, trackProjection, selection, selectionArgs, null);
if (mediaCursor != null) {
if (mediaCursor.getCount() >= 0) {
mediaCursor.moveToPosition(0);
String song_title = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
String song_artist = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
String song_album = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
String song_path = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.Audio.Media.DATA));
}
}
} while (cursor.moveToNext());
}
}
this is the way to get all playlist from the device
public ArrayList<String> getPlayList() {
ArrayList<String> arrayList=new ArrayList<String>();
String[] proj = {"*"};
Uri tempPlaylistURI = MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI;
// In the next line 'this' points to current Activity.
// If you want to use the same code in other java file then activity,
// then use an instance of any activity in place of 'this'.
Cursor playListCursor= activity.managedQuery(tempPlaylistURI, proj, null,null,null);
if(playListCursor == null){
System.out.println("Not having any Playlist on phone --------------");
return arrayList;//don't have list on phone
}
System.gc();
String playListName = null;
System.out.println(">>>>>>> CREATING AND DISPLAYING LIST OF ALL CREATED PLAYLIST <<<<<<");
for(int i = 0; i <playListCursor.getCount() ; i++)
{
playListCursor.moveToPosition(i);
playListName = playListCursor.getString(playListCursor.getColumnIndex("name"));
System.out.println("> " + i + " : " + playListName );
arrayList.add(playListName);
}
if(playListCursor != null)
playListCursor.close();
return arrayList;
}