android concat字符串OutOfMemoryError

android concat字符串OutOfMemoryError,android,string,stringbuffer,Android,String,Stringbuffer,我正在使用http请求库获取xml内容。库的侦听器具有以下功能: void onDataReceived(char[] data) { } void onRequestSucceeded() { } 请求url后,库将接收多个片段的数据,当接收到每个片段的数据时,将调用onDataReceived函数,并将这段数据作为参数传入,我必须将所有片段合并成一个字符串。请求完成后,将调用onrequestsucceed函数,字符串现在是xml的完整内容 我是这样做的: //init the re

我正在使用http请求库获取xml内容。库的侦听器具有以下功能:

void onDataReceived(char[] data)
{

}

void onRequestSucceeded()
{

}
请求url后,库将接收多个片段的数据,当接收到每个片段的数据时,将调用
onDataReceived
函数,并将这段数据作为参数传入,我必须将所有片段合并成一个字符串。请求完成后,将调用
onrequestsucceed
函数,字符串现在是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.
}
//init the result string
StringBuffer resStr = new StringBuffer("");

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

void onRequestSucceeded()
{
    //now the resStr is ready for parse.
}
问题是,有时我的android设备在浓缩字符串时会报告OutOfMemoryError。所以我改成了StringBuffer,如下所示:

//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.
}
//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”。我怀疑编码有问题,但我不知道如何解决

有什么想法吗?

试试
resStr.append(新字符串(数据))

使用

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

toString()将从StringBuffer转换为String对象

尝试这样编写smth:resStr.append(new String(data))我不知道你为什么会被否决,但你解决了我的问题。但我怀疑这是否也会导致OutOfMemoryError。我现在正在测试这是否会导致OutOfMemoryError。在大多数情况下,字符串连接的内存效率非常低,而不是使用
StringBuilder
string.format
。使用
StringBuilder
时,您不应该有内存problems@Wood这是否解决了您的
OutOfMemoryError