Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Context to ArrayAdapter inside Fragment with setRetainInstance(true) will cause leak?

I have a ListFragment which would show list of items via an ArrayAdapter, I'm trying to handle configuration change (Device Rotation) I feel passing activity context to Array Adapter might cause Memory Leak when Activity is restarted on rotation and ListFragment adapter is retained because i'm using setRetainInstance(true), can someone tell me if my understanding is true? If so what is the best way to handle this. And yes I don't want to null my adapter onDetach and reuse it once Fragment view is re-created.

    public class DummyXListFragment extends RoboSherlockListFragment{

        @Override
        public void onCreate(Bundle savedInstanceState) {   
             super.onCreate(savedInstanceState);
             setRetainInstance(true);   
         }   

         @Override
         public void onActivityCreated(Bundle savedInstanceState) {
             super.onActivityCreated(savedInstanceState);


            if (adapter == null)
            adapter = new DummyItemAdapter(getActivity(),
                android.R.layout.simple_list_item_1, list);

    }
like image 225
Mayank Mehta Avatar asked Sep 19 '13 14:09

Mayank Mehta


2 Answers

The Fragment will be retained (and thus won't be garbage collected). The Fragment will hold a reference to the adapter, and the adapter holds a reference to the activity Context, so yes, I believe this will cause a memory leak.

A very simple solution would be to pass getActivity().getApplicationContext() to the adapter constructor instead.

like image 93
Alex Lockwood Avatar answered Nov 12 '22 05:11

Alex Lockwood


Depending on what you are using the activity context for it may be possible to use the application context instead, but there are some circumstances where you may still require the activity context. You cannot, for instance, do a findViewById or display a toast/dialog with an application context.

If you must use the activity context, then I would add a method to your adapter for setting the context so you can set it (the context) to null on detach, then set it again when your fragment/activity is recreated.

Here's a good summary of the different context types and their capabilities: http://www.doubleencore.com/2013/06/context/

like image 41
goto10 Avatar answered Nov 12 '22 04:11

goto10