1

I have an adapter what uses the activity context to register and unregister a listener.

Activity mActivity;
MyBroadcastReceiver mReceiver;

@Override
public void onAttachedToRecyclerView (RecyclerView recyclerView) {
    super.onAttachedToRecyclerView(recyclerView);
    mActivity.registerReceiver(mReceiver, ...);
}

@Override
public void onDetachedFromRecyclerView (RecyclerView recyclerView) {
    super.onDetachedFromRecyclerView(recyclerView);
    mActivity.unregisterReceiver(mReceiver);
    mActivity = null;
}

Although the onAttachedToRecyclerView always gets called, the detach method never, so the adapter leaks a lot of memory even after closing the activity.(running is only noticeable in the Settings app)

What do I have to do?

Ukubu
  • 810
  • 1
  • 6
  • 18
  • To be safe, you could register the receiver in your Activity. You shouldn't hold on to an Activity reference anywhere really. – a person Jan 16 '16 at 11:20

1 Answers1

1

To be safe, you could register the receiver in your Activity. You shouldn't hold on to an Activity reference anywhere really...

If you really want to register the receiver from your adapter use an interface.

public interface Registerer {
    void register();
    void unregister();
}

In Activity:

mRecyclerView.setAdapter(new RecyclerAdapter(someDataSet, 
new Registerer() {
    public void register() {
        registerReceiver(mReceiver, ...);
    }
    public void unRegister() {
        unregisterReceiver(mReceiver);
    }
});

Then you can call the interface methods from your adapter. I don't really see the point of cramming this into your view adapter though.

a person
  • 986
  • 6
  • 13
  • I forgot to mention that my adapter is an abstract class and there are about 10 subclasses of it. These are very huge classes and most of them uses the activity for a lot of things, so my code would be a bit messy with this approach. I need something like "detaching adapter" from my recycler view. – Ukubu Jan 16 '16 at 11:38
  • To fix it, you need to remove the Activity reference. You could hold on to a weak reference or attempt to cast recyclerView.getContext() to an Activity, but you'll probably just see more exceptions. The solution is to decouple your code. Why don't you register the receiver in your Application subclass? Then you'll never have this problem. – a person Jan 16 '16 at 11:40
  • Is this what you're looking for? http://stackoverflow.com/questions/29978695/remove-all-items-from-recyclerview – a person Jan 16 '16 at 11:46