Memory Leak in Android
<p>I have a problem related to Memory Leak. In my app I have to read 2MB data from a Video file, and the method related to same always called when the Activity's onCreate method called then the same statement which allocated 2MB byte array in the code, returns OutofMemory Exception frequently after 10 to 15 attempts because heap memory exceeds. The code is explained below (it is the part of my whole code): </p>

<pre><code>//Reading DRM video from sdcard
                File file = new File("/sdcard/TvAnyTime/watch/"+IDValue+".mp4");
                   try {
                          is = new FileInputStream(file);
                   } catch (FileNotFoundException e2) {
                          e2.printStackTrace();
                   }
                   //reading 2^21 bytes
                   fileData = new byte[2097152];
                   int read = 0;
                   while(read != fileData.length) {
                      try {
                    read += is.read(fileData, read, fileData.length - read);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                   }

                   //The finalHashPattern is then xored across the video file 2^10 times
                   for(int i=0;i&lt;2097152;i+=2048)
                   {
                    byte[] res = new byte[2048];
                    bytesafterXor = new byte[2048];

                    for(int j=0;j&lt;2048;j++)
                    {

                        res[j] = fileData[i+j];
                        bytesafterXor[j] = (byte)(res[j]^finalhash[j]);
                        finaldatafile[i+j] = bytesafterXor[j];
                    }

                    finalHashafterXor.add(bytesafterXor);

                   }
</code></pre>

<p>The statement <code>fileData = new byte[2097152];</code> is responsible for the OutOfMemory Exception because it is allocated every time when onCreate is called. Can we prevent the same by allocating each time a large memory? can we read it in chunks of data? Please suggest me the right solution regarding the same.</p>

<p>Thanks in advance.</p>
