2014-06-05 59 views
0

我正在使用http請求庫來獲取xml內容。的lib的監聽器具有以下功能:android concat字符串OutOfMemoryError

void onDataReceived(char[] data) 
{ 

} 

void onRequestSucceeded() 
{ 

} 

請求的URL後,LIB將獲得多塊中的數據,在接收到每塊數據時,該onDataReceived函數將被調用,而這塊的數據將作爲參數傳入,並且我必須將所有片段連接成一個字符串。在請求完成後,onRequestSucceeded函數將被調用,並且字符串現在是xml的完整內容。

我做這樣的:

//init the result string 
String resStr = new String(""); 

void onDataReceived(char[] data) 
{ 
    resStr += new String(data); 
} 

void onRequestSucceeded() 
{ 
    //now the resStr is ready for parse. 
} 

的問題是,有時我的Android設備報告的OutOfMemoryError concating該字符串。所以我改成StringBuffer的是這樣的:

//init the result string 
StringBuffer resStr = new StringBuffer(""); 

void onDataReceived(char[] data) 
{ 
    resStr.append(data); 
} 

void onRequestSucceeded() 
{ 
    //now the resStr is ready for parse. 
} 

但resStr.toString()給了我喜歡 「@bsdawevas」 怪異的內容。我懷疑編碼有問題,但我不知道如何解決它。

任何想法?

+0

嘗試寫水木清華這樣的:resStr.append(新的字符串(數據)) –

回答

0

嘗試resStr.append(new String(data));

+0

我不知道你爲什麼拒絕投票,但你解決了我的問題。但我懷疑這是否會導致OutOfMemoryError。 – Wood

+0

我正在測試,如果這可能會導致OutOfMemoryError現在。 – Wood

+0

字符串連接在大多數情況下非常無效,而使用'StringBuilder'或'String.format'。使用'StringBuilder'你不應該有內存問題 –

0

使用

String str = resStr.toString(); 
System.out.println(str); 

的toString()將StringBuffer的轉換爲String對象