我正在尝试使用Dagger 2进行注射,但它总是返回null。我想我做得很好,但无论如何它都行不通。
这是应用程序类:
public class ApplicationSA extends Application {
private static AppComponent appComponent;
@Override
public void onCreate() {
super.onCreate();
appComponent = DaggerAppComponent.create();
}
public static AppComponent getComponent() {
return appComponent;
}
}
组件界面:
@Component(modules = {
SnoreDetectorClass.class,
AudioRecorderClass.class
})
public interface AppComponent {
void injectsMainFunctionalityActivity(Activity activity);
}
我想要获取对象的主要类:
public class MainFunctionalityActivity extends AppCompatActivity {
@Inject
AudioRecorderClass audioRecorderClass;
@Inject
SnoreDetectorClass snoreDetectorClass;
@Override
protected void onCreate(Bundle savedInstanceState) {
ApplicationSA.getComponent().injectsMainFunctionalityActivity(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("TESTING","audioRecorderClass= "+audioRecorderClass); // always null
Log.d("TESTING","snoreDetectorClass= "+snoreDetectorClass); // always null
...
}
以下是模块类:
@Module
public class AudioRecorderClass {
public interface AudioRecorderInterface {
void AudioRecorder_hasUpdate(double amplitude_in_dB);
}
public AudioRecorderInterface delegate = null;
@Provides
AudioRecorderClass provideAudioRecorderClass(Activity activity) {
delegate = (AudioRecorderInterface)activity;
return new AudioRecorderClass();
}
...
@Module
public class SnoreDetectorClass {
@Provides
SnoreDetectorClass provideSnoreDetectorClass() {
return new SnoreDetectorClass();
}
...
我做错了什么?为什么对象总是为空?
答案 0 :(得分:2)
你必须明确告诉dagger这里会注入哪些活动,而不是使用超类Activity,而是使用自己的Activity类实现:
void injectsMainFunctionalityActivity(Activity activity);
更改为:
void injectsMainFunctionalityActivity(MainFunctionalityActivity activity);
答案 1 :(得分:2)
啊,我看到这里发生了什么。你不能注入子类。所以在AppComponent
你不能拥有
void injectsMainFunctionalityActivity(Activity activity);
你必须注入
void injectsMainFunctionalityActivity(MainFunctionalityActivity activity);
作为旁注,我建议不要将注射器和模型类组合在一起。最好分开关注点。将它们分开