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:Main.java

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

        try {
            cursor = context.getContentResolver().query(uri, projection, null, null, null);
            int column_index = cursor.getColumnIndex("_data");
            if (column_index != -1 && cursor.moveToFirst()) {
                String path = cursor.getString(column_index);
                if (path == null) {
                    path = getNewTemporaryFilePath(context, uri);
                }
                return path;
            } else {
                return getNewTemporaryFilePath(context, uri);
            }
        } catch (Exception e) {
            return getNewTemporaryFilePath(context, uri);
        }
    } else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

From source file:com.keepassdroid.PasswordActivity.java

public static void Launch(Activity act, String fileName, String keyFile) throws FileNotFoundException {
    if (EmptyUtils.isNullOrEmpty(fileName)) {
        throw new FileNotFoundException();
    }/*from  ww w.  j ava2 s.  c om*/

    Uri uri = UriUtil.parseDefaultFile(fileName);
    String scheme = uri.getScheme();

    if (!EmptyUtils.isNullOrEmpty(scheme) && scheme.equalsIgnoreCase("file")) {
        File dbFile = new File(uri.getPath());
        if (!dbFile.exists()) {
            throw new FileNotFoundException();
        }
    }

    Intent i = new Intent(act, PasswordActivity.class);
    i.putExtra(KEY_FILENAME, fileName);
    i.putExtra(KEY_KEYFILE, keyFile);

    act.startActivityForResult(i, 0);

}

From source file:com.just.agentweb.AgentWebUtils.java

private static String getRealPathBelowVersion(Context context, Uri uri) {
    String filePath = null;/*from w  w w.  j  a v a2 s. c o m*/
    LogUtils.i(TAG, "method -> getRealPathBelowVersion " + uri + "   path:" + uri.getPath()
            + "    getAuthority:" + uri.getAuthority());
    String[] projection = { MediaStore.Images.Media.DATA };

    CursorLoader loader = new CursorLoader(context, uri, projection, null, null, null);
    Cursor cursor = loader.loadInBackground();

    if (cursor != null) {
        cursor.moveToFirst();
        filePath = cursor.getString(cursor.getColumnIndex(projection[0]));
        cursor.close();
    }
    if (filePath == null) {
        filePath = uri.getPath();

    }
    return filePath;
}

From source file:com.pdftron.pdf.utils.ViewerUtils.java

public static Map readImageIntent(Intent data, Context context, Uri outputFileUri)
        throws FileNotFoundException, Exception {
    final boolean isCamera;
    if (data == null || data.getData() == null) {
        isCamera = true;//from  ww w.j  a va  2s . c  o m
    } else {
        final String action = data.getAction();
        if (action == null) {
            isCamera = false;
        } else {
            isCamera = action.equals(MediaStore.ACTION_IMAGE_CAPTURE);
        }
    }

    Uri imageUri;
    if (isCamera) {
        imageUri = outputFileUri;
        AnalyticsHandlerAdapter.getInstance().sendEvent(AnalyticsHandlerAdapter.CATEGORY_FILEBROWSER,
                "Create new document from camera selected");
    } else {
        imageUri = data.getData();
        AnalyticsHandlerAdapter.getInstance().sendEvent(AnalyticsHandlerAdapter.CATEGORY_FILEBROWSER,
                "Create new document from local image file selected");
    }

    String filePath;
    if (isCamera) {
        filePath = imageUri.getPath();
    } else {
        filePath = Utils.getRealPathFromImageURI(context, imageUri);
        if (Utils.isNullOrEmpty(filePath)) {
            filePath = imageUri.getPath();
        }
    }

    // try to get bitmap
    Bitmap bitmap = Utils.getBitmapFromImageUri(context, imageUri, filePath);

    // if a file is selected, check if it is an image file
    if (!isCamera) {
        // if type is null
        if (context.getContentResolver().getType(imageUri) == null) {
            String extension = MimeTypeMap.getFileExtensionFromUrl(imageUri.getPath());
            final String[] extensions = { "jpeg", "jpg", "tiff", "tif", "gif", "png", "bmp" };

            // if file extension is not an image extension
            if (!Arrays.asList(extensions).contains(extension) && extension != null && !extension.equals("")) {
                throw new FileNotFoundException("file extension is not an image extension");
            }
            // if type is not an image
        } else if (!context.getContentResolver().getType(imageUri).startsWith("image/")) {
            throw new FileNotFoundException("type is not an image");
        }
    }

    //////////////////  Determine if image needs to be rotated   ///////////////////
    File imageFile = new File(imageUri.getPath());
    ExifInterface exif = new ExifInterface(imageFile.getAbsolutePath());
    int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);

    int imageRotation = 0;
    switch (orientation) {
    case ExifInterface.ORIENTATION_ROTATE_270:
        imageRotation = 270;
        break;
    case ExifInterface.ORIENTATION_ROTATE_180:
        imageRotation = 180;
        break;
    case ExifInterface.ORIENTATION_ROTATE_90:
        imageRotation = 90;
        break;
    }

    // in some devices (mainly Samsung), the EXIF is not saved with the image so look at the content
    // resolver as a second source of the image's rotation
    if (imageRotation == 0) {
        String[] orientationColumn = { MediaStore.Images.Media.ORIENTATION };
        Cursor cur = context.getContentResolver().query(imageUri, orientationColumn, null, null, null);
        orientation = -1;
        if (cur != null && cur.moveToFirst()) {
            orientation = cur.getInt(cur.getColumnIndex(orientationColumn[0]));
        }

        if (orientation > 0) {
            imageRotation = orientation;
        }
    }

    if (imageRotation != 0) {
        Matrix matrix = new Matrix();
        matrix.postRotate(imageRotation);
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }

    Map<String, Object> output = new HashMap<>();
    output.put("bitmap", bitmap);
    output.put("uri", imageUri);
    output.put("path", filePath);
    output.put("camera", isCamera);
    return output;
}

