1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 package org.chromium.base;
7 import android.content.ContentResolver;
8 import android.content.Context;
9 import android.database.Cursor;
10 import android.net.Uri;
11 import android.os.ParcelFileDescriptor;
12 import android.util.Log;
15 * This class provides methods to access content URI schemes.
17 public abstract class ContentUriUtils {
18 private static final String TAG = "ContentUriUtils";
20 // Prevent instantiation.
21 private ContentUriUtils() {}
24 * Opens the content URI for reading, and returns the file descriptor to
25 * the caller. The caller is responsible for closing the file desciptor.
27 * @param context {@link Context} in interest
28 * @param uriString the content URI to open
29 * @returns file desciptor upon sucess, or -1 otherwise.
32 public static int openContentUriForRead(Context context, String uriString) {
33 ParcelFileDescriptor pfd = getParcelFileDescriptor(context, uriString);
35 return pfd.detachFd();
41 * Check whether a content URI exists.
43 * @param context {@link Context} in interest.
44 * @param uriString the content URI to query.
45 * @returns true if the uri exists, or false otherwise.
48 public static boolean contentUriExists(Context context, String uriString) {
49 ParcelFileDescriptor pfd = getParcelFileDescriptor(context, uriString);
57 * Helper method to open a content URI and return the ParcelFileDescriptor.
59 * @param context {@link Context} in interest.
60 * @param uriString the content URI to open.
61 * @returns ParcelFileDescriptor of the content URI, or NULL if the file does not exist.
63 private static ParcelFileDescriptor getParcelFileDescriptor(Context context, String uriString) {
64 ContentResolver resolver = context.getContentResolver();
65 Uri uri = Uri.parse(uriString);
67 ParcelFileDescriptor pfd = null;
69 pfd = resolver.openFileDescriptor(uri, "r");
70 } catch (java.io.FileNotFoundException e) {
71 Log.w(TAG, "Cannot find content uri: " + uriString, e);
77 * Method to resolve the display name of a content URI.
79 * @param uri the content URI to be resolved.
80 * @param contentResolver the content resolver to query.
81 * @param columnField the column field to query.
82 * @returns the display name of the @code uri if present in the database
83 * or an empty string otherwise.
85 public static String getDisplayName(
86 Uri uri, ContentResolver contentResolver, String columnField) {
87 if (contentResolver == null || uri == null) return "";
90 cursor = contentResolver.query(uri, null, null, null, null);
92 if (cursor != null && cursor.getCount() >= 1) {
94 int index = cursor.getColumnIndex(columnField);
95 if (index > -1) return cursor.getString(index);
97 } catch (NullPointerException e) {
98 // Some android models don't handle the provider call correctly.
99 // see crbug.com/345393
102 if (cursor != null) cursor.close();