Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are ApplicationContext or Activity Context suitable for Adapter?

I am using the adapter for ListView/RecycleView on my project. But I am wondering which kind of Context I should pass to the adapter? ApplicationContext or Activity Context(it's mean this on the activity)?. As I know that the system does not kill the adapter even if the activity being killed. So I have some confusions here:

  1. If I pass the Activity Context to the adapter, so the adapter have an implicit reference to the activity. Can the activity be killed?
  2. In the other hand, I pass ApplicationContext. How long does the Adapter still live? Does it collected by GC after the activity be killed?
  3. Which kind of Context I should pass in specific case?

Thanks,

like image 911
Truong Giang Dam Avatar asked Jan 03 '18 03:01

Truong Giang Dam


2 Answers

If I pass the Activity Context to the adapter, so the adapter have an implicit reference to the activity. Can the activity be killed?

Correction it is an explicit reference since you are passing it manually. So basically the answer to your question is likely YES because the one holding the Adapter is the activity itself, even if the adapter is holding a reference to your activity both of them will be garbage collected once the Activity is finished.

Unless you are dealing with Threads it is recommended to use WeakReference since a Thread can live longer than the activity itself.

In the other hand, I pass ApplicationContext. How long does the Adapter still live? Does it collected by GC after the activity be killed?

YES

Which kind of Context I should pass in specific case?

Both can work but Application context is a lot safer.

As I know that the system does not kill the adapter even if the activity being killed.

Something is not right in the code, probably you are dealing the wrong use of statics or Threads. Additional code required here or a proof of your profiler!

like image 92
Enzokie Avatar answered Sep 27 '22 23:09

Enzokie


ApplicationContext as it should get cleaned by GC when you destroy the activity if you have more than 1

like image 21
Kingsley Mitchell Avatar answered Sep 28 '22 00:09

Kingsley Mitchell