0

New to android and trying to implement MVVM

I am trying to use getApplicationContext in ViewModel while using cursor . I think context is not available in ViewModel , then how should i use cursor.

I am building application to access all folder having videos in it .enter image description here

2 Answers2

0

if you want to get access to ApplicationContext inside you ViewModel make sure that your viewModel class extends AndroidViewModel, so you can get the ApplicationContext by calling getApplication() method :


class FolderViewModel  extends AndroidViewModel {

    public FolderViewModel(@NonNull Application application) {
        super(application);
    }

    private void doSomething() {
        getApplication();
    }
    ...
i30mb1
  • 3,894
  • 3
  • 18
  • 34
  • can u tell me how to create instance of this viewmodel – Dhananjay pathak Nov 15 '20 at 16:49
  • `FolderViewModel viewModel = new ViewModelProvider(this).get(FolderViewModel.class);` – i30mb1 Nov 15 '20 at 16:53
  • java.lang.RuntimeException: Unable to start activity ComponentInfo{in.xparticle.divplayer/in.xparticle.divplayer.HomeActivity}: java.lang.RuntimeException: Cannot create an instance of class in.xparticle.divplayer.viewmodels.FolderViewModel gettting this error need help – Dhananjay pathak Nov 15 '20 at 17:02
0

Here is step-by-step how to use the application context from ViewModel.

Step 1: Let your class extends AndroidViewModel

public class FolderViewModel extends AndroidViewModel {

    public FolderViewModel(@NonNull Application application) {
        super(application);
    }

    public void getAllFolders() {
        Cursor cursor = getApplication().getContentResolver()
                .query(uri, projection, null, null, null);
    }
}

Step 2: Create a viewmodel instance from your activity

ViewModelProvider.Factory factory = 
        ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication());
ViewModelProvider provider = new ViewModelProvider(this, factory);
FolderViewModel folderViewModel = provider.get(FolderViewModel.class);

// Call methods of viewmodel
folderViewModel.getAllFolders();
Son Truong
  • 13,661
  • 5
  • 32
  • 58