Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it leak-safe to keep a Context/Activity instance in RecyclerView.Adapter?

Given an adapter like this:

public class MyAdapter extends RecyclerView.Adapter {

    private final Activity mActivity;
    private final List<Item> mItemList;

    public MyAdapter(Activity activity, List<Item> itemList) {
        this.mActivity = activity;
        this.mItemList = itemList;
    }

    //[...]

    public void onBindViewHolder(ViewHolder holder, int position) {
        final Item i = mItemList.get(position);
        holder.launchButton.setOnClickListener(new OnClickListener() {
                @Override public void onClick(View v) {
                    mActivity.startActivity(i.getIntent());
            });
    }

}

As you can see, the activity instance is needed for launch the intents. Of course, there are other ways to do that (e.g. using interfaces) but the point of the question is if it is safe to keep the hard reference to mActivity instance in the adapter

like image 468
BamsBamx Avatar asked Jan 27 '17 06:01

BamsBamx


People also ask

Should I pass context to adapter?

there is nothing wrong with passing context to your adapter. You just should keep your adapter responsible for work with views, leaving networking or database operations for your fragment.

What is ViewHolder RecyclerView?

A RecyclerView. ViewHolder class which caches views associated with the default Preference layouts. A ViewHolder describes an item view and metadata about its place within the RecyclerView. Adapter implementations should subclass ViewHolder and add fields for caching potentially expensive findViewById results.


1 Answers

Yes, it's fine. Android's garbage collection will recycle objects once there is no strong reference to them from the root object. The adapter is referred to by the RecyclerView, and the RecyclerView will be eligible for garbage collection before the Activity is freed, so by the time the Activity should be recycled, the RecyclerView will be eligible for garbage collection, and thus it will not prevent the Activity from being garbage collected. Also, this is fine if the Activity has a reference to the Adapter, as if two objects only have references to each other, they cannot he accessed from the root object, and thus are both eligible for garbage collection.

like image 112
Jane Fraser Avatar answered Sep 19 '22 02:09

Jane Fraser