NPE when injecting a static @Bean

20 views
Skip to first unread message

Tobias Preuss

unread,
Jun 7, 2017, 1:14:27 PM6/7/17
to androidannotations

I am trying to inject a static field using the @Bean from AndroidAnnotations:


@EBean
public class LogUtil {

   
@Bean(CrashReporting.class) static Reporting reporting;

   
public static void log(Activity activity, String method) {
        reporting
.log(activity.getClass().getName() + ":" + method);
   
}

}

@EBean(scope = EBean.Scope.Singleton)
public class CrashReporting implements Reporting {

   
@Override
   
public void log(String text) {
       
Log.d(getClass().getName(), text);
   
}

}


The reporting field is null at runtime:


Caused by: java.lang.NullPointerException: 
Attempt to invoke interface method
'void com.example.staticinjection.Reporting.log(java.lang.String)'
on a
null object reference
    at com
.example.staticinjection.LogUtil.log(LogUtil.java:15)
    at com
.example.staticinjection.MainActivity.onCreate(MainActivity.java:12)
    at android
.app.Activity.performCreate(Activity.java:6237)
   
...


I created this demo project for you to reproduce the error.

Kay-Uwe Janssen

unread,
Jul 19, 2017, 10:17:28 AM7/19/17
to androidannotations
I have not tested your sample but from what i can see in the code in this post I'd say this can't work. Injection is done when instantiating a class. That means at some point you need to either inject LogUtils or call getInstance() on the generated class as in `LogUtils_.getInstance()` (might need a context parameter).
Reply all
Reply to author
Forward
0 new messages