[英]How to access SharedPrefernces in Repository in Android architecture components
我是android开发的新手,我在探索android体系结构组件,想在存储库中使用共享首选项,但是共享首选项需要一个应用程序上下文,因此想知道如何将应用程序上下文传递到存储库,因为视图模型不应对该活动进行任何引用所以想找出什么是从Android存储库中的共享首选项中获取数据的最佳方法
We have used Dagger DI approach in our project and tried injecting SharedPreferenceUtils in RepositoryImpl : 我们在项目中使用了Dagger DI方法,并尝试在RepositoryImpl中注入SharedPreferenceUtils:
@Singleton
public class SharedPreferenceUtils {
//region Private Fields
private SharedPreferences mSharedPreferences;
private final String TAG = SharedPreferenceUtils.class.getSimpleName();
//endregion
@Inject
public SharedPreferenceUtils(SharedPreferences mSharedPreferences) {
this.mSharedPreferences = mSharedPreferences;
}
}
Then inside AppModule we have provided SharedPreference instance as: 然后在AppModule内部,我们提供了SharedPreference实例,如下所示:
public class AppModule {
@Provides
@Singleton
SharedPreferences providesSharedPreferences(Application application) {
return PreferenceManager.getDefaultSharedPreferences(application);
}
}
Then Simply inside our Repository we have used it as: 然后,仅在我们的存储库中,我们就将其用作:
public class RepoImpl implements Repo{
@Inject
SharedPreferenceUtils mSharedPreferenceUtils;
}
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.