I’m cursious about the soft and weak references in the Java environment. I have also read a bit about both topics. Just to sum up, the weak reference are as the name says, weak references to an object. This means that the reference to this object is easily collected by the GC. A weak reference is created this way:
WeakReference<SomeOtherRef> weakReference = new WeakReference(someOtherRef);
On the other hand a soft reference will stick around much longer than a weak reference. So my question is:
In my application, I have a custom adapter for a ListView This class will handle all the basic ListView stuff as handling clicks etc. When the user click on off the items in my list, a AsyncTask will be started.
convertView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
LoadCase loadCase = new LoadCase(position, holder);
loadCase.execute("");
}
});
For now I dont show any progressDialog, for one reason. The context object. My problem is that the Activity which will initialize the CustomAdapter holds many object, and I have to pass a reference to the Activity Context in order to show a ProgressDialog, this will cause memory leaks, yes, I have tried. Is it safe to apply the Weak/Soft reference to deal with this? A WeakReference can be, at some time, null..this will cause a NullPointerException when I try to initialize my ProgressDialog.
Yes, it’s a good idea to use a
WeakReferencehere, because the activity could be destroyed. You have to check if it’s null each time that you want to use it to avoid aNullPointerException. If it’s null, it means that the activity has been destroyed, and thus it usually doesn’t make sense to show aProgressDialog.Of course, the activity could be destroyed and recreated (for example because of an orientation change). If the
AsyncTasktakes long, this could have the problem that the progress bar is no longer shown. But the problem here would be using anAsyncTaskfor a long task, they are intended for short tasks.Also, remember that if you subclass
AsyncTaskas an inner class in theActivityclass, it will have a strong reference to the Activity, so using aWeakReferencewould be useless.