无法启动 activity:StringIndexOutOfBoundsException:字符串索引超出范围:-2

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

我正在从 table 中检索数据并将其显示在 textview 中,我已经使用 breakString() 方法断开了字符串,但在最后两个 starcast 和 director 数据中,它显示了 StringIndexOutOfBoundsException... 因为我调试了应用程序数据仍在字符串中但是当它到达 starcast 时调试停止...

breakString() 方法

   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;

    }

调试模式图片

enter image description here

enter image description here

enter image description here

在此之后调试停止并且没有任何生成。

更新

您的问题在以下行:

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

由于review的长度为45,逗号的indexOf为44,程序崩溃了。

简单单元测试后:

str = str.substring(review.length()+1, str.length());
...
str = str.substring(starcast.length()+1, str.length());

不过,我强烈推荐StringTokenizer