2013-12-11 60 views
0

我正在處理android上的http get request。ArrayList中的OutOfMemory錯誤。 Android

我從服務器收到大量的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 ""; 
    } 
+1

嘗試使用'StringBuilder'而不是'String'並檢查是否有幫助。 – Apoorv

+0

感謝您的回覆。我剛剛嘗試過,但沒有奏效。得到相同的錯誤。 – user2085965

+0

嘗試評論'newarr.add(解碼);'看看它是否仍然崩潰。 – Apoorv

回答

-1

一個ArrayList的最大容量(或任何類型的列表任何的)僅由JVM有可用的內存量的限制。

U可以使用BufferedReader,也可以使用Scanner而不是String。

否則,如果你仍然想使用字符串,然後嘗試增加JVM.據我所知,沒有辦法在運行時控制堆大小。

儘管可能沒有必要:您可以分別使用-Xms和-Xmx開關提供最小和最大堆大小。 (例如-Xms128m -Xmx512m)jvm將管理這些邊界內的實際堆大小。

嘗試根據您的使用情況

設置的限制更多REFFERENCE嘗試從

http://www.coderanch.com/t/614644/Performance/java/Arraylist-heapsize-memory-error

0

略知一二,你需要處理的數據流,而不是直接把它作爲一個字符串。以Gson Stream Reader爲例:

public List<Message> readJsonStream(InputStream in) throws IOException { 
    JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8")); 
    List<Message> messages = new ArrayList<Message>(); 
    reader.beginArray(); 
    while (reader.hasNext()) { 
     Message message = gson.fromJson(reader, Message.class); 
     messages.add(message); 
    } 
    reader.endArray(); 
    reader.close(); 
    return messages; 
} 

您可以將List視爲分析結果。如果您想顯示它,您也可以使用您正在使用的任何ListAdapter列表。