Reputation: 1903
I have an app which I can select an image from the device Gallery. I need to get the real filepath of the file to upload the file to a remote server. I have this working successfully with images only, but I wish to expand my app to include any filetype. My current code fails when trying to get the filepath of a non image. My code so far:
String filepath = "";
try {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor != null && cursor.getCount() != 0) {
int column_index = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
filepath = cursor.getString(column_index);
}
}
catch(Exception e) {
Log.e("Path Error",e.toString());
}
I believe my problem lies with "MediaStore.Images.Media.DATA", but I am not sure what to replace it with to handle all file types.
UPDATE
OK, worked out that my code is 99% fine. It does work on multiple file types. The problem is with filenames which contain spaces. How do I handle this. I notice that the filepaths are url encoded ie spaces are replaced with "%20".
Upvotes: 1
Views: 1644
Reputation: 7938
Uri fileUri=Uri.fromfile(fileObject);
USE: setUrl(Uri.decode(fileUri));
Upvotes: 1
Reputation: 1903
Turns out problem was handling filenames which contained URL encoded spaces i.e "%20"
For anyone that is interested my adapted code is as follows:
String filepath = "";
String uriPath = uri.toString();
// Handle local file and remove url encoding
if(uriPath.startsWith("file://")) {
filepath = uriPath.replace("file://","");
try {
return URLDecoder.decode(filepath, "UTF-8");
}
catch (UnsupportedEncodingException e) {
e.printStackTrace()
}
}
try {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor != null && cursor.getCount() != 0) {
int column_index = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
filepath = cursor.getString(column_index);
}
}
catch(Exception e) {
Log.e("Path Error",e.toString());
}
return filepath;
Upvotes: 4