Image path from Uri returns null - android

I'm trying to get the path of the selected file from gallery, but it is returning null and I don't know why. Every code I see uses the same approach, but it doesn't work for me. Here is my code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// LOAD_FILE_REQUEST is a global variable:
// private static final int LOAD_FILE_REQUEST = 1;
if (requestCode == LOAD_FILE_REQUEST && resultCode == RESULT_OK && data != null) {
if(data.getData() == null) {
System.out.println("NULL");
} else {
System.out.println("NOT NULL"); // <--- Printed
}
currImageURI = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(currImageURI, filePathColumn, null, null, null);
if(cursor.moveToFirst()){
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String yourRealPath = cursor.getString(columnIndex);
System.out.println("REAL PATH "+yourRealPath);
} else {
System.out.println("NO ROWS!!!"); // <-- Not printed
}
cursor.close();
}
}

Did you add the following line in your manifest ? =]
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Could you explain a little more what your problem is? Where are you getting a null?
In which Android version are you running this code? From Android 4.4 onwards, the filechooser which opens when you send the intent for picking up an image returns a relative uri, since it shows not only the files that are stored in your device but also the ones stored in the cloud. So, it could be happening that you're getting a relative URI and when you query for it's location on the device you're getting null, since the ContentResolver doesn't have the path of that file.
If that's the case (Actually even if you're not, since you should develop your app with compatibility for Android's new versions) i'd recommend you to use Content Resvolver to open a InputStream to get the file (openInputStream(Uri), since it will allow you to fetch a file from any location (both local and cloud).
I hope it helps :)

Well, here is how i do in my live wallpaper (Noiraude, have a look :P )
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case 100:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
#SuppressWarnings("unused")
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(
selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
sharedPreferences = getSharedPreferences("NLP_settings", 0);
Editor editor = sharedPreferences.edit();
editor.putString("key_bit", getPath(selectedImage));
editor.commit();
restartThis();
}
}
}
public String getPath(Uri uri) {
// just some safety built in
if (uri == null) {
return null;
}
// try to retrieve the image from the media store first
// this will only work for images selected from gallery
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();
return cursor.getString(column_index);
}
// this is our fallback here
return uri.getPath();
}

Related

Path of selected image is null

I am trying to get the real path of a URI.
First I start the gallery app through an intent:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select picture"), SELECT_IMAGE );
After that the onActivityResult gets called, where I try to get the absolut path of the URI.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (resultCode == RESULT_OK) {
Uri uri;
if (requestCode == SELECT_IMAGE) {
final Uri uri_data = data.getData();
// Get the path from the Uri
final String path = getPathFromURI(uri_data);
if (path != null) {
File f = new File(path);
uri = Uri.fromFile(f);
}
}
}
} catch (Exception e) {
Log.e("FileSelectorActivity", "File select error", e);
}
}
The uri_data contains "content://com.android.providers.media.documents/document/image%3A67", but the resulting path is null.
The pathFromUri method looks like this:
private String getPathFromURI(Uri contentUri) {
String res = null;
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
Here the column_index is 0, but cursor.getString returns null.
Why does this happen?
I have the permission android.permission.READ_EXTERNAL_STORAGE
EDIT:
So I want to take a picture through the camera app, and the user then chooses the image. So the file should be acutally stored on the phone (which is, since I am testing it on my phone)
EDIT:
Okey, the solution was to request the permissions at runtime...sorry guys

How to solve issue of path of any photo in gallery for kitkat and further versions?

I used this onActivityResult method to fetch photo from Gallery or camera
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == 0) {
finish();
photoFile = null;
theftimage.setImageResource(R.drawable.camera);
}
if (requestCode == REQUEST_TAKE_PHOTO) {
theftimage.setVisibility(View.VISIBLE);
setPic();
}
if (requestCode == SELECT_PICTURE) {
// Get the url from data
if(resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
if (null != selectedImageUri) {
// Get the path from the Uri
String path; //= getPathFromURI(selectedImageUri);
path = ImageFilePath.getPath(getApplicationContext(), selectedImageUri);
String filename=path.substring(path.lastIndexOf("/")+1);
etFileName.setText(filename);
Log.i(TAG, "Image Path : " + path);
// Set the image in ImageView
theftimage.setImageBitmap(BitmapFactory.decodeFile(path));
}
}
}
}
and its method for fetching path
public String getPathFromURI(Uri contentUri) {
String res = null;
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return contentUri.getPath();
}
error is
02-28 11:00:18.488: E/HAL(24576): hw_get_module_by_class: module name gralloc
02-28 11:00:18.488: E/HAL(24576): hw_get_module_by_class: module name gralloc
its giving me error of path in kitkat and further versions. Can you solve this? Help will be appriciated.
You do not need a path if all that you want is putting the selected file in a ImageView.
One statement will do for all Android versions:
theftimage.setImageBitmap(BitmapFactory.decodeStream(
getContentResolver().openInputStream(data.getData())));
Please try the following code:
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
String imgDecodableString;
if(cursor==null) {
imgDecodableString= selectedImage.getPath();
}
else {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
}
}
imgDecodableString will contain the final path of the image and you can set the picture in your ImageView as :
theftimage.setImageBitmap(BitmapFactory.decodeFile(imgDecodableString));

