I am trying to create an application that use to download image from server and show it into listview. The problem that I made was the leak of memory and make my application crash. I was searching in Android blog such as this link, it show a great idea but it still not enough to do it with multiple thread. Some device of android can work with it but some device can only handle in the single thread and sometimes it cannot work at all.
My application has many activity and each of them has a Listview that need to display image quick as possible. Through the Google IO 2012 they use buffer to save the original image to SD Card and it solve the problem Leak memory but it make loading so slow since the image that need to download was too big.
My question is: Is there any way to scale image together with write image to SD Card? I figure out some possible solution is to use Skip byte in the inputstream object and I was able to find Width and Height also Bit per pixel of the image that I need to download.
The following code was use in Google IO 2012 and it work well with multiple threading, in my case I have 4 thread running in the background.
private void downloadAndWriteFile(final String url, final File file) throws OutOfMemoryError {
BufferedOutputStream out = null;
try {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setDoInput(true);
conn.connect();
final InputStream in = new BufferedInputStream(conn.getInputStream(), IO_BUFFER_SIZE_BYTES); // buffer size 1KB
out = new BufferedOutputStream(new FileOutputStream(file), IO_BUFFER_SIZE_BYTES);
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
out.close();
conn.disconnect();
}
catch (Exception e) {
Log.e(TAG, "!!downloadAndWriteFile " + e.getMessage());
file.delete();
}
}
1) use the following code before setting your images to free the native object associated with this bitmap, and clear the reference to the pixel data. It simply allows it to be garbage collected if there are no other references.
2) use this method to reduce the size of bitmap in memory:
This code download the images without using bitmap factory,its not working in emulator,use any android phones
activity_main.xml
finalscreen.xml
You can use this.
}