http-request icon indicating copy to clipboard operation
http-request copied to clipboard

java.lang.OutOfMemoryError in java.lang.String.<init> when downloading json files

Open holoduke opened this issue 10 years ago • 4 comments

Some of my users are reporting out of memory errors. Is there a way to optimize the method ByteArrayOutputStream?

stack trace:

java.lang.RuntimeException: An error occured while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:299) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352) at java.util.concurrent.FutureTask.setException(FutureTask.java:219) at java.util.concurrent.FutureTask.run(FutureTask.java:239) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) at java.lang.Thread.run(Thread.java:856) Caused by: java.lang.OutOfMemoryError at java.lang.String.(String.java:255) at java.lang.String.(String.java:213) at java.io.ByteArrayOutputStream.toString(ByteArrayOutputStream.java:175) at com.github.kevinsawicki.http.HttpRequest.body(HttpRequest.java:1714) at com.github.kevinsawicki.http.HttpRequest.body(HttpRequest.java:1728) at loader.JSONAsyncCachedLoader$1.doInBackground(JSONAsyncCachedLoader.java:66) at loader.JSONAsyncCachedLoader$1.doInBackground(JSONAsyncCachedLoader.java:1) at android.os.AsyncTask$2.call(AsyncTask.java:287) at java.util.concurrent.FutureTask.run(FutureTask.java:234)

holoduke avatar Apr 08 '14 00:04 holoduke

Perhaps try using stream()/reader() instead, what JSON library are you using?

It probably supports streaming using a InputStreamReader and/or InputStream instead of parsing one big String.

kevinsawicki avatar Apr 08 '14 00:04 kevinsawicki

i am using Android's copy of JSONTokener Seems to be no way to insert a stream in that jsontokener lib. Only strings.

holoduke avatar Apr 08 '14 18:04 holoduke

I think you might workaround this by using JsonReader from the Gson library.

kevinsawicki avatar Apr 08 '14 18:04 kevinsawicki

The body(final String charset) method returns a String object so this can throw OOM exception I think. Have the same issue btw.

MateuszMlodawski avatar Jul 28 '14 12:07 MateuszMlodawski