13

I am working on a large code base, and see in many places this type of code:

public static class RequestCustomData implements View.OnClickListener {
    WeakReference<MainActivity> mainActivity;

    public RequestCustomData(MainActivity activity) {
        mainActivity = new WeakReference<>(activity);
    }

    @Override
    public void onClick(View view) {
        MainActivity activity = mainActivity.get();
        activity.requestCustomData(true, null);
    }
}

I am a bit confused why this is used is so many places? I took a look at this document but it did not clarify well why this type of code is so heavily used on the app I am working on it

https://community.oracle.com/blogs/enicholas/2006/05/04/understanding-weak-references

Anyone can explain me if this is a common pattern? If so, why?

gmmo
  • 2,577
  • 3
  • 30
  • 56
  • 1
    Usually it's a band-aid for sloppy limits on the lifetime of a listener. Note that in your example, if the intended purpose of the `WeakReference` ever did come into play, `onClick(...)` would throw a `NullPointerException`. If this code isn't crashing, the use of `WeakReference` is probably an example of [cargo cult programming](https://en.wikipedia.org/wiki/Cargo_cult_programming). – Kevin Krumwiede Mar 24 '16 at 03:25

1 Answers1

27

A weak reference, simply put, is a reference that isn't strong enough to force an object to remain in memory.

The authors of this code most likely wanted to avoid leaking of the Activity context if the RequestCustomData object could outlive the Activity itself.

I recommend Romain Guy's post on this topic as well as several specific cases to avoid:

szym
  • 5,606
  • 28
  • 34
  • 6
    That is indeed the reason people do this. But it's usually better to make sure the listener *doesn't* outlive the activity in the first place. – Kevin Krumwiede Mar 24 '16 at 03:21
  • The link to Romain Guy's post shows _"Error establishing a database connection"_. The link is broken I guess – Shashanth Jul 22 '17 at 06:26
  • 1
    Romain Guy's post is unreachable. IMHO this article based on that post: https://android-developers.googleblog.com/2009/01/avoiding-memory-leaks.html – csonuryilmaz May 03 '21 at 19:33