From source file:ir.keloud.android.lib.common.accounts.AccountUtils.java

/**
* Restore the client cookies//from   w  w  w .  j  ava  2 s.  com
* @param account
* @param client 
* @param context
*/
public static void restoreCookies(Account account, KeloudClient client, Context context) {

    Log_OC.d(TAG, "Restoring cookies for " + account.name);

    // Account Manager
    AccountManager am = AccountManager.get(context.getApplicationContext());

    Uri serverUri = (client.getBaseUri() != null) ? client.getBaseUri() : client.getWebdavUri();

    String cookiesString = am.getUserData(account, Constants.KEY_COOKIES);
    if (cookiesString != null) {
        String[] cookies = cookiesString.split(";");
        if (cookies.length > 0) {
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = new Cookie();
                int equalPos = cookies[i].indexOf('=');
                cookie.setName(cookies[i].substring(0, equalPos));
                cookie.setValue(cookies[i].substring(equalPos + 1));
                cookie.setDomain(serverUri.getHost()); // VERY IMPORTANT 
                cookie.setPath(serverUri.getPath()); // VERY IMPORTANT

                client.getState().addCookie(cookie);
            }
        }
    }
}

From source file:com.facebook.share.internal.ShareInternalUtility.java

/**
 * Creates a new Request configured to upload an image to create a staging resource. Staging
 * resources allow you to post binary data such as images, in preparation for a post of an Open
 * Graph object or action which references the image. The URI returned when uploading a staging
 * resource may be passed as the image property for an Open Graph object or action.
 *
 * @param accessToken the access token to use, or null
 * @param imageUri    the file:// or content:// Uri pointing to the image to upload
 * @param callback    a callback that will be called when the request is completed to handle
 *                    success or error conditions
 * @return a Request that is ready to execute
 * @throws FileNotFoundException/*from  w ww. j a va 2 s  .c  om*/
 */
public static GraphRequest newUploadStagingResourceWithImageRequest(AccessToken accessToken, Uri imageUri,
        Callback callback) throws FileNotFoundException {
    if (Utility.isFileUri(imageUri)) {
        return newUploadStagingResourceWithImageRequest(accessToken, new File(imageUri.getPath()), callback);
    } else if (!Utility.isContentUri(imageUri)) {
        throw new FacebookException("The image Uri must be either a file:// or content:// Uri");
    }

    GraphRequest.ParcelableResourceWithMimeType<Uri> resourceWithMimeType = new GraphRequest.ParcelableResourceWithMimeType<>(
            imageUri, "image/png");
    Bundle parameters = new Bundle(1);
    parameters.putParcelable(STAGING_PARAM, resourceWithMimeType);

    return new GraphRequest(accessToken, MY_STAGING_RESOURCES, parameters, HttpMethod.POST, callback);
}

