您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

SOAP响应非常大-Android-内存不足错误

SOAP响应非常大-Android-内存不足错误

有两种策略可以帮助您解决此问题:

下载时将SOAP XML流直接保存到磁盘。不要将其存储在内存中。 使用SAX样式的解析器对其进行解析,在该解析器中,您无需将整个DOM加载到内存中,而是以块的形式进行解析。 根据要处理的XML的类型,使用SAX解析器通常在代码上更难。您将不得不自己跟踪许多事情,并且将无法在DOM树的各个部分之间“跳转”。但是内存消耗将更低。

但是请注意,许多“高级”网络通信库通常将整个XML DOM加载到内存中,在这里可能就是这种情况。您可能必须自己创建和管理HTTP连接,然后手动解析结果。

只是更新,我发现AndroidHttpTransport中的“ call”方法在此行的内存不足-

           if (debug) {
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    byte[] buf = new byte[256];
                    while (true) {
                        int rd = is.read(buf, 0, 256);
                        if (rd == -1)
                            break;
                        bos.write(buf, 0, rd);
                    }
                    bos.flush();
                    buf = bos.toByteArray(); //Goes out of memory here
                    responseDump = new String(buf);
                    is.close();
                    is = new ByteArrayInputStream(buf);

调用toByteArray会占用大量内存,因此要解决此问题,而不是将响应转换为字节数组,我现在将其直接写入XML文件,并将其保存在我选择的位置。这里 -

if (debug) {
    FileOutputStream bos = new FileOutputStream("/data/data/com.mypackage.myapp/response.xml");
    byte[] buf = new byte[1048576];
    int current = 0; int i=0; int newCurrent = 0;
    while ((current = inputStream.read(buf)) != -1) {
        newCurrent = newCurrent + current;
    Log.d("current", "Current = " + current + " total = "+newCurrent+" i = "+i++);
                    bos.write(buf, 0, current);
                }
                bos.flush();
}

设备不再耗尽内存,并且我有一个自定义的解析方法,该方法采用此XML并将其写入数据库

其他 2022/1/1 18:21:57 有512人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