Java Code Examples for android.net.Uri#getPath()

The following examples show how to use android.net.Uri#getPath() . 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: ZipStorageDocumentFile.java    From ToGoZip with GNU General Public License v3.0 10 votes vote down vote up
public static String getPath(final Context context, final Uri uri) {
    // DocumentProvider
    if (DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                final File externalStorageDirectory = Environment.getExternalStorageDirectory();

                // split[1] results in index out of bound exception in storage root dir
                if (split.length == 1) return externalStorageDirectory.toString();
                return externalStorageDirectory + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }
    }
    if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }
    return null;
}
 
Example 2
Source File: CommonUtil.java    From ClipCircleHeadLikeQQ with Apache License 2.0 6 votes vote down vote up
/**
 * Try to return the absolute file path from the given Uri  兼容了file:///开头的 和 content://开头的情况
 *
 * @param context
 * @param uri
 * @return the file path or null
 */
public static String getRealFilePathFromUri( final Context context, final Uri uri ) {
	if ( null == uri ) return null;
	final String scheme = uri.getScheme();
	String data = null;
	if ( scheme == null )
		data = uri.getPath();
	else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
		data = uri.getPath();
	} else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
		Cursor cursor = context.getContentResolver().query( uri, new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null );
		if ( null != cursor ) {
			if ( cursor.moveToFirst() ) {
				int index = cursor.getColumnIndex( MediaStore.Images.ImageColumns.DATA );
				if ( index > -1 ) {
					data = cursor.getString( index );
				}
			}
			cursor.close();
		}
	}
	return data;
}
 
Example 3
Source File: MimeUtils.java    From Conversations with GNU General Public License v3.0 6 votes vote down vote up
public static String guessMimeTypeFromUri(Context context, Uri uri) {
    // try the content resolver
    String mimeType;
    try {
        mimeType = context.getContentResolver().getType(uri);
    } catch (Throwable throwable) {
        mimeType = null;
    }
    // try the extension
    if ((mimeType == null || mimeType.equals("application/octet-stream")) && uri.getPath() != null) {
        String path = uri.getPath();
        int start = path.lastIndexOf('.') + 1;
        if (start < path.length()) {
            final String guess = MimeUtils.guessMimeTypeFromExtension(path.substring(start));
            if (guess != null) {
                mimeType = guess;
            }
        }
    }
    // sometimes this works (as with the commit content api)
    if (mimeType == null) {
        mimeType = uri.getQueryParameter("mimeType");
    }
    return mimeType;
}
 
Example 4
Source File: DownloadHandler.java    From JumpGo with Mozilla Public License 2.0 6 votes vote down vote up
private static boolean isWriteAccessAvailable(@NonNull Uri fileUri) {
    File file = new File(fileUri.getPath());

    if (!file.isDirectory() && !file.mkdirs()) {
        return false;
    }

    try {
        if (file.createNewFile()) {
            //noinspection ResultOfMethodCallIgnored
            file.delete();
        }
        return true;
    } catch (IOException ignored) {
        return false;
    }
}
 
Example 5
Source File: WebViewLocalServer.java    From webview-local-server with Apache License 2.0 6 votes vote down vote up
private static Uri parseAndVerifyUrl(String url) {
    if (url == null) {
        return null;
    }
    Uri uri = Uri.parse(url);
    if (uri == null) {
        Log.e(TAG, "Malformed URL: " + url);
        return null;
    }
    String path = uri.getPath();
    if (path == null || path.length() == 0) {
        Log.e(TAG, "URL does not have a path: " + url);
        return null;
    }
    return uri;
}
 
Example 6
Source File: MessageListPanelEx.java    From NIM_Android_UIKit with MIT License 6 votes vote down vote up
public void setChattingBackground(String uriString, int color) {
    if (uriString != null) {
        Uri uri = Uri.parse(uriString);
        if (uri.getScheme().equalsIgnoreCase("file") && uri.getPath() != null) {
            ivBackground.setImageBitmap(getBackground(uri.getPath()));
        } else if (uri.getScheme().equalsIgnoreCase("android.resource")) {
            List<String> paths = uri.getPathSegments();
            if (paths == null || paths.size() != 2) {
                return;
            }
            String type = paths.get(0);
            String name = paths.get(1);
            String pkg = uri.getHost();
            int resId = container.activity.getResources().getIdentifier(name, type, pkg);
            if (resId != 0) {
                ivBackground.setBackgroundResource(resId);
            }
        }
    } else if (color != 0) {
        ivBackground.setBackgroundColor(color);
    }
}
 
