views:

78

answers:

1

Ok, I am trying to get the right three characters of a string in an Android app I'm writing.

Based on the research I've done in the SDK and online I should be able to use something like the following to do it.

millisecondsD = millisecondsD.substring(millisecondsD.length() -3, millisecondsD.length());

However, I get a force close whenever I try to use to use the code above. Am I just missing something super simple?

+2  A: 

You may need to check to see that the string is at least 3 characters long and not null first.

if (millesecondsD != null && millisecondsD.length() >=3)
    millesecondsD = milisecondsD.substring(milisecondsD.length() - 3);

Also, you can leave off the second parameter if you want.

Example:

String:
I'm a chunky monkey from funky town
01234567890123456789012345678901234
         10        20        30

So, in this case the last 3 chars are 34, 33, and 32. The indices you have in your code are correct.

jjnguy
Thank you, that fixed it. Was because for the first 100ms it isn't 3 characters long.
smccloud
@smccloud, glad to help. Make sure you click the green check mark to show that this answer is the one that solved your problem.
jjnguy