-6

I am trying to split a Spanish string in Java. And i got the following exception:

ArrayIndexOutOfBoundsException

The string i am trying to split is: pin pon es un muñeco

Debuger shows the following error:

java.lang.ArrayIndexOutOfBoundsException: length=1; index=1

Splitting statement:

String[] splitVideoTitle = tvTitle.getText().toString().split("\\s+"); 

The line of code that caused the above index exception is in this line of code:

String firstWords = splitVideoTitle[0] + " " + splitVideoTitle[1];

Any suggestions to avoid this exception is appreciated.

Thanks

Ajmal Muhammad
  • 685
  • 7
  • 25
Androider
  • 105
  • 11

3 Answers3

4

just add a test :

   String firstWords = "";
if(splitVideoTitle.length>1){
        firstWords = splitVideoTitle[0] + " " + splitVideoTitle[1];
    }
    else firstWords=splitVideoTitle[0];
0

That error simply means that the array splitVideoTitle has only one element at index splitVideoTitle[0]. I assume that this is due to the fact the the full video title does not contain the split character, or the split character is at the begin or end of the title.

Try this:

String firstWords;
if (splitVideoTitle.length >= 2) {
    firstWords = splitVideoTitle[0] + " " + splitVideoTitle[1];
} else if (splitVideoTitle.length == 1) {
    firstWords = splitVideoTitle[0];
}
Illuminat
  • 94
  • 3
0

I tried your code by assigning the value received by Textview to another variable and your code works

    String a = "pin pon es un muñeco";
    String[] splitVideoTitle = a.split("\\s+");
    String firstWords = splitVideoTitle[0] + " " + splitVideoTitle[1];
    Log.i("TAG", "first word" + firstWords);

may be "tvTitle.getText().toString()" this is creating the issue, or returning null..please check the values returned by Textview using LOG.

Meenal
  • 2,879
  • 5
  • 19
  • 43