Search code examples
androidandroid-fragmentsdependency-injectionroboguice

Cant inject null value into class


I have a fragment that I want to reuse. Its functionality is the same, only the layout changes

I am using roboguice to inject views by id into the variables

I added this view for example:

@Nullable
@InjectView(R.id.edtEventLocationAddress)
private EditText edtEventLocationAddress;

now this view may or may not be present in the given layout i provided in the onCreateView method

this is why i put @Nullable on it

however, when I run the app, with the layout that does not have this view, I get

java.lang.NullPointerException: Can't inject null value into class 
com.myapp.CreateEventPageFragment.edtEventLocationAddress when field is not @Nullable

What do I need to do to make roboguice allow me to reuse fragments, and only change their view ?


Solution

  • A late answer but just in case anyone else stumbles on this.

    You are probably using android.support.annotation.Nullable or a similar annotation that has @Retention(RetentionPolicy.CLASS) (or RetentionPolicy.SOURCE). However, you need to use a @Nullable annotation that is retained at runtime for RoboGuice to find it. E.g. this one:

    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    @Target({ElementType.FIELD, ElementType.METHOD,
        ElementType.PARAMETER,
        ElementType.LOCAL_VARIABLE})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface Nullable {}