Android Development: Loading image

In a previous post I talked about loading bitmaps. In this post I will tell something about caching the loaded resources. For this I created a little util class. To give you an example how to use it here is the code. I will explain it step by step.

When the View needs an image it calls the method ‘build’ (3).

It passes a Card object that specifies which card we want to load. We also need to tell the builder which color we need  ( two sides in this game remember? )

It will first check if bitmap belonging to the card specified already has been loaded in the past (20-26).  It therefore will get the correct cache (21-24) ( Yes I have 2 cache’s one for each side ). When the card has not been found in the cache it should be loaded (  5 and 6). Therefore we find the correct drawable (from the R object ) (29-32) and create a bitmap out of it (33-35). We scale it down using a scale matrix and we put the image back in the correct cache (37-41). After that we try to load it again (line 15-16).

By using this approach we asure the app that it will always be using the same instance of a particular bitmap.

I hope this will help you a bit developing your own game apps.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.