Android: Out of Memory error StringBuilder

后端 未结 3 555
灰色年华
灰色年华 2020-12-09 12:08

In my app, I fetching data from the server in the form of JSON. The data is around 1.5 MB. The app works but sometimes it crashes while fetching data from server giving Out

相关标签:
3条回答
  • 2020-12-09 12:19

    If you do not have enough memory to store your string you can: free some memory, reduce memory consumtion and do not store string in memory.

    In your case you need:

    • memory to store response (around 1.5+mb)
    • memory for string builder (around 1.5+mb)
    • memory for resulting string (around 1.5+mb continious memory, very bad)
    • BufferedReader/InputStreamReader...etc. (some kilos)

    Options:

    1. Convert response to a String without string builder. It will save 1+mb.
    2. Read response as a stream and convert it to a String without string builder. Request/Response entity streaming. It will save around 3mb
    3. Do not convert response to a string. Read it as stream and save to a file or db, or give a stream to streaming JSON parser.
    4. Free as much memory as you can before sending your post request and start praying that everything will be alright.
    0 讨论(0)
  • 2020-12-09 12:35

    Just add this to the <application /> tag in your manifest:

    android:largeHeap="true"
    
    0 讨论(0)
  • 2020-12-09 12:41

    Try like this,

    private String sendPostRequest(String url, List<NameValuePair> params)
            throws Exception {
        String ret = null;
        BufferedReader bufferedReader = null;
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost request = new HttpPost(url);
    
        try {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params);
            request.setEntity(entity);
    
            HttpResponse response = httpClient.execute(request);
            bufferedReader = new BufferedReader(new InputStreamReader(response
                    .getEntity().getContent()));
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
               ret =ret +line;
            }
            bufferedReader.close();
    
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return ret;
    }
    
    0 讨论(0)
提交回复
热议问题