无法将null值注入类中

时间:2014-09-14 07:55:13

标签: android android-fragments dependency-injection roboguice

我有一个我想重用的片段。它的功能是相同的,只有布局改变

我正在使用roboguice将id注入视图

我添加了此视图,例如:

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

现在这个视图在onCreateView方法中提供的给定布局中可能存在也可能不存在

这就是我把@Nullable放在上面的原因

但是,当我运行应用程序时,如果布局没有此视图,我会得到

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

我需要做些什么来让roboguice允许我重用片段,只改变他们的观点?

3 个答案:

答案 0 :(得分:3)

迟到的答案,但万一其他人偶然发现了这一点。

您可能正在使用android.support.annotation.Nullable或具有@Retention(RetentionPolicy.CLASS)(或RetentionPolicy.SOURCE)的类似注释。但是,您需要使用在运行时保留的@Nullable注释以供RoboGuice查找。例如。这一个:

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 {}

答案 1 :(得分:0)

导入javax.annotation.Nullable而不是android.support.annotation.Nullable,因为它有运行时保留策略(请参阅Michael.F答案)。

答案 2 :(得分:0)

另一种可能性(这就是我在这个问题上的结果)是你的XML文件或Inject命令中有一个拼写错误,并且它试图注入null,因为它实际上没有找到您指定的ID。

相关问题