0

I know this has been asked many times but still many new developers like me finds it difficult.To avoid memory leaks which context should be used?. Somewhere i found that we should getApplicationContext() and somewhere that try to use context-activity as possible.Also http://android-developers.blogspot.in/2009/01/avoiding-memory-leaks.html says

Try using the context-application instead of a context-activity

For eg

Which Context to pass to RecyclerView Adapter or to a Custom Dialog Class

One way i found is to pass context to adapter in this way

recyclerview.setAdapter(new YourAdapter(new WeakReference<Activity>(ActivityName).get()));

Is my way of passing context is right?

Please do a give detailed explanation so that others also gets benefitted. Thanks

Sonali Pawar
  • 420
  • 3
  • 18

1 Answers1

3

Which Context to pass to RecyclerView Adapter or to a Custom Dialog Class

When dealing with UI concerns, always pass the Activity.

Is my way of passing context is right?

You should not need a WeakReference to the Activity for use in a RecyclerView.

To avoid memory leaks which context should be used?

That cannot be answered in general. The simplest basic rule is: use Application as a Context when you are concerned that the Context might be held in static scope, such as in an object referenced by a static data member, or such as in a thread. Otherwise, use a more-focused Context (e.g., your Activity, your Service).

Dave Smith's blog post on contexts is the best single-page resource on the subject that I have found.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • But if i use a weakref context will it create any problem? – Sonali Pawar Apr 05 '16 at 12:06
  • @SonaliPawar: You might have some performance-related issues, due to constantly going through locks. – CommonsWare Apr 05 '16 at 12:08
  • what if sir i have to do Network related jobs or show dialogs from adapter, will activity context be suitable? – Sonali Pawar Apr 05 '16 at 12:11
  • @SonaliPawar: As I wrote in my answer, when dealing with UI concerns, like a dialog, always use the `Activity`. "Network related jobs" do not have an intrinsic need for a `Context`. What matters is not that they are "network related", but what they are doing and how long they are taking. There are **many** patterns for asynchronous work. – CommonsWare Apr 05 '16 at 12:21