子串崩溃

时间:2012-08-30 10:47:11

标签: java substring

我不知道为什么,但如果我创建一个子串,应用程序崩溃了!

以下是代码:

while(data_mio.moveToNext())
{
    titolo_da_inserire=data_mio.getString(prodotto);
    titolo_da_inserire=titolo_da_inserire.substring(0,35)+"...";
    personList.add( new Prodotto_per_lista(
                      R.drawable.freccia_1, titolo_da_inserire,
                      Integer.parseInt(data_mio.getString(id_immagine)))
                  );
}

2 个答案:

答案 0 :(得分:0)

实际上声明String titolo_da_inserire喜欢,

String titolo_da_inserire = "";

现在,在使用subString() 之前检查字符串的长度 titolo_da_inserire

if(titolo_da_inserire.length() >= 35)
 titolo_da_inserire = titolo_da_inserire.substring(0,35)+"...";
else
 titolo_da_inserire = titolo_da_inserire.substring(0,titolo_da_inserire.length())+"...";

答案 1 :(得分:0)

如果您的titolo_da_inserire 字符串少于35,那么它会抛出java.lang.StringIndexOutOfBoundsException您应用崩溃的方式

<强>示例

String st ="string";

st = st.substring(0,15); // throws exception String index out of range

System.out.println(st);

所以你需要检查长度

if(st.length()>15)

{

st = st.substring(0,15);

System.out.println(st);

}