How to get the file path from URI? [duplicate] - android

This question already has answers here:
Get filename and path from URI from mediastore
(32 answers)
Closed 10 years ago.
Please find my code below. I need to get the file path of the pdf document, selected by the user from SDcard. The issue is that the URI.getPath() returns:
/file:///mnt/sdcard/my%20Report.pdf/my Report.pdf
The correct path is:
/sdcard/my Report.pdf
Please note that i searched on stackoverflow but found the example of getting the filePath of image or video, there is no example of how to get the filepath in case of PDF?
My code , NOT all the code but only the pdf part:
public void openPDF(View v)
{
Intent intent = new Intent();
//intent.setType("pdf/*");
intent.setType("application/pdf");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Pdf"), SELECT_PDF_DIALOG);
}
public void onActivityResult(int requestCode, int resultCode, Intent result)
{
if (resultCode == RESULT_OK)
{
if (requestCode == SELECT_PDF_DIALOG)
{
Uri data = result.getData();
if(data.getLastPathSegment().endsWith("pdf"))
{
String pdfPath = data.getPath();
}
else
{
CommonMethods.ShowMessageBox(CraneTrackActivity.this, "Invalid file type");
}
}
}
}
Can some please help me how to get the correct path from URI?

File myFile = new File(uri.toString());
myFile.getAbsolutePath()
should return u the correct path
EDIT
As #Tron suggested the working code is
File myFile = new File(uri.getPath());
myFile.getAbsolutePath()

Here is the answer to the question
here
Actually we have to get it from the sharable ContentProvider of Camera Application.
EDIT . Copying answer that worked for me
private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(mContext, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}

Related

ImageView not populating from file path

