android.provider.MediaStore.Images Java Examples

The following examples show how to use android.provider.MediaStore.Images. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BucketHelper.java    From medialibrary with Apache License 2.0 6 votes vote down vote up
private static BucketEntry[] loadBucketEntriesFromImagesAndVideoTable(
        ThreadPool.JobContext jc, ContentResolver resolver, int type) {
    HashMap<Integer, BucketEntry> buckets = new HashMap<Integer, BucketEntry>(64);
    if ((type & MediaObject.MEDIA_TYPE_IMAGE) != 0) {
        updateBucketEntriesFromTable(
                jc, resolver, Images.Media.EXTERNAL_CONTENT_URI, buckets);
    }
    if ((type & MediaObject.MEDIA_TYPE_VIDEO) != 0) {
        updateBucketEntriesFromTable(
                jc, resolver, Video.Media.EXTERNAL_CONTENT_URI, buckets);
    }
    BucketEntry[] entries = buckets.values().toArray(new BucketEntry[buckets.size()]);
    Arrays.sort(entries, new Comparator<BucketEntry>() {
        @Override
        public int compare(BucketEntry a, BucketEntry b) {
            // sorted by dateTaken in descending order
            return b.dateTaken - a.dateTaken;
        }
    });
    return entries;
}
 
Example #2
Source File: ImageTask.java    From boxing with Apache License 2.0 6 votes vote down vote up
private List<ImageMedia> buildAlbumList(ContentResolver cr, String bucketId, int page,
                                        @NonNull final IMediaTaskCallback<ImageMedia> callback) {
    List<ImageMedia> result = new ArrayList<>();
    String columns[] = getColumns();
    Cursor cursor = null;
    try {
        boolean isDefaultAlbum = TextUtils.isEmpty(bucketId);
        boolean isNeedPaging = mPickerConfig == null || mPickerConfig.isNeedPaging();
        boolean isNeedGif = mPickerConfig != null && mPickerConfig.isNeedGif();
        int totalCount = getTotalCount(cr, bucketId, columns, isDefaultAlbum, isNeedGif);

        String imageMimeType = isNeedGif ? SELECTION_IMAGE_MIME_TYPE : SELECTION_IMAGE_MIME_TYPE_WITHOUT_GIF;
        String[] args = isNeedGif ? SELECTION_ARGS_IMAGE_MIME_TYPE : SELECTION_ARGS_IMAGE_MIME_TYPE_WITHOUT_GIF;
        String order = isNeedPaging ? Images.Media.DATE_MODIFIED + DESC + " LIMIT "
                + page * IMediaTask.PAGE_LIMIT + " , " + IMediaTask.PAGE_LIMIT : Images.Media.DATE_MODIFIED + DESC;
        String selectionId = isNeedGif ? SELECTION_ID : SELECTION_ID_WITHOUT_GIF;
        cursor = query(cr, bucketId, columns, isDefaultAlbum, isNeedGif, imageMimeType, args, order, selectionId);
        addItem(totalCount, result, cursor, callback);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return result;
}
 
Example #3
Source File: ImageTask.java    From boxing with Apache License 2.0 6 votes vote down vote up
private void queryThumbnails(ContentResolver cr, String[] projection) {
    Cursor cur = null;
    try {
        cur = Images.Thumbnails.queryMiniThumbnails(cr, Images.Thumbnails.EXTERNAL_CONTENT_URI,
                Images.Thumbnails.MINI_KIND, projection);
        if (cur != null && cur.moveToFirst()) {
            do {
                String imageId = cur.getString(cur.getColumnIndex(Images.Thumbnails.IMAGE_ID));
                String imagePath = cur.getString(cur.getColumnIndex(Images.Thumbnails.DATA));
                mThumbnailMap.put(imageId, imagePath);
            } while (cur.moveToNext() && !cur.isLast());
        }
    } finally {
        if (cur != null) {
            cur.close();
        }
    }
}
 
Example #4
Source File: ImageTask.java    From boxing with Apache License 2.0 6 votes vote down vote up
private Cursor query(ContentResolver cr, String bucketId, String[] columns, boolean isDefaultAlbum,
                     boolean isNeedGif, String imageMimeType, String[] args, String order, String selectionId) {
    Cursor resultCursor;
    if (isDefaultAlbum) {
        resultCursor = cr.query(Images.Media.EXTERNAL_CONTENT_URI, columns, imageMimeType,
                args, order);
    } else {
        if (isNeedGif) {
            resultCursor = cr.query(Images.Media.EXTERNAL_CONTENT_URI, columns, selectionId,
                    new String[]{bucketId, args[0], args[1], args[2], args[3]}, order);
        } else {
            resultCursor = cr.query(Images.Media.EXTERNAL_CONTENT_URI, columns, selectionId,
                    new String[]{bucketId, args[0], args[1], args[2]}, order);
        }
    }
    return resultCursor;
}
 
Example #5
Source File: StorageProvider.java    From FireFiles with Apache License 2.0 6 votes vote down vote up
protected ParcelFileDescriptor openImageThumbnailCleared(long id, CancellationSignal signal)
        throws FileNotFoundException {
    final ContentResolver resolver = getContext().getContentResolver();

    Cursor cursor = null;
    try {
        cursor = resolver.query(Images.Thumbnails.EXTERNAL_CONTENT_URI,
                ImageThumbnailQuery.PROJECTION, Images.Thumbnails.IMAGE_ID + "=" + id, null,
                null);
        if (cursor.moveToFirst()) {
            final String data = cursor.getString(ImageThumbnailQuery._DATA);
            return ParcelFileDescriptor.open(
                    new File(data), ParcelFileDescriptor.MODE_READ_ONLY);
        }
    } finally {
        IoUtils.closeQuietly(cursor);
    }
    return null;
}
 
Example #6
Source File: StorageProvider.java    From FireFiles with Apache License 2.0 6 votes vote down vote up
protected int queryOrientationForImage(long id, CancellationSignal signal) {
    final ContentResolver resolver = getContext().getContentResolver();

    Cursor cursor = null;
    try {
        cursor = resolver.query(Images.Media.EXTERNAL_CONTENT_URI,
                ImageOrientationQuery.PROJECTION, ImageColumns._ID + "=" + id, null, null);
        if (cursor.moveToFirst()) {
            return cursor.getInt(ImageOrientationQuery.ORIENTATION);
        } else {
            Log.w(TAG, "Missing orientation data for " + id);
            return 0;
        }
    } finally {
        IoUtils.closeQuietly(cursor);
    }
}
 
Example #7
Source File: StorageProvider.java    From FireFiles with Apache License 2.0 6 votes vote down vote up
protected int queryOrientationForImage(long id, CancellationSignal signal) {
    final ContentResolver resolver = getContext().getContentResolver();

    Cursor cursor = null;
    try {
        cursor = resolver.query(Images.Media.EXTERNAL_CONTENT_URI,
                ImageOrientationQuery.PROJECTION, ImageColumns._ID + "=" + id, null, null);
        if (cursor.moveToFirst()) {
            return cursor.getInt(ImageOrientationQuery.ORIENTATION);
        } else {
            Log.w(TAG, "Missing orientation data for " + id);
            return 0;
        }
    } finally {
        IoUtils.closeQuietly(cursor);
    }
}
 
Example #8
Source File: Global.java    From Favorite-Android-Client with Apache License 2.0 6 votes vote down vote up
public static String getRealPathFromURI(Context context, Uri contentUri) {
	Cursor cursor = null;
	try {
		Log.i("test", contentUri.toString());
		String[] proj = { MediaStore.Images.Media.DATA };
		cursor = context.getContentResolver().query(contentUri, proj, null,
				null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	} finally {
		if (cursor != null) {
			cursor.close();
		}
	}
}
 
Example #9
Source File: StorageProvider.java    From FireFiles with Apache License 2.0 6 votes vote down vote up
protected ParcelFileDescriptor openImageThumbnailCleared(long id, CancellationSignal signal)
        throws FileNotFoundException {
    final ContentResolver resolver = getContext().getContentResolver();

    Cursor cursor = null;
    try {
        cursor = resolver.query(Images.Thumbnails.EXTERNAL_CONTENT_URI,
                ImageThumbnailQuery.PROJECTION, Images.Thumbnails.IMAGE_ID + "=" + id, null,
                null);
        if (cursor.moveToFirst()) {
            final String data = cursor.getString(ImageThumbnailQuery._DATA);
            return ParcelFileDescriptor.open(
                    new File(data), ParcelFileDescriptor.MODE_READ_ONLY);
        }
    } finally {
        IoUtils.closeQuietly(cursor);
    }
    return null;
}
 
Example #10
Source File: LocalImage.java    From medialibrary with Apache License 2.0 6 votes vote down vote up
@Override
public void rotate(int degrees) throws Exception {
    GalleryUtils.assertNotInRenderThread();
    Uri baseUri = Images.Media.EXTERNAL_CONTENT_URI;
    ContentValues values = new ContentValues();
    int rotation = (this.rotation + degrees) % 360;
    if (rotation < 0) rotation += 360;

    if (mimeType.equalsIgnoreCase("image/jpeg")) {
        ExifInterface exifInterface = new ExifInterface(filePath);
        exifInterface.setAttribute(ExifInterface.TAG_ORIENTATION,
                String.valueOf(rotation));
        exifInterface.saveAttributes();
        fileSize = new File(filePath).length();
        values.put(Images.Media.SIZE, fileSize);
    }

    values.put(Images.Media.ORIENTATION, rotation);
    mApplication.getContentResolver().update(baseUri, values, "_id=?",
            new String[]{String.valueOf(id)});
}
 
Example #11
Source File: LocalImage.java    From medialibrary with Apache License 2.0 6 votes vote down vote up
public LocalImage(Path path, MediaDataContext application, int id) {
    super(path, nextVersionNumber());
    mApplication = application;
    ContentResolver resolver = mApplication.getContentResolver();
    Uri uri = Images.Media.EXTERNAL_CONTENT_URI;
    Cursor cursor = LocalAlbum.getItemCursor(resolver, uri, PROJECTION, id);
    if (cursor == null) {
        throw new RuntimeException("cannot get cursor for: " + path);
    }
    try {
        if (cursor.moveToNext()) {
            loadFromCursor(cursor);
        } else {
            throw new RuntimeException("cannot find data for: " + path);
        }
    } finally {
        cursor.close();
    }
}
 
Example #12
Source File: BitmapManager.java    From droidddle with Apache License 2.0 6 votes vote down vote up
public synchronized void cancelThreadDecoding(Thread t, ContentResolver cr) {
    ThreadStatus status = getOrCreateThreadStatus(t);
    status.mState = State.CANCEL;
    if (status.mOptions != null) {
        status.mOptions.requestCancelDecode();
    }

    // Wake up threads in waiting list
    notifyAll();

    // Since our cancel request can arrive MediaProvider earlier than getThumbnail request,
    // we use mThumbRequesting flag to make sure our request does cancel the request.
    try {
        synchronized (status) {
            while (status.mThumbRequesting) {
                Images.Thumbnails.cancelThumbnailRequest(cr, -1, t.getId());
                Video.Thumbnails.cancelThumbnailRequest(cr, -1, t.getId());
                status.wait(200);
            }
        }
    } catch (InterruptedException ex) {
        // ignore it.
    }
}
 
Example #13
Source File: BitmapManager.java    From droidddle with Apache License 2.0 6 votes vote down vote up
public Bitmap getThumbnail(ContentResolver cr, long origId, int kind, BitmapFactory.Options options, boolean isVideo) {
    Thread t = Thread.currentThread();
    ThreadStatus status = getOrCreateThreadStatus(t);

    if (!canThreadDecoding(t)) {
        Log.d(TAG, "Thread " + t + " is not allowed to decode.");
        return null;
    }

    try {
        synchronized (status) {
            status.mThumbRequesting = true;
        }
        if (isVideo) {
            return Video.Thumbnails.getThumbnail(cr, origId, t.getId(), kind, null);
        } else {
            return Images.Thumbnails.getThumbnail(cr, origId, t.getId(), kind, null);
        }
    } finally {
        synchronized (status) {
            status.mThumbRequesting = false;
            status.notifyAll();
        }
    }
}
 
Example #14
Source File: UserPhotosFragment.java    From android-open-project-demo with Apache License 2.0 6 votes vote down vote up
public Loader<Cursor> onCreateLoader(final int id, Bundle bundle) {

		CursorLoader cursorLoader = null;

		switch (id) {
		case LOADER_USER_PHOTOS_EXTERNAL:
			String selection = null;
			String[] selectionArgs = null;

			if (null != bundle
					&& bundle.containsKey(LOADER_PHOTOS_BUCKETS_PARAM)) {
				selection = Images.Media.BUCKET_ID + " = ?";
				selectionArgs = new String[] { bundle
						.getString(LOADER_PHOTOS_BUCKETS_PARAM) };
			}

			cursorLoader = new PhotupCursorLoader(getActivity(),
					MediaStoreCursorHelper.MEDIA_STORE_CONTENT_URI,
					MediaStoreCursorHelper.PHOTOS_PROJECTION, selection,
					selectionArgs, MediaStoreCursorHelper.PHOTOS_ORDER_BY,
					false);
			break;
		}

		return cursorLoader;
	}
 
Example #15
Source File: PBJournalAdapter.java    From client-android with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean handleMessage(Message message) {
    // done on async thread
    final View view = (View) message.obj;
    final ImageView thumbImageView = (ImageView) view.findViewById(R.id.thumbnail);
    Bitmap bitmap = Images.Thumbnails.getThumbnail(context.getContentResolver(),
            message.what, Images.Thumbnails.MICRO_KIND, null);
    if (bitmap == null) {
        bitmap = Video.Thumbnails.getThumbnail(context.getContentResolver(),
                message.what, Video.Thumbnails.MICRO_KIND, null);
    }
    final Bitmap fBitmap = bitmap;

    // back on UI thread to set the bitmap to the view
    new Handler(context.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            thumbImageView.setImageBitmap(fBitmap);
        }
    });

    return true;
}
 
