Example usage for android.net Uri getPath

List of usage examples for android.net Uri getPath

Introduction

In this page you can find the example usage for android.net Uri getPath.

Prototype

@Nullable
public abstract String getPath();

Source Link

Document

Gets the decoded path.

Usage

From source file:com.google.samples.apps.iosched.util.UIUtils.java

/**
 * If an activity's intent is for a Google I/O web URL that the app can handle natively, this
 * method translates the intent to the equivalent native intent.
 *//*  w  w w. j  a v  a2s.  c  o m*/
public static void tryTranslateHttpIntent(Activity activity) {
    Intent intent = activity.getIntent();
    if (intent == null) {
        return;
    }

    Uri uri = intent.getData();
    if (uri == null || TextUtils.isEmpty(uri.getPath())) {
        return;
    }

    Uri sessionDetailWebUrlPrefix = Uri.parse(Config.SESSION_DETAIL_WEB_URL_PREFIX);
    String prefixPath = sessionDetailWebUrlPrefix.getPath();
    String path = uri.getPath();

    if (sessionDetailWebUrlPrefix.getScheme().equals(uri.getScheme())
            && sessionDetailWebUrlPrefix.getHost().equals(uri.getHost()) && path.startsWith(prefixPath)) {
        String sessionId = path.substring(prefixPath.length());
        activity.setIntent(
                new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions.buildSessionUri(sessionId)));
    }
}

From source file:com.example.app_2.utils.Utils.java

