【发布时间】:2013-12-11 13:02:19
【问题描述】:
我正在处理 android 上的 http get 请求。
我从服务器收到大量 json 数据,字符串无法处理或存储该数据并出现 OutOfMemory 异常。
然后我尝试将它保存在 arrayList 中,它可以存储最大 Integer.Maximum 值。 但在 ~8970 位置存储时出现 OutOfMemory 异常。
这是我的链接,其中包含 json 数据。
http://ec2-50-19-105-251.compute-1.amazonaws.com/ad/Upload/getitemlist10122013035042.txt
这是我的代码:
ArrayList<String> newarr = new ArrayList<String>();
try {
URL url = new URL(urlFilePath);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
// urlConnection.setDoOutput(true);
// connect
urlConnection.connect();
// Stream used for reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
// create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0;
int check;
while ((bufferLength = inputStream.read(buffer)) > 0) {
String decoded = new String(buffer, 0, bufferLength);
newarr.add(decoded); // OutOfMemory Exception.
}
fileOutput.close();
buffer = null;
inputStream.close();
String path = file.getAbsolutePath();
return path;
} catch (final MalformedURLException e) {
e.printStackTrace();
return "";
} catch (final IOException e) {
e.printStackTrace();
return "";
} catch (final Exception e) {
System.out.println("EXCEPTION:: " + e.getMessage());
e.printStackTrace();
return "";
}
【问题讨论】:
-
尝试使用
StringBuilder而不是String并检查是否有帮助。 -
感谢您的回复。我刚才试过了,但没有奏效。得到同样的错误。
-
尝试注释掉
newarr.add(decoded);,看看它是否仍然崩溃。 -
你能追踪到哪个项目 id 出现内存不足错误吗?
-
为什么这里需要字符串中的数据,因为这是 json 数据。您需要提取 json 数据。你的场景有什么特殊情况吗?如果你只需要数据,那么你可以参考:tutorialspoint.com/json/json_java_example.htm
标签: android json arraylist out-of-memory http-get