已经被封锁好几天了。
由于某些原因,我的androidmodule.java中的“application”成员字段在注入后为空。
Android模块.java
@Module(
library = true
)
public class AndroidModule {
@Inject MittoApplication application;
@Provides @Singleton
SharedPreferences provideSharedPreferences() {
return PreferenceManager.getDefaultSharedPreferences( application );
}
}
应用程序模块.java
@Module(
includes = { ApiModule.class, AndroidModule.class },
library = true
)
public class ApplicationModule {
private Application application;
public ApplicationModule( Application application ) {
this.application = application;
}
@Provides @Singleton
Application providesApplication() {
return application;
}
}
基本活动.java
public class BaseActivity extends AppCompatActivity {
private ObjectGraph objectGraph;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
objectGraph = MittoApplication.getApplication(this).buildScopedObjectGraph(getModules());
objectGraph.inject(this);
}
@Override
protected void onDestroy() {
objectGraph = null;
super.onDestroy();
}
protected List<Object> getModules( ) {
return Arrays.<Object>asList(
);
}
}
mittoapplication.java文件
public class MittoApplication extends Application {
private static Context context;
private ObjectGraph objectGraph;
public void onCreate() {
super.onCreate();
MittoApplication.context = getApplicationContext();
initializeObjectGraph();
}
public static MittoApplication getApplication( Context context ) {
MittoApplication mittoApplication = (MittoApplication) context.getApplicationContext();
return mittoApplication;
}
public ObjectGraph getObjectGraph() {
return this.objectGraph;
}
public ObjectGraph buildObjectGraph( List<Object> modules ) {
return ObjectGraph.create(modules.toArray() );
}
public ObjectGraph buildScopedObjectGraph( List<Object> modules ) {
return objectGraph.plus(modules.toArray() );
}
private ObjectGraph buildInitialObjectGraph( List<Object> modules ) {
return ObjectGraph.create( modules.toArray() );
}
private void initializeObjectGraph() {
objectGraph = buildInitialObjectGraph( Arrays.<Object>asList( new ApplicationModule(this) ));
}
public static Context getContext() {
return MittoApplication.context;
}
}
我花了很多时间思考这个问题,我看过无数的例子和博客网站。希望有比我更聪明的人来帮忙。
谢谢你的阅读。
1条答案
按热度按时间ijnw1ujt1#
字段注入只适用于直接调用对象图。获得
application
示例,则需要将其作为提供程序方法的参数引用。而且,你从来没有提供过
MittoApplication
,只有一个Application
.值得一提的是,你正在使用匕首1,所以我相信你需要改变你的习惯
AndroidModule
成为complete=false
: