0

Suppose we have some Adapter or ViewHolder which takes an OnClickListener as a constructor parameter:

public class PassageDateSpecifiedViewHolder extends BasePassageViewHolder<Passage> {
    WeakReference<PassageRecyclerAdapter.OnItemClickListener> reference;

    public PassageDateSpecifiedViewHolder(View itemView,
                                      PassageRecyclerAdapter.OnItemClickListener listener) {
        super(itemView);
        this.reference = new WeakReference<>(listener); //will reference live as long as my PassageDateSpecifiedViewHolder  class?
    }

    @Override
    protected void onClick(View view, Passage item) {
        PassageRecyclerAdapter.OnItemClickListener localListener = reference.get();
        if (localListener != null) {
            localListener.onItemClick(item);
        }
    }
} 

So, according to some guides, I need to WeakReference for onClickListeners in order to avoid memory leaks. This is acually clear, but I can't understand what happend if I pass an anonymous class into my constructor, or class, where the instance of my onClickListener is created(or listener itself) was destroyed.

This means that there are no links and this listener can be destoryed. Tell me, where I'm wrong.

Samuel Robert
  • 10,106
  • 7
  • 39
  • 60
nutella_eater
  • 3,393
  • 3
  • 27
  • 46

1 Answers1

0

You should go through this question before implementing listeners as weak reference.

I can't understand what happend if I pass an anonymous class into my constructor, or class, where the instance of my onClickListener is created(or listener itself) was destroyed.

In this case your reference.get() will return null.

Will reference live as long as my PassageDateSpecifiedViewHolder class?

This is not guaranteed. It depends on the object which contains listener. If that object is destroyed you will loose reference to the listener.

Community
  • 1
  • 1
mallaudin
  • 4,744
  • 3
  • 36
  • 68
  • yep, I know that. What if in the first case, the activity has been destoryed, but your textView is still alive(suppose it is in another class) – nutella_eater Nov 22 '16 at 11:45
  • Yeah, that's why I made a weakReference for it. – nutella_eater Nov 22 '16 at 11:49
  • Exactly! But I should use WeakReference to avoid memory leaks. But It can return null in some cases. Which way is right? Can you also update your answer and add some Adapter/Holder class where listener is passed, so it will be more clear for me. – nutella_eater Nov 22 '16 at 11:58