I do not fully understand the problem with a memory leak due to the transfer of context to static methods. I understand that there is no universal advice and you need to look at the code, but can anyone give a link to a clear explanation.

For example, I have a Singleton DB class where I need to pass context every time.

  public DB(Context ctx) { mCtx = ctx; } 

So this is why the following is not taken:

 public class AppContext { private static Context sContext; private static Application sApplication; public static Context getContext() { return sContext; } public static void setContext(Context context) { sContext = context; } public static Application getApplication() { return sApplication; } public static void setApplication(Application application) { sApplication = application; } } 

And in the main activation, perform setContext and setApplication and then use AppContext.getApplication () in DB instead of passing the context each time?

2 answers 2

If you keep a "hard" link to Context, that is, Activity, then the activation cannot be destroyed. In general, you should read about the reachability of objects by reference, about weak and soft references (the first thing that came to hand) . In short, it’s very bad ** to keep tightly ** a link to activations, especially in a static field, so try to avoid it in every possible way. At first glance, it seems to be okay, but what if there are a lot of resources, high-resolution photos, etc. in the activation? Memory leak, and God forbid OutOfMemoryError =)

Also remember that static fields are evil, and very insidious. Try to keep the statics in general. In this case, in general, perhaps there is no need to sculpt the structure above. To work with the database, take the context directly at the place of work with the database -> work -> close the database -> release the Context

For example, if you pass the context to your DB class in the constructor, then after you have worked with the base, you should zero it out, chtoli ...

    I don’t know correctly but I understand you, but try to better look towards Dependency Injection. I myself have never come across an androyd, but I found that under the androyd there is also Spring ( http://projects.spring.io/spring-android/ ). This is a great DI framework that allows you to get rid of all the problems with the transmission or storage of context.