在android中从服务器下载数据时出现异常内存异常

时间:2013-05-10 06:38:54

标签: java android

我必须从服务器下载大约6000条记录到sqlite数据库中。记录显示为JSON个对象。在使用BufferedReader检索它们时,我得到一个错误,因为内存不足异常。我搜索了很多网站但找不到合适的答案。请提出一些最佳解决方案。

我的代码是:

URL url = new URL("myurl");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
//getting error here
line = in.readLine();
System.out.println(line);
JSONArray outerArray = (JSONArray) JSONSerializer.toJSON(line);
System.out.println("size : " + outerArray.size());

我得到了这个致命的例外 -

                 E/AndroidRuntime(616): java.lang.OutOfMemoryError: [memory exhausted]

3 个答案:

答案 0 :(得分:1)

下载文件的大小太大而无法保存在内存中

尝试这样做

    // download the file
                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream();

                byte data[] = new byte[1024];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....

                    output.write(data, 0, count);
                }

                output.flush();
                output.close();
//

更多解释see this

<强> 另外

你应该使用gson或者gson或者jackson。有了Jackson,您也可以使用混合方法。这会显着减少你的内存消耗,因为只有被解析的json部分被加载到内存中。

https://sites.google.com/site/gson/gson-user-guide

答案 1 :(得分:0)

您似乎试图一次性下载整个JSON数组并消耗大量内存。而不是做readLine,尝试在固定数量的缓冲区块(例如:1024)中读取输入,如果它足以制作一个或多个JSON数组,则解析它。然后继续阅读下一个块。这样你就不会留下你的记忆空间

请注意,只有在您可以保证JSON数组元素不会超过1024字节时,此方法才有效。否则请尝试相应地调整此数字/使用可调数据结构

答案 2 :(得分:0)

堆内存可能很少提供给您的应用

您需要通过清单中的条目注册较大堆的应用

<application android:largeHeap="true"> </application>

http://developer.android.com/guide/topics/manifest/application-element.html#largeHeap

相关问题