From source file:com.cerema.cloud2.lib.common.accounts.AccountUtils.java

/**
* Restore the client cookies/*from  ww  w .  j a va 2s .com*/
* @param account
* @param client 
* @param context
*/
public static void restoreCookies(Account account, OwnCloudClient client, Context context) {

    Log_OC.d(TAG, "Restoring cookies for " + account.name);

    // Account Manager
    AccountManager am = AccountManager.get(context.getApplicationContext());

    Uri serverUri = (client.getBaseUri() != null) ? client.getBaseUri() : client.getWebdavUri();

    String cookiesString = am.getUserData(account, Constants.KEY_COOKIES);
    if (cookiesString != null) {
        String[] cookies = cookiesString.split(";");
        if (cookies.length > 0) {
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = new Cookie();
                int equalPos = cookies[i].indexOf('=');
                cookie.setName(cookies[i].substring(0, equalPos));
                cookie.setValue(cookies[i].substring(equalPos + 1));
                cookie.setDomain(serverUri.getHost()); // VERY IMPORTANT 
                cookie.setPath(serverUri.getPath()); // VERY IMPORTANT

                client.getState().addCookie(cookie);
            }
        }
    }
}

From source file:com.facebook.share.internal.ShareInternalUtility.java

/**
 * Creates a new Request configured to upload a photo to the specified graph path. The
 * photo will be read from the specified Uri.
 *
 * @param graphPath   the graph path to use
 * @param accessToken the access token to use, or null
 * @param photoUri    the file:// or content:// Uri to the photo on device.
 * @param caption     the user generated caption for the photo.
 * @param params      the parameters/*from www.  jav a 2  s . c  om*/
 * @param callback    a callback that will be called when the request is completed to handle
 *                    success or error conditions
 * @return a Request that is ready to execute
 * @throws FileNotFoundException
 */
public static GraphRequest newUploadPhotoRequest(String graphPath, AccessToken accessToken, Uri photoUri,
        String caption, Bundle params, Callback callback) throws FileNotFoundException {
    if (Utility.isFileUri(photoUri)) {
        return newUploadPhotoRequest(graphPath, accessToken, new File(photoUri.getPath()), caption, params,
                callback);
    } else if (!Utility.isContentUri(photoUri)) {
        throw new FacebookException("The photo Uri must be either a file:// or content:// Uri");
    }

    Bundle parameters = new Bundle();
    if (params != null) {
        parameters.putAll(params);
    }
    parameters.putParcelable(PICTURE_PARAM, photoUri);

    return new GraphRequest(accessToken, graphPath, parameters, HttpMethod.POST, callback);
}

From source file:Main.java

/**
 * Get a file path from a Uri.//from w  ww. jav  a  2s  .  co m
 * 
 * @param context
 * @param uri
 * @return
 * @throws URISyntaxException
 * 
 * @author paulburke
 */
public static String getPath(Context context, Uri uri) throws URISyntaxException {

    if (DEBUG)
        Log.d(TAG + " File -",
                "Authority: " + uri.getAuthority() + ", Fragment: " + uri.getFragment() + ", Port: "
                        + uri.getPort() + ", Query: " + uri.getQuery() + ", Scheme: " + uri.getScheme()
                        + ", Host: " + uri.getHost() + ", Segments: " + uri.getPathSegments().toString());

    if ("content".equalsIgnoreCase(uri.getScheme())) {
        String[] projection = { "_data" };
        Cursor cursor = null;

        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) {
            // Eat it
        }
    }

    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

From source file:eu.nubomedia.nubomedia_kurento_health_communicator_android.kc_and_communicator.util.FileUtils.java

public static String getRealPathFromURI(Uri contentUri, Context ctx) {
    String[] proj = { MediaStore.Video.Media.DATA };
    Cursor cursor = ((Activity) ctx).managedQuery(contentUri, proj, null, null, null);
    if (cursor != null) {
        int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
        cursor.moveToFirst();//from  www .ja va 2s .  co m
        String ret = cursor.getString(columnIndex);

        return ret;
    } else {
        return contentUri.getPath();
    }
}