Wednesday, June 15, 2016

Get Path from Uri and get Uri from path in Android

In android taking pic from camera or pic image from sd card, we get response in OnActivityResult  in form of data (Intent) so get path from data we use this method.

Uri imageUri = data.getData();
public String getPathFromUri(Uri uri) {
    String[] projection = {MediaStore.Images.Media.DATA};
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    if (cursor == null) return null;
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    String s = cursor.getString(column_index);
    cursor.close();
    return s;
}

// after taking pic or pic from sd card back to this method
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// get here uri and convert to path
}

sometime we have only sd card path and want to convert Uri then use below method 

private Uri getUriFromPath(String filePath) {
    long photoId;
    Uri photoUri = MediaStore.Images.Media.getContentUri("external");
    String[] projection = {MediaStore.Images.ImageColumns._ID};
    Cursor cursor = getContentResolver().query(photoUri, projection, 
MediaStore.Images.ImageColumns.DATA + " LIKE ?", new String[] { filePath }
, null);
    cursor.moveToFirst();
    int columnIndex = cursor.getColumnIndex(projection[0]);
    photoId = cursor.getLong(columnIndex);
    cursor.close();
    return Uri.parse(photoUri.toString() + "/" + photoId);
}

No comments :

Post a Comment