Search code examples
androidsingletonandroid-annotations

AndroidAnnotations access Singleton class object into other class static method


From MyActivity, call to:

  1. MyClass.getInstance();
  2. MyClass.doStuff();

...

@EBean(scope = EBean.Scope.Singleton)  
public class MyClass {
    @Bean
    MyManager manager;

    public static void doStuff(){   
        manager.show();
        // null pointer exception for the manager  why ? how to access it ?
    }  
     public static MyClass getInstance() {
        if (_instance == null) {
            _instance = new MyClass();
        }
        return  _instance;
    }
}

...

@EBean(scope = EBean.Scope.Singleton)  
public class MyManager {
    public void show(){     }
}

Android annotations access singleton class object into other class static method. Note : AA version 3.3.1


Solution

  • I am afraid you are using AA @EBean incorrectly. Did you read the documentation?

    You do not have to write a getInstance() method yourself, AA will generate the appropriate method, do the injections in it, and automatically call it when injecting the bean into other components. You got a NullPointerException because you created the bean with your own getInstance() method, so no AA injections were performed. But actually you are getting a compile error in doStuff(), because you are accessing an instance field in a static method... So i assume the manager field is static, right? You should not use static fields/methods in singletons, the concept of the singleton is one instance is existing only, so using static fields/methods is redundant and also confusing.

    You can fix the problem by either:

    • Creating an instance of MyClass by calling MyClass_.getInstance(context) manually, then use it
    • Inject a MyClass instance into another component with the @Bean annotation and use it from there