2012-08-30 59 views
0

我不知道爲什麼,但如果我使子字符串應用程序崩潰!子字符串崩潰

下面的代碼:

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))) 
       ); 
} 
+0

你確保你的字符串titolo_da_inserire的最小長度爲35個字符? –

+0

不知道......這也許是問題所在?在PHP這不是一個問題,但在這裏它可能是..讓我檢查 – Zak

+0

崩潰後發佈stacktrace –

回答

0

實際聲明一樣,

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())+"..."; 
+0

還有一件事:檢查字符串是否爲空... –

+0

@BorisStrandjev - 只檢查'空'左.. ..空字符串將是'長度爲0'。 – user370305

+0

對不起,我誤解了你的代碼。但是,實際上,對我來說有意義的是: '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())+「...」; ' –

0

如果您前字符串具有小於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); 

}