2014-06-05 58 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对象