4

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 ?

Lena Bru
  • 13,521
  • 11
  • 61
  • 126

3 Answers3

3

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 {}
Michael.F
  • 110
  • 1
  • 9
0

Import javax.annotation.Nullable instead of android.support.annotation.Nullable as it has runtime retention policy (see Michael.F answer).

Alexey Kozhevnikov
  • 4,249
  • 1
  • 21
  • 29
0

Another possibility (which is how I ended up on this question) is that you have a typo in your XML file or in the Inject command, and it's trying to inject null because it didn't actually find the ID you specified.

Carl Anderson
  • 3,446
  • 1
  • 25
  • 45