Room + ViewModel + LiveData + RecyclerView (MVVM) Part 5 – VIEWMODEL – Android Studio Tutorial



In part 5 of the Architecture Components tutorial, we will create our Viewmodel class.
The ViewModel works as a gateway between the UI controller and the repository. It stores and processes data for the activity/fragment and it doesn’t get destoyed on configuration changes, so it doesn’t lose it’s variable state for example when the device is rotated.
By extending AndroidViewModel, we get a handle to the application context, which we then use to instantiate our RoomDatabase.
In our activity we let the system provide us the correct ViewModel instance by calling ViewModelProviders.of, where we pass the Activity or Fragment this ViewModel’s lifecycle should be scoped to. When our Activity/Fragment is then destroyed, the ViewModel will go through it’s onCleared method and get removed from the memory.
In our activitie’s onCreate method, we retrieve the LiveData that is stored in our ViewModel and call observe on it, where we pass a LifecycleOwner and an Observer. In the onChange callback we get an update on our data whenever something in the corresponding database table changes. The LiveData will automatically start and stop sending updates to our activity at the right time in it’s lifecycle and clean up any unused references.

Watch the whole playlist:

Example code, dependencies & instructions:

____________________
⭐ Get my new MVVM Caching Course now:

❗ Subscribe to the channel:

💲 Earn money by becoming an affiliate for my courses:

📨 Subscribe to the Coding in Flow newsletter:

💻 Hire me for your next project:

💚 Donate to Coding in Flow with a message:

❓ Ask your programming questions in our chat:

📣 Follow Coding in Flow on other sites:
Facebook:
Instagram:
Twitter:
Github:

34 Replies to “Room + ViewModel + LiveData + RecyclerView (MVVM) Part 5 – VIEWMODEL – Android Studio Tutorial”

  1. Bhavishay Mankani

    For those who are having trouble in ViewModelProviders try this:
    noteViewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(NoteViewModel.class);

  2. STD Fast050

    I keep getting this error when I create an instance of NoteModelClass new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(NoteViewModel.class);

    this is the error:
    2021-02-09 17:19:36.659 14409-14409/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.fast050.roomviewmodellivedatarecyclerviewmvvm, PID: 14409
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.fast050.roomviewmodellivedatarecyclerviewmvvm/com.fast050.roomviewmodellivedatarecyclerviewmvvm.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.fast050.roomviewmodellivedatarecyclerviewmvvm.NoteViewModel
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6077)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
    Caused by: java.lang.RuntimeException: Cannot create an instance of class com.fast050.roomviewmodellivedatarecyclerviewmvvm.NoteViewModel
    at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:223)
    at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
    at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
    at com.fast050.roomviewmodellivedatarecyclerviewmvvm.MainActivity.onCreate(MainActivity.java:24)
    at android.app.Activity.performCreate(Activity.java:6662)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
    at android.app.ActivityThread.-wrap12(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:154) 
    at android.app.ActivityThread.main(ActivityThread.java:6077) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 
    Caused by: java.lang.IllegalAccessException: java.lang.Class<com.fast050.roomviewmodellivedatarecyclerviewmvvm.NoteViewModel> is not accessible from java.lang.Class<androidx.lifecycle.ViewModelProvider$NewInstanceFactory>
    at java.lang.Class.newInstance(Native Method)
    at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:219)
    at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187) 
    at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150) 
    at com.fast050.roomviewmodellivedatarecyclerviewmvvm.MainActivity.onCreate(MainActivity.java:24) 
    at android.app.Activity.performCreate(Activity.java:6662) 
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118) 
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599) 
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
    at android.app.ActivityThread.-wrap12(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:154) 
    at android.app.ActivityThread.main(ActivityThread.java:6077) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)

  3. تيم

    If some has a trouble with ViewModelProvider try this
    noteViewModel = new ViewModelProvider(

    this,

    new ViewModelProvider.AndroidViewModelFactory(getApplication())

    ).get(NoteViewModel.class);

  4. Breno César

    Hello, thank you for your good explanation, just a question, isn't necessary to put a ' allNotes = repository.getAllNotes(); ' inside the method delete to update the LiveData 'AllNotes' when a change occur like the ' delete' change ?

  5. NAVJOT SINGH

    If you are getting error "Caused by: java.lang.InstantiationException: java.lang.Class<NoteViewModel> has no zero argument constructor",
    instantiate your View Model as follows:
    noteViewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication())).get(NoteViewModel.class);

  6. Biswas Khayargoli

    How to query notes by passing id … suppose I want to select * from notes where noteid = 1 … HOW TO DO THIS ? HOW TO RETURN DATA FROM ASYNC TASK????? HELP!!!!!!!!!!!!

  7. AiM bOt•exe

    very useful video learned most of android from your videos but ran into a issue :-

    error: Entities and POJOs must have a usable public constructor. You can have an empty constructor or a constructor whose parameters match the fields (by name and type).
    public class Note {
    ^
    Tried the following constructors but they failed to match:

  8. Razan Abu Ghazaleh

    ViewModelProviders is deprecated, for java programmers,i use this:
    noteViewModel= new ViewModelProvider(MainActivity.this).get(NoteViewModel.class);

    but give me this error
    :
    Caused by: java.lang.RuntimeException: Cannot create an instance of class com.employeeapproom.NoteViewModel

    then i use this but give me a same error :
    noteViewModel= new ViewModelProvider(this,
    ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(NodeViewModel.class);

  9. Shashank Sinha

    If anyone is getting error in initializing NoteViewModel in MainActivity – "Cannot create an instance of ViewModel class" caused by the ViewModel.class has no zero-argument constructor. ", Use-
    NoteViewModel noteViewModel = new ViewModelProvider.AndroidViewModelFactory(getApplication()).create(NoteViewModel.class);

  10. Mulkraj Singh

    Even after using the
    YourViewModelClass yourViewModelInstance = new dsdfViewModelProvider(this).get(YourViewModelClass.class);
    you are getting runtime exception like
    "Cannot create an instance of class com.example.architectureexample.NoteViewModel"
    use
    noteViewModel = new ViewModelProvider.AndroidViewModelFactory(getApplication()).create(NoteViewModel.class);

    to create the instance of the NoteViewModel class.

  11. Arun Kumar Krishtamshetty

    I am seeing this error "Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.example.myapplication.NoteViewModel" while trying to launch application.
    Can some one please help?

  12. Anton Larsson

    Solution for my error which was:


    Caused by: java.lang.RuntimeException: Cannot create an instance of class com.*****.viewmodeltesting.TaskViewModel

    Caused by: java.lang.RuntimeException: cannot find implementation for com.*****.viewmodeltesting.sql.TaskDatabase. TaskDatabase_Impl does not exist

    Add this dependency:
    [OLD] annotationProcessor "android.arch.persistence.room:compiler:$room_version"
    annotationProcessor "androidx.room:room-compiler:$room_version"

  13. tee jay

    I used confused by all the long stories in the documentation. Not saying the documentation is bad; I just don't have the patience for too much details

Leave a Reply

Your email address will not be published. Required fields are marked *