1

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".

4
  • like audio and video i can give u is it ohk for u Commented Dec 4, 2013 at 8:50
  • It needs to be able to handle any kind of file eg image/audio/video pdf docx etc etc ... Commented Dec 4, 2013 at 9:02
  • What is the error you get? Also any .DATA in MediaStore is just "_data" because they all inherit that from MediaColumns - that should not be your problem Commented Dec 4, 2013 at 9:24
  • You are correct it isn't that which is causing the app to crash, but it is not getting the filepath from uri: filepath returns a null value Commented Dec 4, 2013 at 9:48

2 Answers 2

4

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; 
Sign up to request clarification or add additional context in comments.

Comments

1
Uri fileUri=Uri.fromfile(fileObject); USE: setUrl(Uri.decode(fileUri)); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.