0
protected Void doInBackground(Void... voids) {

...

ABV = elem.select("td > span.muted").text();
Log.d("myLOG_ABV", ABV);
Log.d("myLOG_ABVlength", String.valueOf(ABV.length()));

/*String temp_ABV = ABV.substring(ABV.length()-6, ABV.length());*/

... }

Result

D/myLOG_ABV: Russian River Brewing Company American Wild Ale | 7.50% D/myLOG_ABVlength: 55

and then, I cancled the annotation code.

...

ABV = elem.select("td > span.muted").text();
Log.d("myLOG_ABV", ABV);
Log.d("myLOG_ABVlength", String.valueOf(ABV.length()));

***String temp_ABV = ABV.substring(ABV.length()-6, ABV.length());***

...

Result

Caused by: java.lang.StringIndexOutOfBoundsException: length=0; index=-6

Why am I getting StringIndexOutOfBoundsException error in this substring method?

I got the result that 'ABVlength : 55' in my code with annotation.

But after cancellation of annotation, I got StringIndexOutOfBoundsException.

Seriously, I am fighting with this code for 7hours 30minutes.

wook767
  • 3
  • 1
  • 2
    Perhaps this code is executed multiple times, and in some of them `ABV` is empty. – Eran Dec 09 '18 at 11:50
  • The exception message says that you get it because the length of your string is 0. Why it’s 55 once and 0 another time — is impossible to tell from the code you have posted. – Ole V.V. Dec 09 '18 at 12:03
  • Closely related: [java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 exception](https://stackoverflow.com/questions/39077303/java-lang-indexoutofboundsexception-index-0-size-0-exception) – Ole V.V. Dec 09 '18 at 12:05
  • 1
    @Eran / Thanks Eran. It was perfectly right. This code is in the FOR sentence. I found that one of values is empty. So I got this error. Yesterday, I modified the code, and then I fixed it. Thanks a lot man. – wook767 Dec 10 '18 at 04:06

1 Answers1

1

So we have:

***String temp_ABV = ABV.substring(ABV.length()-6, ABV.length());***

Caused by: java.lang.StringIndexOutOfBoundsException: length=0; index=-6

How can you get an index of -6 in this situation? ABV must have zero length, i.e. "".

It may be the case that ABV should have at least six characters, but that indicates a bug elsewhere.

What to do?

First and foremost, validate your inputs.

Somewhere you would normally want something like:

if (abv.length() < 6) {
    throw new IllegalArgumentException("...");
}

Next find where that value is coming from and fix the bug.

Looks like you're parsing some kind of external document. In this case you may want the handling to be more lenient:

int abvLen = abv.length();
int abvEndIndex = abvLen - 6;
if (abvEndIndex < 0) {
    log.error("ABV length less than 6", abv);
    abvEndIndex = 0;
}
String abvEnd = abv.substring(abvEndIndex, abvLen);
Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
  • Thanks Tom. My code was in the FOR sentence. I found that one of values is empty. So I got this error. Yesterday, I modified the code. And then I fixed it. Thanks for sincere reply. :) – wook767 Dec 10 '18 at 04:11