Example 7
Source File: PickFileActivity.java    From android-intents with Apache License 2.0 5 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == PICK_FILE && resultCode == RESULT_OK) {
        Uri file = data.getData();
        String path = file.getPath();

        pathView.setText(path);
    }
    super.onActivityResult(requestCode, resultCode, data);
}
 
Example 8
Source File: AudioActivity.java    From AJCPlayer with Apache License 2.0 5 votes vote down vote up
public String getRealPathFromURI(Uri contentUri) {
    String videoPath = contentUri.getPath();

    try{
        String[] proj = { MediaStore.Video.Media.DATA };
        //Cursor cursor = activity.managedQuery(contentUri, proj, null, null,
        //null);
        Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
        Log.i("cursor", "upload-->" + cursor);
        Log.i("contentUri", "upload-->" + contentUri);
        Log.i("proj", "upload-->" + proj);
        int position=0;

        if (cursor !=null && cursor.moveToPosition(position)) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

            Log.i("column_index", "Upload-->" + column_index);
            videoPath = cursor.getString(column_index);  //I got a null pointer exception here.(But cursor hreturns saome value)
            Log.i("videoPath", "Upload-->" + videoPath);
            cursor.close();

        }

    } catch(Exception e){
        Log.e("MainActivity", e.toString());
        return contentUri.getPath();
    }

    return videoPath;

}
 
Example 9
Source File: FileUtils.java    From MediaPickerPoject with MIT License 5 votes vote down vote up
public static String getRealPathFromURI(Context context,Uri contentURI) {
    String result;
    Cursor cursor = context.getContentResolver().query(contentURI, null, null, null, null);
    if (cursor == null) { // Source is Dropbox or other similar local file path
        result = contentURI.getPath();
    } else {
        cursor.moveToFirst();
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        result = cursor.getString(idx);
        cursor.close();
    }
    return result;
}
 
Example 10
Source File: FileUtils.java    From odyssey with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Method to extract a path from a given uri with optional arguments.
 *
 * @param context       The application context.
 * @param uri           The given {@link Uri}.
 * @param selection     Optional selection statement.
 * @param selectionArgs Optional selection arguments.
 * @return The extracted path or null if the scheme of the uri is not supported.
 */
private static String extractPathFromUri(final Context context, final Uri uri, final String selection, final String[] selectionArgs) {
    if (CONTENT_SCHEME.equalsIgnoreCase(uri.getScheme())) {
        // handle content uri

        String[] projection = {MediaStore.Audio.Media.DATA};

        final Cursor cursor = PermissionHelper.query(context, uri, projection, selection, selectionArgs, null);

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                final int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);

                final String filePath = cursor.getString(columnIndex);

                cursor.close();

                return filePath;
            }
        }

        return null;
    } else if (FILE_SCHEME.equalsIgnoreCase(uri.getScheme())) {
        // handle file uri

        return uri.getPath();
    } else {
        // currently we don't support any other uri scheme

        return null;
    }
}
 
Example 11
Source File: UriUtils.java    From arca-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static Uri removeQueryParameter(final Uri uri, final String removeParam) {
	final String baseUri = uri.getScheme() + "://" + uri.getAuthority() + uri.getPath();
	final Uri.Builder builder = Uri.parse(baseUri).buildUpon();
	final Set<String> params = getQueryParameterNames(uri);
	for (final String param : params) {
		if (!param.equals(removeParam)) {
			final String value = uri.getQueryParameter(param);
			builder.appendQueryParameter(param, value);
		}
	}
	return builder.build();
}
 
