Use the following method to get the file path from the Uri. Here you need to pass the context and the uri and it maintains the compatibility for pre-Kitkat.
public String getRealPathFromURI(Context context, Uri contentUri) {
String res = "";
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
} else {
Log.d(TAG, "Cursor is null");
return contentUri.getPath();
}
return res;
}
Updated for Camera : The above solution is working for Uri returned for the Gallery Intent. For the camera intent use the below code.
public File getOutputMediaFile() {
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir;
// If the externam directory is writable then then return the External
// pictures directory.
if (isExternalStorageWritable()) {
mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
.getAbsolutePath() + File.separator + IConstants.CUSTOM_PROFILE_PIC_PATH);
} else {
mediaStorageDir = Environment.getDownloadCacheDirectory();
}
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
return mediaFile;
}
Create a global variable selectedImage
for storing the image path.
private Uri getOutputMediaFileUri() {
File mediaFile = Utilities.getInstance().getOutputMediaFile();
selectedImage = mediaFile.getAbsolutePath();
return Uri.fromFile(mediaFile);
}
Now call the Camera intent using the following method.
public void dispatchCameraIntent(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// If there any applications that can handle this intent then call the intent.
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
Uri fileUri = getOutputMediaFileUri();
Log.d(TAG, "camera Uri : " + fileUri);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(takePictureIntent, CAMERA_PICKER);
}
}
In OnActivityResult
use the selectedImage
as the file path.