I am ( a beginner android) trying to get the real path (ex: image_name.jpg etc) of Image selected from the gallery by the user.
Here is the code snippet:
if (requestCode == SELECT_FILE) {
Uri selectedImage = data.getData();
Bitmap bitmapImage;
try {
bitmapImage =decodeBitmap(selectedImage );
photoImage = (ImageView) findViewById(R.id.photoImage);
photoImage.setImageBitmap(bitmapImage);
photoName = (TextView) findViewById(R.id.designPhoto);
File thePath = new File(getRealPathFromURI(selectedImage));
photoName.setText(getRealPathFromURI(selectedImage));
} catch (Exception e) {
e.printStackTrace();
}
}
private String getRealPathFromURI(Uri contentURI) {
String thePath = "no-path-found";
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(contentURI, filePathColumn, null, null, null);
if(cursor.moveToFirst()){
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
thePath = cursor.getString(columnIndex);
}
cursor.close();
return thePath;
}
but I am not getting anything in the photoName textView also tried lots of codes and guides but with no sucess.
but when I tried it with
photoName.setText(selectedImage.getPath());
I am getting
/document/image:n (where n=any numbers) ex:/document/image:147
but I want a proper file name or path ex: image_name.jpg or /path/image_name.png
trying it from last 3 hours, it would be great if anyone could help me out. humble Thanks in advance.
I got it working using
MediaStore.Images.Media.DISPLAY_NAME
updated and working code might help others:
private String getRealPathFromURI(Uri contentURI) {
String thePath = "no-path-found";
String[] filePathColumn = {MediaStore.Images.Media.DISPLAY_NAME};
Cursor cursor = getContentResolver().query(contentURI, filePathColumn, null, null, null);
if(cursor.moveToFirst()){
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
thePath = cursor.getString(columnIndex);
}
cursor.close();
return thePath;
}
Related
I have two applications, one contains content provider and other app receives data using content resolver. If i add any data form provider that should be displayed from receiver in second app, this is the expected functionality.But after adding data once I remove first app from stack then second app displays null cursor,If I keep first app in stack, then second app displays correct value .(This issue only comes in one plus devices)
code snippet where cursor value coming null is,
Cursor c = getContentResolver().query(CONTENT_URI, null, null, null,
null);
may be it will help you
private String uriToFilename(Uri uri) {
String path = null;
if (Build.VERSION.SDK_INT < 11) {
path = getRealPathFromURI_BelowAPI11(this, uri);
} else if (Build.VERSION.SDK_INT < 19) {
path = getRealPathFromURI_API11to18(this, uri);
} else {
path = getRealPathFromURI_API19(this, uri);
}
return path;
}
BelowAPI11
public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index
= cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
API11to18
public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
String result = null;
CursorLoader cursorLoader = new CursorLoader(
context,
contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
if (cursor != null) {
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
}
return result;
}
API19
public static String getRealPathFromURI_API19(Context context, Uri uri) {
Log.e("uri", uri.getPath());
String filePath = "";
if (DocumentsContract.isDocumentUri(context, uri)) {
String wholeID = DocumentsContract.getDocumentId(uri);
Log.e("wholeID", wholeID);
// 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);
}
cursor.close();
}
} else {
filePath = uri.getPath();
}
return filePath;
}
Enable Don’t optimize inside Settings to resolve one plus issue.
Settings –> Battery –> Battery Optimization –> Your App –> Don’t optimize
enter image description here
Environment.getExternalStorageDirectory().toString() + "/DCIM/Camera"
I tried this code for find the location of camera storage images but its give only "DCIM" image location.but some devices not store always in "DCIM" folder so how could i find out storage location?
Try this:
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
Try to below code work for my app perfect :-
Uri selectedImageUri = data.getData();
String selectedImagePath = getRealPathFromURI(selectedImageUri);
Method:-
public String getRealPathFromURI(Uri contentUri)
{
try
{
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
catch (Exception e)
{
return contentUri.getPath();
}
}
I have 2 Buttons in My activity. 1st One: Upload Image 2nd One: Get Uploaded image name. Now i have Pressed "Upload Image" Button and selected a image from gallery and that image is displayed in ImageView. Then i Pressed 2nd Button "Get Uploaded Image Name" and a Toast will display the name of that image which is in ImageView. I want the code of this only.
Uri uri = data.getData();
String[] projection = { MediaStore.Images.Media._ID, MediaStore.Images.Media.BUCKET_ID,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
ArrayList<String> ids = new ArrayList<String>();
mAlbumsList.clear();
if (cursor != null) {
while (cursor.moveToNext()) {
Album album = new Album();
int columnIndex = cursor.getColumnIndex(MediaStore.Images.Media.BUCKET_ID);
album.id = cursor.getString(columnIndex);
if (!ids.contains(album.id)) {
columnIndex = cursor.getColumnIndex(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
album.name = cursor.getString(columnIndex);
columnIndex = cursor.getColumnIndex(MediaStore.Images.Media._ID);
album.coverID = cursor.getLong(columnIndex);
mAlbumsList.add(album);
ids.add(album.id);
} else {
mAlbumsList.get(ids.indexOf(album.id)).count++;
}
}
cursor.close();
This is the way that you can retrieve the image name.. :
Uri selectedImage = data.getData();
String selectedImageName = selectedImage.getLastPathSegment();
I am getting null in contenturi in samsung phones while capturing photo from camera but rest of others phones its working fine.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try
{
if (requestCode == IMAGE_CAPTURE) {
if (resultCode == RESULT_OK){
Uri contentUri = data.getData();
if(contentUri!=null)
{
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
imageUri = Uri.parse(cursor.getString(column_index));
}
tempBitmap = (Bitmap) data.getExtras().get("data");
mainImageView.setImageBitmap(tempBitmap);
isCaptureFromCamera = true;
}
}
This above code works in some mobile but does not work in samsung mobile in my case, so I implemented the common logic for all devices.
After capturing the photo from camera, I implement a logic using Cursor and iterate the cursor to get the path of last captured photo from camera.The below code works fine on any device.
Cursor cursor = getContentResolver().query(Media.EXTERNAL_CONTENT_URI, new String[]{Media.DATA, Media.DATE_ADDED, MediaStore.Images.ImageColumns.ORIENTATION}, Media.DATE_ADDED, null, "date_added ASC");
if(cursor != null && cursor.moveToFirst())
{
do {
uri = Uri.parse(cursor.getString(cursor.getColumnIndex(Media.DATA)));
photoPath = uri.toString();
}while(cursor.moveToNext());
cursor.close();
}
Hi i am also facing this issue to like I am checking app on MOTO G its not working but on Samsung devices its working So i do Below coding please check:-
Uri selectedImageUri = data.getData();
try {
selectedImagePath = getPathBelowOs(selectedImageUri);
} catch (Exception e) {
e.printStackTrace();
}
if (selectedImagePath == null) {
try {
selectedImagePath = getPathUpperOs(selectedImageUri);
} catch (Exception e) {
e.printStackTrace();
}
}
public String getPathBelowOs(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
/**
* Getting image from Uri
*
* #param contentUri
* #return
*/
public String getPathUpperOs(Uri contentUri) {// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(contentUri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Images.Media.DATA };
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, sel,
new String[] { id }, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
}
I'am invoking default gallery app from my app to select any photo. Below is my code to get the selected image path from gallery. It's working fine for all the photos except few. When i select any of PICASA uploaded photos from Gallery, app is force closing. Please help me.
Inside onActivityResult()....
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String selectedPhotoPath = cursor.getString(columnIndex).trim(); <<--- NullPointerException here
cursor.close();
bitmap = BitmapFactory.decodeFile(selectedPhotoPath);
......
Sometimes data.getData(); returns null depending on the app you use to get the picture. A workaround for this is to use the above code in onActivityResult:
/**
*Retrieves the path of the image that was chosen from the intent of getting photos from the galery
*/
Uri selectedImageUri = data.getData();
// OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();
// MEDIA GALLERY
String filename = getImagePath(selectedImageUri);
String chosenPath;
if (filename != null) {
chosenPath = filename;
} else {
chosenPath = filemanagerstring;
}
The variable chosenPath will have the correct path of the chosen image. The method getImagePath() is this:
public String getImagePath(Uri uri) {
String selectedImagePath;
// 1:MEDIA GALLERY --- query from MediaStore.Images.Media.DATA
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
selectedImagePath = cursor.getString(column_index);
} else {
selectedImagePath = null;
}
if (selectedImagePath == null) {
// 2:OI FILE Manager --- call method: uri.getPath()
selectedImagePath = uri.getPath();
}
return selectedImagePath;
}
Please try below code
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
Uri targetUri = data.getData();
textTargetUri.setText(targetUri.toString());
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(targetUri));
....
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
OR
Please check below link
OR
How to pick an image from gallery (SD Card) for my app?
String ImagePath = "";
private void setImageFromGallery(Intent data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = this.getContentResolver().query(selectedImage, filePathColumn, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Log.i("choosepath", "image" + picturePath);
ImagePath = picturePath;
} else {
ImagePath = selectedImage.getPath(); // Add this line
}
ImageView imgView = (ImageView) findViewById(R.id.imgView);
imgView.setImageBitmap(BitmapFactory.decodeFile(imagePath));
Bitmap bitmap = Utilities.rotateImage(pictureImagePath);
}
Current Android system (first version -> 2.3.3 -> even 4.4.2) looks like not able to selected multiple files, so you need custom gallery to do that.
Afer researched so many times, I found Custom Camera Gallery library can help you do that thing already.