在网上搜索了解这个功能后,大多数主题或帖子都使用依赖注入来使用Retrofit或其他有用的Android库,但我有一些自定义类想要使用DI,但我无法完成它。例如,我有一个简单的自定义类用于使用SharePreference,并将其用作Singleton类。
在我的代码中,我无法将正确的Dagger分配给SpApplication类的组件,以便在活动或片段中使用它。
我收到了这个错误信息:
感谢您的提前帮助。
在我的代码中,我无法将正确的Dagger分配给SpApplication类的组件,以便在活动或片段中使用它。
public class SP {
private SharedPreferences preferences;
private Context context;
public SP(Context context) {
this.context = context;
}
private SharedPreferences getPrefs() {
return preferences = PreferenceManager.getDefaultSharedPreferences(context);
}
public String getString(SharedPrefsTypes propertyName) {
return getPrefs().getString(propertyName.toString(), "");
}
public int getInt(SharedPrefsTypes propertyName) {
return getPrefs().getInt(propertyName.toString(), 0);
}
...
public enum SharedPrefsTypes {
Login
}
}
我将尝试使用依赖注入来实现这个目标:
AppModules 类:
@Module
public class AppModules {
private Context context;
public AppModules(Context context) {
this.context = context;
}
@Provides
@Singleton
SP provideSharePreferences() {
SP sharePreference = new SP(context);
return sharePreference;
}
}
ApplicationComponent
类:
@Component(modules = AppModules.class)
public interface ApplicationComponent {
void inject(ActivityMain activity);
}
SpApplication
类:
public class SpApplication extends Application {
private static SpApplication self;
private ApplicationComponent component;
@Override
public void onCreate() {
super.onCreate();
self = this;
component = DaggerApplicationComponent.builder().build();
}
public static SpApplication get(Context context) {
return (SpApplication) context.getApplicationContext();
}
public static SpApplication getInstance() {
return self;
}
public ApplicationComponent getComponent() {
return component;
}
}
我的ActivityMain
类:
public class ActivityMain extends AppCompatActivity {
@Inject
SP sharePreference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((SpApplication) getApplication()).getComponent().inject(this);
sharePreference.setInt(SP.SharedPrefsTypes.Login, 0);
}
}
我收到了这个错误信息:
android.app.Application cannot be cast to com.pishguy.yendir.SpApplication
感谢您的提前帮助。
ApplicationComponent
类中添加void inject(ActivityMain target)
以便注入到ActivityMain
后,我发现在活动中这一行代码sharePreference.setInt(SP.SharedPrefsTypes.Login,0);
出现了null object reference
的问题。 - mahdi pishguy((SpApplication)getApplication()).getComponent().inject(this)
。在使用注入服务之前,应该先执行此操作。 - Vasiliy((SpApplication) getApplication()).getComponent().inject(this);
后,我得到了一个android.app.Application cannot be cast to com.pishguy.yendir.SpApplication
的错误。 - mahdi pishguySpApplication
注册为您的自定义Application
类了。 - Vasiliy