I can't get my ImageViews to update from either URI or file path - they just don't show an image
Intent to capture image:
Intent photo = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(photo, 1);
On ActivityResult
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
Uri imageUri = data.getData();
filePath = getRealPathFromURI(this, imageUri);
}
GetRealPathFromURI class:
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
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);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
It then inserts 'filePath' from onActivityResult in to a db
Retrieving from db and updating ImageViews
imgfilepath[y] = cursorc.getString(cursorc.getColumnIndex("IMAGE"));
imgFile[y] = new File(imgfilepath[y]);
Uri uri = Uri.fromFile(imgFile[y]);
String path = uri.getPath();
mImage.setImageURI(uri);
I've tried so many different ways to setImageBitmap etc which haven't worked (I can't remember all of them) - Can anyone see why this is not showing the image?
The image is in emulated storage and not the SD card.
EDIT:
I've added EXTRA_OUTPUT tag but I can't see the image in DDMS anywhere & the camera does not exit after taking the picture/accepting the image
Intent photo = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
final File root = new File(Environment.getExternalStorageDirectory() + File.separator + "MyDir" + File.separator);
root.mkdirs();
final String fname = "img_"+ System.currentTimeMillis() + ".jpg";
final File sdImageMainDirectory = new File(root, fname);
mImageUri = Uri.fromFile(sdImageMainDirectory);
photo.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
startActivityForResult(photo, 1);
Uri imageUri = data.getData();
ACTION_IMAGE_CAPTURE does not return a Uri.
The image is in emulated storage
Perhaps that one camera app does, in which case that camera app has a bug, to go along with the return-a-Uri bug.
There are thousands of Android device models. These ship with hundreds of different camera apps pre-installed, and there are hundreds more available from the Play Store and elsewhere. Many will have ACTION_IMAGE_CAPTURE implementations. Most should follow the documented protocol. None should save the image for your request, because you did not tell the camera app where to save the image.
Either:
Provide a location, via EXTRA_OUTPUT, for the camera app to save the image to, then load the image from that location, or
Use data.getExtra("data") to get a Bitmap that represents a thumbnail-sized image, if you do not provide EXTRA_OUTPUT

Android: Directory and file chooser android library

I'm using aFileChooser android library project in my app to select the file from external storage. but it doesn't seem to pick only directory to let user select the download location to download the files.
Is there any android library project which support both pick file and pick directory?
I understand there are multiple questions have been answered here either for file chooser or directory chooser but after extensive search I couldn't find one for both directory and file chooser.
Any help would be appreciated.
I have no android library project, but you can simply make your own file chooser with the next code. This code will ask you to chose a file browser, when you select a file in the file browser you'll get the path in the onActivityResult function in the FilePath String.
Create this public:
private static final int ACTIVITY_CHOOSE_FILE = 3;
When a button is clicked you can call this:
Intent chooseFile;
Intent intent;
chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.setType("file/*");
intent = Intent.createChooser(chooseFile, "Choose a file");
startActivityForResult(intent, ACTIVITY_CHOOSE_FILE);
You can catch the directory with this code :
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
String path = "";
if(requestCode == ACTIVITY_CHOOSE_FILE)
{
Uri uri = data.getData();
String FilePath = getRealPathFromURI(uri);
}
}
public String getRealPathFromURI(Uri contentUri) {
String [] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query( contentUri, proj, null, null,null);
if (cursor == null) return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
Edit:
If you do not want to use an external file browser, you can import this android library into your project:
https://code.google.com/p/afiledialog/

Get Audio Recorded by RecorderAudio Activity

I've searched a lot, but didnt found the solution to capture the audio recorded by Recorder Activity.
private void onClick() {
Intent intent = new Intent();
intent.setAction(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
try {
startActivityForResult(intent, IDF_ACTIVITY_AUDIO);
} catch (ActivityNotFoundException e) {
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == IDF_ACTIVITY_AUDIO) {
final String folder = Environment.getExternalStorageDirectory() + "/myAudio/";
String pathAudio = data.getData().getPath();
Uri audioUri = data.getData();
// pathAudio == /external/audio/media/8
// audioUri /external/audio/media/8
File audio = new File(folder + "audioTest");
//how to getAudio from data and save in audio file???
}
}
}
This two methods show my problem. With the Uri object returned by Native Recorder Activity, I need to save the audio in my own file.
Anyone know how to do this??
Can you indicate some links to fully understand how Uri works?
EDIT:
The String '/external/audio/media/8' do not represent valid path. What this string means?
Look at Start audio recording with intent of MediaStore.Audio.Media.RECORD_SOUND_ACTION and Using Intent to record audio,
These both tutorial give you a URI after recording audio now using that uRI you can get absolute path of that file and you can also write that file where you want using simple File I/O operation.
EDIT:
new File(new URI(androidURI.toString()));
Hi i am also searching for storing the recorded files in my own folder
But you can get the exact file name using
String absolutepath=getRealPathFromURI(audioUri);
public String getRealPathFromURI(Uri contentUri)
{
String[] proj = { MediaStore.Audio.Media.DATA};
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = `enter code here`cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
cursor.moveToFirst();
System.out.println("absolutepath audiopath in getRealPathFromURI : "+cursor.getString(column_index));
return cursor.getString(column_index);
}

Store picture on sd directory problem

I'm using the follow code to take a picture using the native camera:
private File mImageFile;
private String mTempImagePath;
public static Uri imageUri;
public void imageFromCamera() {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
Log.d("fototemp", "No SDCARD");
} else {
mImageFile = new File(Environment.getExternalStorageDirectory()+File.separator+"testFolder", "Pic"+System.currentTimeMillis()+".jpg");
imageUri = Uri.fromFile(mImageFile);
DataClass dc = (DataClass) getApplicationContext();
File tempFile = new File(Environment.getExternalStorageDirectory()+File.separator+"testFolder");
Uri tempUri = Uri.fromFile(tempFile);
dc.setString(DataClass.IMAGE_PATH, tempUri.toString());
Log.d("fototemp", "ImagePath: " + tempUri.toString());
mTempImagePath = mImageFile.getAbsolutePath();
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mImageFile));
startActivityForResult(intent, 0);
}
}
The ImagePath I print out in the imageFromCamera() method is: 4file:///file%3A/mnt/sdcard/testFolder
Now when I try to access these foto's by using managedQuery I get a different directory.
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI.toString() gives content://media/external/images/thumbnails
What is the difference between these 2 paths? And how can I get the managedQuery to go to the testFolder map to look for pictures?
edit:
I'm trying to connect:
Uri phoneUriII = Uri.parse(Environment.getExternalStorageDirectory()+File.separator+"testFolder");
imagecursor = managedQuery(phoneUriII, img, null,null, MediaStore.Images.Thumbnails.IMAGE_ID + "");
but this code crashes
Sorry don't really understand your question.
Just send this as the URI path.
Environment.getExternalStorageDirectory()+File.separator+"testFolder"
Also
Check if you have the permissions to write to the sd card.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
I'm using this function in a couple of projects and it works fine.
/**
* Retrieves physical path to the image from content Uri
* #param contentUri
* #return
*/
private String getRealImagePathFromURI(Uri contentUri) {
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);
}

Android: How to Upload Images from the SD Card

In my application, I want to upload the images from the SD card with restricting the user to upload only less than 2mb. How can I accomplish this?
Use following steps:
1) Use the following intent to open gallery with images:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 101);
2) Receive the Uri of selected file in onActivityResult func.
if (requestCode == 101 && data != null) {
Uri selectedImageUri = data.getData();
} else {
Toast toast = Toast.makeText(this, "No Image is selected.",
Toast.LENGTH_LONG);
toast.show();
}
Convert the Uri into a path using following func:
public String getPath(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);
}
After that create a File object from the path and then check the size of file:
File mFile = new File(path);
int length = mFile.length(); // file size in bytes
After that you can simply put an if-else to check the file size restriction and then use multi-part upload process for uploading the file.
you can use this article for multipart upload.

Categories

Resources