I have to display around 100 icons (each 50x50) in Button. I am downloading big png Image which contains all 100 icons, then I create each icon using Image.subImage()
method.
But my application getting OutOfMemoryError
.
I am thinking about 2 solution for this:
Which is the best solution? or do you have any other solution for this problem.
LWUIT is designed for small devices, and so should you design your code. So a big image is not a good idea.
You should really use seperate images. and only keep those in memory that you can see. Or you will keep running into outofmemory errors.
I would handle it like this. Get a cachemap. if you want an image, check if it isn't already in the cachemap. if it is, use the image from the cachemap if it isn't download it and put the image in the cachemap. when you're out of memory, remove the last image from the cachemap and download the new.
if (imageCache.get(url) != null) {
//#debug
System.out.println("Get cached image from: " + url);
asyncImage.setImage((Image) imageCache.get(url));
asyncImage.setQueued(false);
} else {
//#debug
System.out.println("Start download image from:" + url);
map.put(url, asyncImage);
ImageDownloadService d = new ImageDownloadService(url, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
NetworkEvent n = (NetworkEvent) evt;
Image image = (Image) n.getMetaData();
String url = n.getConnectionRequest().getUrl();
AsyncImage asyncImage = (AsyncImage) ImageManager.this.map.get(url);
map.put(url, asyncImage);
asyncImage.setImage(image);
map.remove(url);
imageCache.put(url, asyncImage.getImage());
asyncImage.setQueued(false);
if (Display.getInstance().getCurrent() instanceof AsyncLoadable) {
((AsyncLoadable) Display.getInstance().getCurrent()).asyncLoaded();
} else {
Display.getInstance().getCurrent().repaint();
}
//#debug
System.out.println("Retrieved image from:" + url);
}
});
d.addResponseCodeListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
NetworkEvent n = (NetworkEvent) evt;
String url = n.getConnectionRequest().getUrl();
AsyncImage asyncImage = (AsyncImage) ImageManager.this.map.get(url);
asyncImage.setQueued(false);
map.remove(n.getConnectionRequest().getUrl());
//#debug
System.out.println("Failed image from:" + url);
}
});
NetworkManager.getInstance().addToQueue(d);