• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Can't get filename from path

Hi,
Below is my code, which won't produce a filename from a given path. Wht am i missing?
Code:
//get file name from path
								String realFileName = existingFileName;
								int idx = realFileName.lastIndexOf("/");
								realFileName.substring(idx+1, realFileName.length());
 
Just a guess, but I think the problem might be in your substring statement:

Code:
realFileName.substring(idx+1, realFileName.length());

I'm assuming that realFileName contains a full path, but you just want the last node. Your idx should be OK, since you set it to the last instance of a "/" in the string, but your length argument will give the length of the entire path, not the last index. String positions in Java are 0 based, so

HELLO
is indexed like this:

01234
HELLO

Has a length of 5, but the last position is 4.
I'm surprised that you're not getting an index out of bounds exception. Or maybe you are, but Android is swallowing it.

In any case, try this fix:
Code:
String realFileName = existingFileName;
int lastIndex = realFileName.length() - 1;
int idx = realFileName.lastIndexOf("/");
realFileName.substring(idx+1, lastIndex);


HTH.
 
The problem is with this line of code:
realFileName.substring(idx+1, lastIndex);

Where the realFileName = /mnt/sdcard/DCIM/Camera/VID_20110809_094345.3gp, the realFileName, on using the substring function, remains the same. Interestingly, idx+1 = 23 and lastIndex = 46.

This is not a syntax error!!
 
Back
Top Bottom