Cannot create an instance of class ViewModel in Android MVVM

喜你入骨 提交于 2021-01-29 04:53:55

问题


I am learning android MVVM pattern android development. I wanted to create a recycclerview activity to show data from server. But it's not accepting my viewmodel class. Bellow is my logcat errors.

LOGCAT

2020-04-12 21:03:18.026 2008-2008/com.shovon.mvvm E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.shovon.mvvm, PID: 2008
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.shovon.mvvm/com.shovon.mvvm.activity.RecyclerActivity}: java.lang.RuntimeException: Cannot create an instance of class com.shovon.mvvm.viewmodel.RecyclerActivityViewModel
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
    at android.os.Handler.dispatchMessage(Handler.java:107)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7356)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
 Caused by: java.lang.RuntimeException: Cannot create an instance of class com.shovon.mvvm.viewmodel.RecyclerActivityViewModel
    at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:221)
    at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
    at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
    at com.shovon.mvvm.activity.RecyclerActivity.onCreate(RecyclerActivity.kt:23)
    at android.app.Activity.performCreate(Activity.java:7802)
    at android.app.Activity.performCreate(Activity.java:7791)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409) 
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016) 
    at android.os.Handler.dispatchMessage(Handler.java:107) 
    at android.os.Looper.loop(Looper.java:214) 
    at android.app.ActivityThread.main(ActivityThread.java:7356) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) 
 **Caused by: java.lang.InstantiationException: java.lang.Class<com.shovon.mvvm.viewmodel.RecyclerActivityViewModel> has no zero argument constructor**
    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.shovon.mvvm.activity.RecyclerActivity.onCreate(RecyclerActivity.kt:23) 
    at android.app.Activity.performCreate(Activity.java:7802) 
    at android.app.Activity.performCreate(Activity.java:7791) 
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299) 
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245) 
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409) 
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016) 
    at android.os.Handler.dispatchMessage(Handler.java:107) 
    at android.os.Looper.loop(Looper.java:214) 
    at android.app.ActivityThread.main(ActivityThread.java:7356) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) 

VIEWMODEL

Here is my viewmodel class. I am passing some data to activity from this viewmodel. But problem is activity does not accept this viewmodel. Maybe viewmodel has any issue.

class RecyclerActivityViewModel(application: Application) : AndroidViewModel(application) {

    val repository = RecyclerActivityRepository(application)


    fun userData(): LiveData<ArrayList<UserResponse>>{
        return repository.getUserData()
    }
}

REPOSITORY

class RecyclerActivityRepository(application: Application) {

    var liveData = MutableLiveData<ArrayList<UserResponse>>()
    private val userList = ArrayList<UserResponse>()
    private var adapter: UserAdapter? = null


    fun getUserData(): MutableLiveData<ArrayList<UserResponse>>{
        if (liveData == null){
            liveData = MutableLiveData<ArrayList<UserResponse>>()
        }

        RetrofitClient.instance.getUsers()
            .enqueue(object : Callback<List<UserResponse>> {
                override fun onFailure(call: Call<List<UserResponse>>, t: Throwable) {
                    Log.v("Retrofit", t.message.toString())
                }

                override fun onResponse(
                    call: Call<List<UserResponse>>,
                    response: Response<List<UserResponse>>
                ) {
                    Log.v("Retrofit", "Success")
                    Log.v("response_code", response.code().toString())
                    try {
                        userList.addAll(response.body()!!)
                        adapter?.notifyDataSetChanged()
                    }catch (e: Exception){
                        Log.v("error", e.message.toString())}
                }

            })
        return liveData
    }
}

ACTIVITY

Here is my logic code

class RecyclerActivity : AppCompatActivity() {

private lateinit var viewModel: RecyclerActivityViewModel

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_recycler)
    viewModel = ViewModelProvider(this).get(RecyclerActivityViewModel::class.java)



}
}

回答1:


this might help

viewModel= ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(RecyclerActivityViewModel::class.java)


来源:https://stackoverflow.com/questions/61173893/cannot-create-an-instance-of-class-viewmodel-in-android-mvvm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!