Android How to Load an Audio file from the sdcard/file manager and play it

I'm developing an app, and in that app I have one button, named 'choose sound'. When user will click this button, he/she should be asked to choose any audio file from the file manager/memory.
So, I know that for this, I'll have to use Intent.Action_GetData. I'm doing the same:
//code start
Intent intent = new Intent();
intent.setType("audio/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,1);
#Override
protected void onActivityResult(int requestCode,int resultCode,Intent data){
if(requestCode == 1){
if(resultCode == RESULT_OK){
//the selected audio.
Uri uri = data.getData();
int SoundID=soundPool.Load(uri.toString(), 1);
//SoundPool is already constructed and is working perfectly for the resource files
PlaySound(SoundID);
//PlaySound method is already defined
}
}
super.onActivityResult(requestCode, resultCode, data);
}
//end of code
but it's not working
Now, in OnActivityResult, I'm not getting that how to load the proper URI of the file selected by user, because before Android 4.4, it returns the different URI and after Android 4.4 it returns the different URI on intent.GetData();. Now, what I have to do?
Also, I know that for playing the audio file, I'll have to use SoundPool, and I have the code for that too, in fact it's working fine for the resource/raw/audio files, but how to load/play files in SoundPool from this URI?
In your onActivityResult(), do the following changes:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && data != null)
{
String realPath = null;
Uri uriFromPath = null;
realPath = getPathForAudio(YourActivity.this, data.getData());
uriFromPath = Uri.fromFile(new File(realPath)); // use this uriFromPath for further operations
}
}
Add this method in your Activity:
public static String getPathForAudio(Context context, Uri uri)
{
String result = null;
Cursor cursor = null;
try {
String[] proj = { MediaStore.Audio.Media.DATA };
cursor = context.getContentResolver().query(uri, proj, null, null, null);
if (cursor == null) {
result = uri.getPath();
} else {
cursor.moveToFirst();
int column_index = cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);
result = cursor.getString(column_index);
cursor.close();
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally {
if (cursor != null) {
cursor.close();
}
}
return result;
}
Hope It will do your job. You can play audio using MediaPlayer class also
You can put below codes in your project when you want to select audio.
Intent intent_upload = new Intent();
intent_upload.setType("audio/*");
intent_upload.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent_upload,1);
And override onActivityResult in the same Activity, as below
#Override
protected void onActivityResult(int requestCode,int resultCode,Intent data){
if(requestCode == 1){
if(resultCode == RESULT_OK){
//the selected audio.
Uri uri = data.getData();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
Try to get the path :
//method to get the file path from uri
public String getPath(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;
}
then load it :
s2 = soundPool.load(YOU_PATH, PRIORITY);

import images from gallery into fragment

im trying to implement a fragment inside a navigation slider. I need to create a button in 1 of my fragments to import images from my default gallery. I have tried many codes online, but they don't seem to be working.
It depend on android version you are using if you test your app in android 6.0 than you should ask permission at runtime else image is not returned by android.
For Pre-Marshmallow you can use code:
Intent pickIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");
startActivityForResult(pickIntent, 0);
and then override method
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, requestCode, data);
try {
// When an Image is picked
if (requestCode == 0 && resultCode == Activity.RESULT_OK && null != data) {
Uri selectedImage = data.getData();
image.setImageBitmap(BitmapFactory.decodeFile(getRealPathFromURI(selectedImage)));
} else
new ShowErrorToast(getActivity(), "Hey! your Android phone is busy");
} catch (Exception e) {
}
}
than use method to get path of image
public String getRealPathFromURI(Uri data) {
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(data
, filePathColumn, null, null, null);
String picturePath = "";
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
}
return picturePath;
}
For Marshmallow you should ask for permission runtime and follow above code

How to save a selected Uri pic to drawable?

I am trying to set the picture that the user chooses from their gallery, by using Uri, as their background for an app, but I cant quite figure it out. One thing that I tried doing was straight up setting the background to the uri, but it fails do to compatibility mismatch. How can I do this, either by programmatically setting the drawable or any other way at at all?
Here is what I have tried
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == 1) {
if (intent != null && resultCode == RESULT_OK) {
Uri selectedImage = intent.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 filePath = cursor.getString(columnIndex);
cursor.close();
if (bmp != null && !bmp.isRecycled()) {
bmp = null;
}
bmp = BitmapFactory.decodeFile(filePath);
imageView.setBackground(selectedImage);//error here
//imageView.setBackgroundResource(0);//originally this, but this crashes also
imageView.setImageBitmap(bmp);
}
}
}
Check out this link Retrieve drawable resource from Uri
try {
InputStream inputStream = getContentResolver().openInputStream(yourUri);
yourDrawable = Drawable.createFromStream(inputStream, yourUri.toString() );
imageView.setImageDrawable(yourDrawable);
} catch (FileNotFoundException e) {
yourDrawable = getResources().getDrawable(R.drawable.default_image);
}

Categories

Resources