Android: Out of Memory error StringBuilder

后端 未结 3 556
灰色年华
灰色年华 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.

提交回复
热议问题