Tobias Moe Thorstensen
Tobias Moe Thorstensen

Reputation: 8981

Soft reference and weak reference

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.

Upvotes: 1

Views: 784

Answers (1)

Pablo
Pablo

Reputation: 3673

Yes, it's a good idea to use a WeakReference here, because the activity could be destroyed. You have to check if it's null each time that you want to use it to avoid a NullPointerException. If it's null, it means that the activity has been destroyed, and thus it usually doesn't make sense to show a ProgressDialog.

Of course, the activity could be destroyed and recreated (for example because of an orientation change). If the AsyncTask takes long, this could have the problem that the progress bar is no longer shown. But the problem here would be using an AsyncTask for a long task, they are intended for short tasks.

Also, remember that if you subclass AsyncTask as an inner class in the Activity class, it will have a strong reference to the Activity, so using a WeakReference would be useless.

Upvotes: 1

Related Questions