Example #16
Source File: MediaResourceManager.java    From GreenDamFileExploere with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * 获取图片地址列表
 * 
 * @return list
 */
public static List<String> getImagesFromMedia() {
    ArrayList<String> pictures = new ArrayList<String>();
    Cursor c = null;
    try {
        FileCategoryPageFragment.mAllPictureSize = 0;
        c = mContentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[] { "_id", "_data", "_size" }, null, null, null);
        while (c.moveToNext()) {
            String path = c.getString(c.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
            if (!FileUtils.isExists(path)) {
                continue;
            }
            long size = c.getLong(c.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE));
            FileCategoryPageFragment.mAllPictureSize += size;
            pictures.add(path);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (c != null) {
            c.close();
        }
    }
    return pictures;
}
 
Example #17
Source File: StorageProvider.java    From FireFiles with Apache License 2.0 6 votes vote down vote up
protected ParcelFileDescriptor openImageThumbnailCleared(long id, CancellationSignal signal)
        throws FileNotFoundException {
    final ContentResolver resolver = getContext().getContentResolver();

    Cursor cursor = null;
    try {
        cursor = resolver.query(Images.Thumbnails.EXTERNAL_CONTENT_URI,
                ImageThumbnailQuery.PROJECTION, Images.Thumbnails.IMAGE_ID + "=" + id, null,
                null);
        if (cursor.moveToFirst()) {
            final String data = cursor.getString(ImageThumbnailQuery._DATA);
            return ParcelFileDescriptor.open(
                    new File(data), ParcelFileDescriptor.MODE_READ_ONLY);
        }
    } finally {
        IoUtils.closeQuietly(cursor);
    }
    return null;
}
 
