Home > Back-end >  Android, MVVM: call ContentResolver in ViewModel
Android, MVVM: call ContentResolver in ViewModel

Time:11-26

I am currently refactoring my code structure to the MVVM-Design-Pattern. 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.

The Problem is, in my current code I am using ContentResolver to query the Contacts-Database on the phone.

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. How to access the database from within the viewModel? Is it even possible?

CodePudding user response:

If you need to access a context in a ViewModel, you can use an AndroidViewModel, which lets you access an application context using getApplication(). You can use that to get things like a 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).

  • Related