1

I'm trying to implement upload feature in app. In case of small files it is working fine. But when I tried to upload large files, it throws out of memory error.

@Override
public byte[] getBody() {
   File file = new File(filepathnew);
   //  int size = (int) file.length();
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   try{
    BufferedInputStream reader = new BufferedInputStream(new FileInputStream (filepathnew));
    int read;
    byte[] buffer = new byte[32000];
    while ((read = reader.read(buffer)) >= 0) {
       baos.write(buffer, 0, read);
    }
    } catch (FileNotFoundException fnf){
       fnf.printStackTrace();
    } catch (IOException ioe){
       ioe.printStackTrace();
    }
       byte[] everything  = baos.toByteArray();
       return everything;
}

Error log is

E/AndroidRuntime: FATAL EXCEPTION: Thread-2667 Process: in.codme.cloudapp, PID: 15914
java.lang.OutOfMemoryError: Failed to allocate a 131008012 byte allocation with 16777216 free bytes and 50MB until OOM
at java.io.ByteArrayOutputStream.expand(ByteArrayOutputStream.java:91)
at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:201)
at in.codme.cloudapp.FileBrowserActivity$19.getBody(FileBrowserActivity.java:866)
at com.android.volley.toolbox.HurlStack.addBodyIfExists(HurlStack.java:236)
at com.android.volley.toolbox.HurlStack.setConnectionParametersForRequest(HurlStack.java:214)
at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:106)
at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:93)
at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:105)
07-15 16:47:02.869 15914-15916/in.codme.cloudapp W/art: Suspending all threads took: 49.184ms
Yasin Kaçmaz
  • 6,573
  • 5
  • 40
  • 58
Alen Abraham
  • 109
  • 1
  • 2
  • 11
  • Do you have `android:largeHeap="true"` in your `Manifest.xml` – Yasin Kaçmaz Jul 15 '16 at 11:28
  • 2
    Why are you writing to a baos ? In this way you put all in memory. Instead you shoud do away with the baos and upload directly by writing to the output stream. So in that loop you read in the buffer and ten write the buffer like you have now but then to the outputstream directly. So do away with getBody() and change to uploadBody(); – greenapps Jul 15 '16 at 11:39
  • 1
    @YasinKacmaz, "largeHeap" is reserved for apps that REALLY need this kind of behavior, using it to patch issues in your app is a bad practice. Most apps should do just fine with the default heap size. – Egor Jul 15 '16 at 11:42
  • @Egor thanks for reply , i know but think maybe it will help him. I think efficient way is using `FileInputStream` – Yasin Kaçmaz Jul 15 '16 at 11:48
  • 1
    @Alen Abraham i see a couple of questions that using FileInputStream and output stream , one of them : [upload-large-file-in-android-without-outofmemory-error](http://stackoverflow.com/questions/9630430/upload-large-file-in-android-without-outofmemory-error) – Yasin Kaçmaz Jul 15 '16 at 11:50

0 Answers0