2
已被封鎖數天。注入匕首返回null
出於某種原因,我的AndroidModule.java中的'application'成員字段在注入後爲null。
AndroidModule.java
@Module(
library = true
)
public class AndroidModule {
@Inject MittoApplication application;
@Provides @Singleton
SharedPreferences provideSharedPreferences() {
return PreferenceManager.getDefaultSharedPreferences(application);
}
}
ApplicationModule.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;
}
}
BaseActivity.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;
}
}
我已經花了很多時間思考這個問題,我已經看過無數的例子和博客網站。我會幫助一個更聰明的人。
感謝您的閱讀。