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);
}
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With