I am trying to copy a 5mb database file to data folder from raw folder of my application.
I can copy it some times successfully.But after that i cannot click on images, while clicking i am getting OutOfMemory-exception.
so am trying to clear heap memory. is there any way to do that.
private void copyFromZipFile() throws IOException{
InputStream is = mycontext.getResources().openRawResource(R.raw.dbfile);
// Path to the just created empty db
File outFile = new File(DB_PATH ,DB_NAME);
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFile.getAbsolutePath());
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));
try {
ZipEntry ze;
while ((ze = zis.getNextEntry()) != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int count;
while ((count = zis.read(buffer)) != -1) {
try
{
baos.write(buffer, 0, count);
Log.d("", "writing..."+buffer.toString());
}catch (Exception e) {
// TODO: handle exception
Log.v("","Error writing"+e );
}
}
baos.writeTo(myOutput);
}
} finally {
zis.close();
myOutput.flush();
myOutput.close();
is.close();
}
}
In your first
while-loop, you are recreating theByteArrayOutputStreamfor every iteration. You are not closing it and you don’t explicitly set it tonullafter you’re done, so this is a Memory-Leak because the garbage-collector can’t collect the instance.A better approach would be moving the creation of
baos,bufferandcountout of the loop and using thereset()-method on theByteArrayOutputStreamafter you wrote to theOutputStream.