Example #18
Source File: BitmapManager.java    From reader with MIT License 6 votes vote down vote up
public synchronized void cancelThreadDecoding(Thread t, ContentResolver cr) {
    ThreadStatus status = getOrCreateThreadStatus(t);
    status.mState = State.CANCEL;
    if (status.mOptions != null) {
        status.mOptions.requestCancelDecode();
    }

    // Wake up threads in waiting list
    notifyAll();

    // Since our cancel request can arrive MediaProvider earlier than getThumbnail request,
    // we use mThumbRequesting flag to make sure our request does cancel the request.
    try {
        synchronized (status) {
            while (status.mThumbRequesting) {
                Images.Thumbnails.cancelThumbnailRequest(cr, -1, t.getId());
                Video.Thumbnails.cancelThumbnailRequest(cr, -1, t.getId());
                status.wait(200);
            }
        }
    } catch (InterruptedException ex) {
        // ignore it.
    }
}
 
Example #19
Source File: StorageProvider.java    From FireFiles with Apache License 2.0 6 votes vote down vote up
protected int queryOrientationForImage(long id, CancellationSignal signal) {
    final ContentResolver resolver = getContext().getContentResolver();

    Cursor cursor = null;
    try {
        cursor = resolver.query(Images.Media.EXTERNAL_CONTENT_URI,
                ImageOrientationQuery.PROJECTION, ImageColumns._ID + "=" + id, null, null);
        if (cursor.moveToFirst()) {
            return cursor.getInt(ImageOrientationQuery.ORIENTATION);
        } else {
            Log.w(TAG, "Missing orientation data for " + id);
            return 0;
        }
    } finally {
        IoUtils.closeQuietly(cursor);
    }
}
 
