0

In the below example code from my project, android studio warns me that this is a memory leak. Is Android Studio right? Application class is singleton thus i thought that it is good to store it in my class. What is your suggestions?

public class MyApi {

    private static MyApi instance ; // Compiler gives the following warning:  Do not place Android context classes in static fields (static reference to MyApi which has field context pointing to Context); this is a memory leak

     private Context context; // i need this context inside MyApi class.

    public static MyApi getInstance() {
        return instance;
    }

    public static void init(Context context) {
        instance = new MyApi(context);
    }
    private MyApi(final Context context) {
        this.context = context;
    }
}

public class App extends Application{
    @Override
    public void onCreate() {
        MyApi.init(this);
    }
}
oiyio
  • 5,219
  • 4
  • 42
  • 54
  • https://stackoverflow.com/questions/2472690/in-java-is-there-any-disadvantage-to-static-methods-on-a-class – IntelliJ Amiya Jul 10 '19 at 13:55
  • Change all references to `Context` in `MyApi` to `Application`. Your code is fine from a memory leak standpoint... except that something else could call `init()` with some `Context` that is not an `Application`. – CommonsWare Jul 10 '19 at 13:56
  • My App class extends from MultiDexApplication. Should i Change all references to Application or MultiDexApplication ? – oiyio Jul 10 '19 at 13:58

1 Answers1

1

Lint sees you store a Context in a static. It does not know which kind of context it is.

If it was an activity context, then it would be super easy to leak. Application context is an application-scoped singleton and it does not cause a leak. You can ignore or suppress this warning if you want to.

static state is kind of an anti-pattern so most of the time you're better of avoiding it though.

laalto
  • 150,114
  • 66
  • 286
  • 303