[英]OutOfMemoryError while JSON parsing in android
我使用下面的代碼來解析從Web獲取的JSON字符串,(30,000條記錄)
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost(params[0]);
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
HttpEntity entity = response.getEntity();
try {
inputStream = entity.getContent();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"),8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
result = sb.toString();
我在下面的代碼中收到OutofMemory錯誤
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
如何擺脫這個錯誤。當json字符串非常龐大時,會發生此錯誤,因為它包含大約30,000條記錄的數據。
在這方面的任何幫助都非常感謝..
Android為每個應用程序設置了內存上限(幾乎所有手機中都有16 MB,而一些新的平板電腦有更多)。 應用程序應確保它們的實時內存限制保持在該級別以下。
因此,我們不能保持一個大字符串,比如超過1MB,因為應用程序的總活動內存使用量可能會超過該限制。 請記住,總內存使用量包括我們在應用程序中分配的所有對象(包括UI元素)。
因此,您唯一的解決方案是使用Streaming JSON解析器,它可以獲取數據。 那就是你不應該在String對象中保持完整的字符串。 一種選擇是使用Jackson JSON解析器 。
編輯:Android現在支持API級別11的JSONReader 。從未使用它,但它似乎要走了......
如果數據文件太大,則無法將其全部讀取到內存中。
讀取一行,然后將其寫入本機文件。 不要使用StringBuilder來保存內存中的所有數據。
嘗試在chuncks中導入數據,例如每次1000條記錄。 希望你不會遇到這個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.