Example #20
Source File: BitmapManager.java    From reader with MIT License 6 votes vote down vote up
public synchronized void cancelThreadDecoding(Thread t, ContentResolver cr) {
    ThreadStatus status = getOrCreateThreadStatus(t);
    status.mState = State.CANCEL;
    if (status.mOptions != null) {
        status.mOptions.requestCancelDecode();
    }

    // Wake up threads in waiting list
    notifyAll();

    // Since our cancel request can arrive MediaProvider earlier than getThumbnail request,
    // we use mThumbRequesting flag to make sure our request does cancel the request.
    try {
        synchronized (status) {
            while (status.mThumbRequesting) {
                Images.Thumbnails.cancelThumbnailRequest(cr, -1, t.getId());
                Video.Thumbnails.cancelThumbnailRequest(cr, -1, t.getId());
                status.wait(200);
            }
        }
    } catch (InterruptedException ex) {
        // ignore it.
    }
}
 
Example #21
Source File: MediaRepository.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@WorkerThread
private @NonNull List<Media> getMediaInBucket(@NonNull Context context, @NonNull String bucketId) {
  if (!Permissions.hasAll(context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
    return Collections.emptyList();
  }

  List<Media> images = getMediaInBucket(context, bucketId, Images.Media.EXTERNAL_CONTENT_URI, true);
  List<Media> videos = getMediaInBucket(context, bucketId, Video.Media.EXTERNAL_CONTENT_URI, false);
  List<Media> media  = new ArrayList<>(images.size() + videos.size());

  media.addAll(images);
  media.addAll(videos);
  Collections.sort(media, (o1, o2) -> Long.compare(o2.getDate(), o1.getDate()));

  return media;
}
 
Example #22
Source File: StorageProvider.java    From FireFiles with Apache License 2.0 5 votes vote down vote up
protected long getImageForPathCleared(String path) throws FileNotFoundException {
    final ContentResolver resolver = getContext().getContentResolver();
    Cursor cursor = null;
    try {
        cursor = resolver.query(Images.Media.EXTERNAL_CONTENT_URI,
                ImagesBucketThumbnailQuery.PROJECTION, ImageColumns.DATA + "= ? ",
                new String[] { path.replaceAll("'", "''") }, ImageColumns.DATE_MODIFIED + " DESC");
        if (cursor.moveToFirst()) {
            return cursor.getLong(ImagesBucketThumbnailQuery._ID);
        }
    } finally {
        IoUtils.closeQuietly(cursor);
    }
    throw new FileNotFoundException("No image found for bucket");
}
 
Example #23
Source File: ImageActivity.java    From retroboy with MIT License 5 votes vote down vote up
private void setInput(Uri inputuri) {
	if (inputuri != null) {
		// Find the image info
		Cursor cursor = null;
		
		try {
			cursor = getContentResolver().query(inputuri, new String[] {Images.Media.DISPLAY_NAME, Images.Media.ORIENTATION}, null, null, null);
			if (cursor != null && cursor.moveToFirst()) {
				_inputinfo = new ImageInfo(inputuri, cursor.getString(0), cursor.getInt(1));
				Log.i(TAG, "Image name: " + _inputinfo.filename);					
			}
		}
		finally {
			if (cursor != null) {
				cursor.close();
			}
		}
	}

	// Set application title
	if (_inputinfo != null) {
		getActionBar().setTitle(_inputinfo.filename);
	}
	
	// Process image in background
	if (_outputpath == null && _inputinfo != null) {
		new ProcessImageTask(_inputinfo, _outputpath).execute();
	}
}
 
Example #24
Source File: MainActivity.java    From ImageEditor-android with MIT License 5 votes vote down vote up
/**
 * Pick a random image from the user gallery
 * 
 * @return
 */
@SuppressWarnings("unused")
private Uri pickRandomImage() {
	Cursor c = getContentResolver().query(
			Images.Media.EXTERNAL_CONTENT_URI,
			new String[] { ImageColumns._ID, ImageColumns.DATA },
			ImageColumns.SIZE + ">?", new String[] { "90000" }, null);
	Uri uri = null;

	if (c != null) {
		int total = c.getCount();
		int position = (int) (Math.random() * total);
		Log.d(LOG_TAG, "pickRandomImage. total images: " + total
				+ ", position: " + position);
		if (total > 0) {
			if (c.moveToPosition(position)) {
				String data = c.getString(c
						.getColumnIndex(Images.ImageColumns.DATA));
				long id = c.getLong(c
						.getColumnIndex(Images.ImageColumns._ID));

				uri = Uri.parse(data);

				Log.d(LOG_TAG, uri.toString());
			}
		}
		c.close();
	}
	return uri;
}
 
Example #25
Source File: MediaResourceManager.java    From GreenDamFileExploere with Apache License 2.0 5 votes vote down vote up
public static Bitmap getVideoThumbnail(int id) {
    Bitmap bitmap = null;
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inDither = false;
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    bitmap = MediaStore.Video.Thumbnails.getThumbnail(mContentResolver, id, Images.Thumbnails.MICRO_KIND, options);
    return bitmap;
}
 
Example #26
Source File: VideoObject.java    From droidddle with Apache License 2.0 5 votes vote down vote up
@Override
public Bitmap miniThumbBitmap() {
    try {
        long id = mId;
        return BitmapManager.instance().getThumbnail(mContentResolver, id, Images.Thumbnails.MICRO_KIND, null, true);
    } catch (Throwable ex) {
        Log.e(TAG, "miniThumbBitmap got exception", ex);
        return null;
    }
}
 
Example #27
Source File: StorageProvider.java    From FireFiles with Apache License 2.0 5 votes vote down vote up
protected long getImageForBucketCleared(long bucketId) throws FileNotFoundException {
    final ContentResolver resolver = getContext().getContentResolver();
    Cursor cursor = null;
    try {
        cursor = resolver.query(Images.Media.EXTERNAL_CONTENT_URI,
                ImagesBucketThumbnailQuery.PROJECTION, ImageColumns.BUCKET_ID + "=" + bucketId,
                null, ImageColumns.DATE_MODIFIED + " DESC");
        if (cursor.moveToFirst()) {
            return cursor.getLong(ImagesBucketThumbnailQuery._ID);
        }
    } finally {
        IoUtils.closeQuietly(cursor);
    }
    throw new FileNotFoundException("No video found for bucket");
}
 
Example #28
Source File: MediaDocumentsProvider.java    From FireFiles with Apache License 2.0 5 votes vote down vote up
private Uri getUriForDocumentId(String docId) {
    final Ident ident = getIdentForDocId(docId);
    if (TYPE_IMAGE.equals(ident.type) && ident.id != -1) {
        return ContentUris.withAppendedId(
                Images.Media.EXTERNAL_CONTENT_URI, ident.id);
    } else if (TYPE_VIDEO.equals(ident.type) && ident.id != -1) {
        return ContentUris.withAppendedId(
                Video.Media.EXTERNAL_CONTENT_URI, ident.id);
    } else if (TYPE_AUDIO.equals(ident.type) && ident.id != -1) {
        return ContentUris.withAppendedId(
                Audio.Media.EXTERNAL_CONTENT_URI, ident.id);
    } else {
        throw new UnsupportedOperationException("Unsupported document " + docId);
    }
}
 
Example #29
Source File: MediaDocumentsProvider.java    From FireFiles with Apache License 2.0 5 votes vote down vote up
private void includeImagesRoot(MatrixCursor result) {
    int flags = Root.FLAG_LOCAL_ONLY | Root.FLAG_SUPPORTS_RECENTS;
    if (isEmpty(Images.Media.EXTERNAL_CONTENT_URI)) {
        flags |= Root.FLAG_EMPTY;
        sReturnedImagesEmpty = true;
    }

    final RowBuilder row = result.newRow();
    row.add(Root.COLUMN_ROOT_ID, TYPE_IMAGES_ROOT);
    row.add(Root.COLUMN_FLAGS, flags);
    row.add(Root.COLUMN_TITLE, getContext().getString(R.string.root_images));
    row.add(Root.COLUMN_DOCUMENT_ID, TYPE_IMAGES_ROOT);
    row.add(Root.COLUMN_MIME_TYPES, IMAGE_MIME_TYPES);
}
 
Example #30
Source File: MediaRepository.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@WorkerThread
private @NonNull FolderResult getFolders(@NonNull Context context, @NonNull Uri contentUri) {
  String                  cameraPath         = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath() + File.separator + "Camera";
  String                  cameraBucketId     = null;
  Uri                     globalThumbnail    = null;
  long                    thumbnailTimestamp = 0;
  Map<String, FolderData> folders            = new HashMap<>();

  String[] projection = new String[] { Images.Media.DATA, Images.Media.BUCKET_ID, Images.Media.BUCKET_DISPLAY_NAME, Images.Media.DATE_MODIFIED };
  String   selection  = Images.Media.DATA + " NOT NULL";
  String   sortBy     = Images.Media.BUCKET_DISPLAY_NAME + " COLLATE NOCASE ASC, " + Images.Media.DATE_MODIFIED + " DESC";

  try (Cursor cursor = context.getContentResolver().query(contentUri, projection, selection, null, sortBy)) {
    while (cursor != null && cursor.moveToNext()) {
      String     path      = cursor.getString(cursor.getColumnIndexOrThrow(projection[0]));
      Uri        thumbnail = Uri.fromFile(new File(path));
      String     bucketId  = cursor.getString(cursor.getColumnIndexOrThrow(projection[1]));
      String     title     = cursor.getString(cursor.getColumnIndexOrThrow(projection[2]));
      long       timestamp = cursor.getLong(cursor.getColumnIndexOrThrow(projection[3]));
      FolderData folder    = Util.getOrDefault(folders, bucketId, new FolderData(thumbnail, title, bucketId));

      folder.incrementCount();
      folders.put(bucketId, folder);

      if (cameraBucketId == null && path.startsWith(cameraPath)) {
        cameraBucketId = bucketId;
      }

      if (timestamp > thumbnailTimestamp) {
        globalThumbnail    = thumbnail;
        thumbnailTimestamp = timestamp;
      }
    }
  }

  return new FolderResult(cameraBucketId, globalThumbnail, thumbnailTimestamp, folders);
}