Example 12
Source File: FilePickUtils.java    From ml with Apache License 2.0 5 votes vote down vote up
private static String getPathDeprecated(Context ctx, Uri uri) {
    if( uri == null ) {
        return null;
    }
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = ctx.getContentResolver().query(uri, projection, null, null, null);
    if( cursor != null ){
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
    return uri.getPath();
}
 
Example 13
Source File: PreviewActivity.java    From sandriosCamera with MIT License 5 votes vote down vote up
private void saveCroppedImage(Uri croppedFileUri) {
    try {
        File saveFile = new File(previewFilePath);
        FileInputStream inStream = new FileInputStream(new File(croppedFileUri.getPath()));
        FileOutputStream outStream = new FileOutputStream(saveFile);
        FileChannel inChannel = inStream.getChannel();
        FileChannel outChannel = outStream.getChannel();
        inChannel.transferTo(0, inChannel.size(), outChannel);
        inStream.close();
        outStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 14
Source File: FileUtils.java    From AndJie with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Convert Uri into File.
 * 
 * @param uri
 * @return file
 */
public static File getFile(Uri uri) {
	if (uri != null) {
		String filepath = uri.getPath();
		if (filepath != null) {
			return new File(filepath);
		}
	}
	return null;
}
 
Example 15
Source File: GlideUtils.java    From zom-android-matrix with Apache License 2.0 5 votes vote down vote up
public static void loadImageFromUri(Context context, Uri uri, ImageView imageView) {
    if(SecureMediaStore.isVfsUri(uri))
    {
        try {
            info.guardianproject.iocipher.File fileImage = new info.guardianproject.iocipher.File(uri.getPath());
            if (fileImage.exists())
            {
                FileInputStream fis = new info.guardianproject.iocipher.FileInputStream(fileImage);
                Glide.with(context)
                        .load(fis)
                        .apply(noDiskCacheOptions)
                        .into(imageView);
            }
        }
        catch (Exception e)
        {
            Log.w(LOG_TAG,"unable to load image: " + uri.toString());
        }
    }
    else if (uri.getScheme() != null && uri.getScheme().equals("asset"))
    {
        String assetPath = "file:///android_asset/" + uri.getPath().substring(1);
        Glide.with(context)
                .load(assetPath)
                .apply(noDiskCacheOptions)
                .into(imageView);
    }
    else
    {
        Glide.with(context)
                .load(uri)
                .into(imageView);
    }
}
 
Example 16
Source File: GiftCardViewActivityTest.java    From gift-card-guard with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void startWithoutParametersCaptureReceiptCreateGiftCard() throws IOException
{
    ActivityController activityController = Robolectric.buildActivity(GiftCardViewActivity.class).create();
    activityController.start();
    activityController.visible();
    activityController.resume();

    // Add something that will 'handle' the media capture intent
    registerMediaStoreIntentHandler();

    Activity activity = (Activity)activityController.get();

    checkAllFields(activity, "", "", "", "", false);

    // Complete image capture successfully
    Uri imageLocation = captureImageWithResult(activity, R.id.captureButton, true);

    checkAllFields(activity, "", "", "", "", true);

    // Save and check the gift card
    saveGiftCardWithArguments(activity, "store", "cardId", "value", imageLocation.getPath(), true);

    // Ensure that the file still exists
    File imageFile = new File(imageLocation.getPath());
    assertTrue(imageFile.isFile());

    // Delete the file to cleanup
    boolean result = imageFile.delete();
    assertTrue(result);
}
 
Example 17
Source File: ImageUtils.java    From chat21-android-sdk with GNU Affero General Public License v3.0 5 votes vote down vote up
public static String getRealPathFromURI(ContentResolver contentResolver, Uri contentUri) {
    Cursor cursor = contentResolver.query(contentUri, null, null, null, null);
    if (cursor == null) {
        return contentUri.getPath();
    } else {
        cursor.moveToFirst();
        int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        return cursor.getString(index);
    }
}
 
Example 18
Source File: ActivityCrop.java    From iGap-Android with GNU Affero General Public License v3.0 5 votes vote down vote up
private String getRealPathFromURI(Uri contentURI) {
    String result;
    Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
    if (cursor == null) { // Source is Dropbox or other similar local file path
        result = contentURI.getPath();
    } else {
        cursor.moveToFirst();
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        result = cursor.getString(idx);
        cursor.close();
    }
    return result;
}
 
Example 19
Source File: Editor.java    From editor with GNU General Public License v3.0 5 votes vote down vote up
private void newFile()
{
    textView.setText("");
    changed = false;

    file = getNewFile();
    Uri uri = Uri.fromFile(file);
    path = uri.getPath();

    setTitle(uri.getLastPathSegment());
}
 
Example 20
Source File: SecureMediaStore.java    From Zom-Android-XMPP with GNU General Public License v3.0 4 votes vote down vote up
public static void exportContent(String mimeType, Uri mediaUri, java.io.File exportPath) throws IOException {
    String sourcePath = mediaUri.getPath();

    copyToExternal( sourcePath, exportPath);
}