简体   繁体   English

Android,MVVM:在 ViewModel 中调用 ContentResolver

[英]Android, MVVM: call ContentResolver in ViewModel

I am currently refactoring my code structure to the MVVM-Design-Pattern.我目前正在将我的代码结构重构为 MVVM 设计模式。 In the official android.com documentation ( https://developer.android.com/topic/libraries/architecture/viewmodel ) they write the following: In the official android.com documentation ( https://developer.android.com/topic/libraries/architecture/viewmodel ) they write the following:

Caution: A ViewModel must never reference a view, Lifecycle, or any class that may hold a reference to the activity context.注意: ViewModel 绝不能引用视图、生命周期或任何可能持有对活动上下文的引用的 class。

The Problem is, in my current code I am using ContentResolver to query the Contacts-Database on the phone.问题是,在我当前的代码中,我使用 ContentResolver 来查询电话上的联系人数据库。

var cursor: Cursor? = mainActivity.contentResolver.query(
        ContactsContract.Data.CONTENT_URI,
        projection,
        selection,
        selectionArgs,
        ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME
)

I want to query the database in the viewModel code, but as it seems, ViewModel has no getContentResolver() Method or anything like that and I am not allowed to pass the activity to the viewModel.我想在 viewModel 代码中查询数据库,但看起来, ViewModel没有getContentResolver()方法或类似的方法,并且我不允许将活动传递给 viewModel。 How to access the database from within the viewModel?如何从 viewModel 中访问数据库? Is it even possible?甚至可能吗?

If you need to access a context in a ViewModel, you can use an AndroidViewModel , which lets you access an application context using getApplication() .如果您需要访问 ViewModel 中的上下文,可以使用AndroidViewModel ,它允许您使用getApplication()访问应用程序上下文。 You can use that to get things like a ContentResolver.您可以使用它来获取诸如 ContentResolver 之类的东西。

The cautionary note you listed is about not using or storing an activity, fragment, view, or other lifecycle component in the ViewModel - not really applicable to an application context (which is sometimes needed to get things like strings, or in your case, a ContentResolver, that are not tied to a view lifecycle).您列出的注意事项是关于不在 ViewModel 中使用或存储活动、片段、视图或其他生命周期组件 - 并不真正适用于应用程序上下文(有时需要获取字符串等内容,或者在您的情况下, ContentResolver,与视图生命周期无关)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM