Search code examples
androidsubstringindexoutofboundsexceptionstring-function

unable to start activity:StringIndexOutOfBoundsException: String index out of range: -2


I am retriving data from table and display it in textview , i have break the string using breakString() method but in last two data that are starcast and director , its showing StringIndexOutOfBoundsException... as i have debug the app data are still inside the string but the debugging stops when it reaches to starcast...

breakString() method

   public void breakString(String str)
    {
        name=str.substring(1,str.indexOf(","));
        str= str.substring( name.length()+2, str.length(  ) );

        genre=str.substring(0,str.indexOf(","));
        str= str.substring( genre.length()+1, str.length(  ) );

        year=str.substring(0,str.indexOf(","));
        str= str.substring( year.length()+1, str.length(  ) );

        duration=str.substring(0,str.indexOf(","));
        str= str.substring( duration.length()+1, str.length(  ) );

        String str1 = str.substring(0,str.indexOf(","));
        rating=Double.valueOf(str1);

        str = str.substring( str1.length()+1, str.length() );
        review = str.substring(0,str.indexOf( "," ));
        str=str.substring(review.length()+1,str.indexOf(","));

        starcast = str.substring( 0, str.indexOf( "," ));
        str = str.substring( starcast.length()+1, str.indexOf(","));
       // str = str1.substring( starcast.length()+1, str.length()-1 );

        director = str;

    }

debug mode image

enter image description here

enter image description here

enter image description here

after this the debugging stops and nothing is being generted.


Solution

  • UPDATE

    Your problem is in the following line:

     str=str.substring(review.length()+1,str.indexOf(",")) //Original
     str=str.substring(review.length()+1,str.length()); // Should be
    

    The program crashed since the length of review is 45 and the indexOf the comma is 44.