2012-11-01 69 views
4

我使用下面的代碼來解析JSON字符串從網絡獲取,(30000條記錄)的OutOfMemoryError而JSON解析Android中

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條記錄的數據。

在這方面的任何幫助,高度讚賞..

+0

類似的問題在這裏解決 http://stackoverflow.com/questions/6173396/parse-data-of-size-about-3mb-using-json-in-android?rq=1 – tdgtyugdyugdrugdr

回答

1

如果數據文件太大,無法將其所有的讀取到內存。

讀一行,然後將其寫入本機文件。不要使用StringBuilder來將所有數據保存在內存中。

0

嘗試導入您的數據塊,如1000條記錄每次。希望你不會遇到這個問題。

3

Android爲每個應用程序強加了一個內存上限(幾乎所有手機都是16 MB,一些較新的平板電腦有更多)。應用程序應確保它們的實時內存限制低於該級別。

因此,我們無法保留一個大的字符串,比如超過1MB,因爲應用程序的實時內存使用總量可能會超過此限制。請記住,總內存使用量包括我們在應用程序中分配的所有對象(包括UI元素)。

因此,您唯一的解決方案是使用Streaming JSON解析器,該解析器會根據數據處理數據。那就是你不應該在String對象中保持完整的字符串。一種選擇是使用Jackson JSON parser

編輯:Android現在支持JSONReader從API級別11.從未使用過它,但它似乎去..

0

我解決了這個問題,此library的方式。 有一個很好的教程here

有了這個,你將繞過轉換entity.getContent()爲字符串,這將解決您的問題。

InputStream inputStream = entity.getContent(); 
JsonReader reader = Json.createReader(inputStream); 
JsonObject jsonObject = reader.readObject(); 
return jsonObject;