Suppose you had a long list of images. As the user scrolled down you
load the images from the net, and then display them.
To avoid having to reload the images again if the user scrolls back
up, you put the images in a cache (probably something like a
Map<String, Drawable>)
However because it is a long list you don't want to run into an out of
memory situation if the user scrolls very far down and lots of images
are put in the cache.
So instead of storing the Drawables directly in the map, you create a
Map<String, WeakReference<Type>> (although I would use SoftReference
for the purpose described here).
This means that if Android is going to encounter an out of memory
situation it will clear all of the Soft/Weak references (and thus
hopefully avoid running out of memory). You will have to load the
images again since your cache has been cleared, but this is far better
than your application running out of memory and crashing.
So you do something like:
// caching an image
Map<String, SoftReference> cache = new HashMap<String,
SoftReference<Drawable>>();
cache.put("http://mysite.com/images/1.jpg", new
SoftReference<Drawable>.put(myDrawable));
// retrieve an image
if (cache.containsKey(url)) {
// looks like we have this image cached
Drawable drawable = cache.get(url).get();
if (drawable == null) {
// the softreference has been cleared by the GC, reload the
image
} else {
// softreference is still valid, got our image
}
}
Essentially a weak reference is a weaker reference than a soft
reference - the GC should free weak references to regain memory before
soft references.
I think that's (mostly) correct, hope it helps.
On Jul 22, 6:48 pm, GodsMoon <[email protected]> wrote:
> Google just posted a new blog post
> onhttp://android-developers.blogspot.com/2010/07/multithreading-for-per....
> I understand the AsyncTask and I'm even using one in a list with
> images already.
>
> But I don't understand what a WeakReference is. I gather is is a
> garbage collector directive, but I thought I didn't need to manage
> garbage collection on Android.
>
> http://developer.android.com/reference/java/lang/ref/WeakReference.html
> isn't as helpful as I was hoping it would be.
--
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en