12

I have a ListView in an Activity and I am setting a custom adapter to the ListView.

Should my adapter class be:

private static class MyAdapter extends ArrayAdapter 

or

private class MyAdapter extends ArrayAdapter

I guess it should make no difference as long as the adapter is enclosed within the activity reference but wanted to confirm that.

dnkoutso
  • 6,041
  • 4
  • 37
  • 58
  • (For future readers) The last question is backwards. If you have a static inner class, and need access to the activity/context, you should use a WeakReference (if there is anything that could outlive the activity). If the class is not static and inner, it has an implicit strong reference to the outer class. In that case, you'd also still need to be careful about how the adapter is used. Using static can help find implicit leaks, but adds overhead in passing around a context/weakreference. – lilbyrdie Jun 06 '14 at 12:58
  • Also, in any of the calls into an adapter that take a View object, the context is available (View.getContext()). You can use instanceof to make sure it's your activity. – lilbyrdie Jun 06 '14 at 13:00

1 Answers1

17

Holding onto the context is fine from within an adapter if you are careful about how you use the adapter. Adapters are usually tied to the lifecycle of their Context (an Activity) so it's fine. Use a WeakReference only if it makes sense.

Romain Guy
  • 97,993
  • 18
  • 219
  • 200
  • Could you elaborate more on "being careful how to use the adapter" part? So it seems it shouldn't matter which of the two since the adapter is tied to the Activity life cycle. – dnkoutso Oct 28 '11 at 23:06
  • 1
    Don't keep the adapter in a static field that lives longer than your activities for instance. – Romain Guy Oct 29 '11 at 01:37
  • @RomainGuy what about if we explicitly `null` the static adapter object in `onDestroy()`? is it a good approach? – Muhammad Babar Jun 04 '13 at 09:39
  • 3
    No, because onDestroy() isn't a guaranteed call, from what I understand. – lilbyrdie Jun 06 '14 at 12:54