【问题标题】:android concat string OutOfMemoryErrorandroid concat string OutOfMemoryError
【发布时间】:2014-06-05 07:26:12
【问题描述】:

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

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。所以我改成这样的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”。我怀疑编码有问题,但我不知道如何解决。

有什么想法吗?

【问题讨论】:

  • 试着这样写:resStr.append(new String(data))

标签: android string stringbuffer


【解决方案1】:

试试resStr.append(new String(data));

【讨论】:

  • 我不知道你为什么被否决,但你解决了我的问题。但我怀疑这是否也会导致 OutOfMemoryError。
  • 我现在正在测试这是否会导致 OutOfMemoryError。
  • 字符串连接在大多数情况下内存效率非常低,而不是使用StringBuilderString.format。使用StringBuilder,您应该不会有内存问题
  • @Wood 是否整理出了你的 OutOfMemoryError
【解决方案2】:

使用

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-16
    • 1970-01-01
    • 1970-01-01
    • 2016-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多