public static String getPath(Context context, Uri uri) {
    if ("content".equalsIgnoreCase(uri.getScheme())) {
        String[] projection = { "_data" };
        Cursor cursor = null;/*ww  w. j a  va  2 s  .co m*/

        try {
            cursor = context.getContentResolver().query(uri, projection, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow("_data");
            if (cursor.moveToFirst()) {
                return cursor.getString(column_index);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

From source file:com.dycody.android.idealnote.utils.StorageHelper.java

/**
 * Creates a fiile to be used as attachment.
 *//*from ww  w  . j  a  v  a  2s . com*/
public static Attachment createAttachmentFromUri(Context mContext, Uri uri, boolean moveSource) {
    String name = FileHelper.getNameFromUri(mContext, uri);
    String extension = FileHelper.getFileExtension(FileHelper.getNameFromUri(mContext, uri))
            .toLowerCase(Locale.getDefault());
    File f;
    if (moveSource) {
        f = createNewAttachmentFile(mContext, extension);
        try {
            FileUtils.moveFile(new File(uri.getPath()), f);
        } catch (IOException e) {
            Log.e(Constants.TAG, "Can't move file " + uri.getPath());
        }
    } else {
        f = StorageHelper.createExternalStoragePrivateFile(mContext, uri, extension);
    }
    Attachment mAttachment = null;
    if (f != null) {
        mAttachment = new Attachment(Uri.fromFile(f), StorageHelper.getMimeTypeInternal(mContext, uri));
        mAttachment.setName(name);
        mAttachment.setSize(f.length());
    }
    return mAttachment;
}

From source file:in.shick.diode.common.Common.java

/**
 *
 * @param settings The {@link RedditSettings} object used to for preference-retrieving.
 * @param context The {@link Context} object to use, as necessary.
 * @param url The URL to launch in the browser.
 * @param threadUrl The (optional) URL of the comments thread for the 'View comments' menu option in the browser.
 * @param requireNewTask set this to true if context is not an Activity
 * @param bypassParser Should URI parsing be bypassed, usually true in the case an external browser is being launched.
 * @param useExternalBrowser Should the external browser app be launched instead of the internal one.
 * @param saveHistory Should the URL be entered into the browser history?
 *///from ww w  . jav  a  2  s .co m
public static void launchBrowser(RedditSettings settings, Context context, String url, String threadUrl,
        boolean requireNewTask, boolean bypassParser, boolean useExternalBrowser, boolean saveHistory) {

    try {
        if (saveHistory) {
            Browser.updateVisitedHistory(context.getContentResolver(), url, true);
        }
    } catch (Exception ex) {
        if (Constants.LOGGING)
            Log.i(TAG, "Browser.updateVisitedHistory error", ex);
    }
    boolean forceDesktopUserAgent = false;
    if (!bypassParser && settings != null && settings.isLoadImgurImagesDirectly()) {
        Matcher m = m_imgurRegex.matcher(url);
        if (m.matches() && m.group(1) != null) {
            // We've determined it's an imgur link, no need to parse it further.
            bypassParser = true;
            url = "http://i.imgur.com/" + m.group(1);
            if (!StringUtils.isEmpty(m.group(2))) {
                String extension = m.group(2);
                if (".gifv".equalsIgnoreCase(extension)) {
                    extension = ".mp4";
                }
                url += extension;
            } else {
                // Need to give images an extension, or imgur will redirect to the mobile site.
                url += ".png";
            }
            forceDesktopUserAgent = true;
        }
    }
    if (settings != null && settings.isLoadVredditLinksDirectly()) {
        if (url.contains("v.redd.it")) {
            url += "/DASH_600_K";
        }
    }

    Uri uri = Uri.parse(url);

    if (!bypassParser) {
        if (Util.isRedditUri(uri)) {
            String path = uri.getPath();
            Matcher matcher = COMMENT_LINK.matcher(path);
            if (matcher.matches()) {
                if (matcher.group(3) != null || matcher.group(2) != null) {
                    CacheInfo.invalidateCachedThread(context);
                    Intent intent = new Intent(context, CommentsListActivity.class);
                    intent.setData(uri);
                    intent.putExtra(Constants.EXTRA_NUM_COMMENTS, Constants.DEFAULT_COMMENT_DOWNLOAD_LIMIT);
                    if (requireNewTask)
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                    return;
                }
            }
            matcher = REDDIT_LINK.matcher(path);
            if (matcher.matches()) {
                CacheInfo.invalidateCachedSubreddit(context);
                Intent intent = new Intent(context, ThreadsListActivity.class);
                intent.setData(uri);
                if (requireNewTask)
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
                return;
            }
            matcher = USER_LINK.matcher(path);
            if (matcher.matches()) {
                Intent intent = new Intent(context, ProfileActivity.class);
                intent.setData(uri);
                if (requireNewTask)
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
                return;
            }
        } else if (Util.isRedditShortenedUri(uri)) {
            String path = uri.getPath();
            if (path.equals("") || path.equals("/")) {
                CacheInfo.invalidateCachedSubreddit(context);
                Intent intent = new Intent(context, ThreadsListActivity.class);
                intent.setData(uri);
                if (requireNewTask)
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            } else {
                // Assume it points to a thread aka CommentsList
                CacheInfo.invalidateCachedThread(context);
                Intent intent = new Intent(context, CommentsListActivity.class);
                intent.setData(uri);
                intent.putExtra(Constants.EXTRA_NUM_COMMENTS, Constants.DEFAULT_COMMENT_DOWNLOAD_LIMIT);
                if (requireNewTask)
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }
            return;
        }
    }
    uri = Util.optimizeMobileUri(uri);

    // Some URLs should always be opened externally, if BrowserActivity doesn't support their content.
    if (Util.isYoutubeUri(uri) || Util.isAndroidMarketUri(uri)) {
        useExternalBrowser = true;
    }

    if (useExternalBrowser) {
        Intent browser = new Intent(Intent.ACTION_VIEW, uri);
        browser.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());
        if (requireNewTask) {
            browser.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(browser);
    } else {
        Intent browser = new Intent(context, BrowserActivity.class);
        browser.setData(uri);
        if (forceDesktopUserAgent) {
            browser.putExtra(Constants.EXTRA_FORCE_UA_STRING, "desktop");
        }
        if (threadUrl != null) {
            browser.putExtra(Constants.EXTRA_THREAD_URL, threadUrl);
        }
        if (requireNewTask) {
            browser.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(browser);
    }
}

From source file:mobisocial.noteshere.util.UriImage.java

public static float rotationForImage(Context context, Uri uri) {
    if (uri.getScheme().equals("content")) {
        String[] projection = { Images.ImageColumns.ORIENTATION };
        Cursor c = context.getContentResolver().query(uri, projection, null, null, null);
        try {/*from   w  w w .  j a va 2 s. c  o m*/
            if (c.moveToFirst()) {
                return c.getInt(0);
            }
        } finally {
            c.close();
        }
    } else if (uri.getScheme().equals("file")) {
        try {
            ExifInterface exif = new ExifInterface(uri.getPath());
            int rotation = (int) exifOrientationToDegrees(
                    exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL));
            return rotation;
        } catch (IOException e) {
            Log.e(TAG, "Error checking exif", e);
        }
    }
    return 0f;
}

From source file:mil.nga.giat.mage.sdk.utils.MediaUtility.java

public static String getFileAbsolutePath(Uri uri, Context c) {
    String fileName = null;/*from   ww  w  . jav  a 2  s . c  o  m*/
    String scheme = uri.getScheme();
    if (scheme.equals("file")) {
        fileName = uri.getPath();
    } else if (scheme.equals("content")) {
        Cursor cursor = null;
        try {
            String[] proj = { MediaStore.Images.Media.DATA };
            cursor = c.getContentResolver().query(uri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } catch (Exception e) {
            Log.e(LOG_NAME, "Error reading content URI", e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }
    return fileName;
}

From source file:it.feio.android.omninotes.utils.StorageManager.java

/**
 * @param mContext/*w  w w .  j  a v  a  2s.c o  m*/
 * @param uri
 * @return
 */
public static Attachment createAttachmentFromUri(Context mContext, Uri uri, boolean moveSource) {
    String name = FileHelper.getNameFromUri(mContext, uri);
    String extension = FileHelper.getFileExtension(FileHelper.getNameFromUri(mContext, uri))
            .toLowerCase(Locale.getDefault());
    File f = null;
    if (moveSource) {
        f = createNewAttachmentFile(mContext, extension);
        try {
            FileUtils.moveFile(new File(uri.getPath()), f);
        } catch (IOException e) {
            Log.e(Constants.TAG, "Can't move file " + uri.getPath());
        }
    } else {
        f = StorageManager.createExternalStoragePrivateFile(mContext, uri, extension);
    }
    Attachment mAttachment = null;
    if (f != null) {
        mAttachment = new Attachment(Uri.fromFile(f), StorageManager.getMimeTypeInternal(mContext, uri));
        mAttachment.setName(name);
        mAttachment.setSize(f.length());
    }
    return mAttachment;
}

From source file:Main.java

/**
 * Get a uri's file path/*from w ww.j a v  a2s .  c  o  m*/
 * 
 * @param context the application context
 * @param uri     the uri to query
 * 
 * @return the file path
 */
public static String getUriPath(Context context, Uri uri) {
    String filePath = null;

    String scheme = uri.getScheme();

    if (scheme.startsWith("content")) {
        String[] projection = { MediaStore.Files.FileColumns.DATA };

        /* 
         * FIXME 2013-10-24 Tianzi Hou
         * 
         * we cannot get file path if it is from 
         *  content://com.google.android.gallery3d.provider
         * i.e. the Picasa service
         */
        filePath = null;
        Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);

        if (cursor != null) {
            int column_index = cursor.getColumnIndexOrThrow(projection[0]);
            cursor.moveToFirst();
            filePath = cursor.getString(column_index);
            cursor.close();
        }
    } else if (scheme.startsWith("file")) {
        filePath = uri.getPath();
    }

    return filePath;
}

From source file:com.activiti.android.platform.provider.transfer.ContentTransferManager.java

public static void requestUpload(Fragment fr, Uri uri, String objectId, int type, String mimetyp) {
    Cursor cursor = null;//from ww  w  .  j  a  va 2  s.co  m
    String name = null, source, sourceId, mimetype = mimetyp;
    try {
        Bundle settingsBundle = new Bundle();

        // Retrieve other info
        cursor = fr.getActivity().getContentResolver().query(uri, null, null, null, null);

        if (cursor == null && uri != null) {
            // Is it a file ?
            File file = new File(uri.getPath());
            if (file.exists()) {
                // It's a file
                name = file.getName();
                settingsBundle.putString(ContentTransferSyncAdapter.ARGUMENT_CONTENT_PATH, file.getPath());
                if (mimetype == null) {
                    MimeType mime = MimeTypeManager.getInstance(fr.getActivity()).getMimetype(file.getName());
                    mimetype = (mime != null) ? mime.getMimeType() : mimetyp;
                }
            }
        } else if (cursor != null && cursor.moveToFirst()) {
            name = cursor.getString(cursor.getColumnIndex(DocumentsContract.Document.COLUMN_DISPLAY_NAME));
            mimetype = cursor.getString(cursor.getColumnIndex(DocumentsContract.Document.COLUMN_MIME_TYPE));
            settingsBundle.putString(ContentTransferSyncAdapter.ARGUMENT_CONTENT_URI, uri.toString());
        } else {
            throw new Exception("Cursor is empty");
        }

        settingsBundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
        settingsBundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);

        settingsBundle.putInt(ContentTransferSyncAdapter.ARGUMENT_MODE,
                ContentTransferSyncAdapter.MODE_SAF_UPLOAD);
        settingsBundle.putString(ContentTransferSyncAdapter.ARGUMENT_FILE_PATH, name);
        if (type == TYPE_TASK_ID) {
            settingsBundle.putString(ContentTransferSyncAdapter.ARGUMENT_TASK_ID, objectId);
        } else if (type == TYPE_PROCESS_ID) {
            settingsBundle.putString(ContentTransferSyncAdapter.ARGUMENT_PROCESS_ID, objectId);
        } else if (type == TYPE_PROFILE_ID) {
            settingsBundle.putString(ContentTransferSyncAdapter.ARGUMENT_PROFILE_ID, objectId);
        }
        settingsBundle.putString(ContentTransferSyncAdapter.ARGUMENT_MIMETYPE, mimetype);
        ContentResolver.requestSync(
                ActivitiAccountManager.getInstance(fr.getActivity()).getCurrentAndroidAccount(),
                ContentTransferProvider.AUTHORITY, settingsBundle);
    } catch (Exception e) {
        Log.w("COntent Transfer", Log.getStackTraceString(e));
    } finally {
        CursorUtils.closeCursor(cursor);
    }
}

From source file:Main.java

@SuppressLint("NewApi")
public static String getRealPathFromURI_API19(Context context, Uri uri) {
    String filePath = "";
    if (DocumentsContract.isDocumentUri(context, uri)) {
        String wholeID = DocumentsContract.getDocumentId(uri);
        // Split at colon, use second item in the array
        String[] splits = wholeID.split(":");
        if (splits.length == 2) {
            String id = splits[1];

            String[] column = { MediaStore.Images.Media.DATA };
            // where id is equal to
            String sel = MediaStore.Images.Media._ID + "=?";
            Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    column, sel, new String[] { id }, null);
            int columnIndex = cursor.getColumnIndex(column[0]);
            if (cursor.moveToFirst()) {
                filePath = cursor.getString(columnIndex);
            }/*from w w w  . j  a v  a  2  s.co m*/
            cursor.close();
        }
    } else {
        filePath = uri.getPath();
    }
    return filePath;
}