This question already has answers here:
Android room persistent: AppDatabase_Impl does not exist
(29 answers)
Closed 12 months ago.
I am working on a notes application with room and ViewModel but while initializing the ViewModel inside activity, I am getting this
java.lang.RuntimeException: Cannot create an instance of class package.notes.homeScreen.HomeScreenVM
here is my main activity
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var viewModel: HomeScreenVM
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setUI()
setViewModel()
}
private fun setUI() {
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
}
private fun setViewModel() {
viewModel = ViewModelProvider(this, HomeScreenViewModelFactory(this.application))[HomeScreenVM::class.java]
}
}
and ViewModel is like-
class HomeScreenVM(application: Application) : AndroidViewModel(application) {
//some methods
}
and my viewmodelfactory is like-
class HomeScreenViewModelFactory(private val application: android.app.Application) : ViewModelProvider.AndroidViewModelFactory(application) {
#Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(HomeScreenVM::class.java))
return HomeScreenVM(application) as T
throw IllegalArgumentException("Unknown model class")
}
}
I don't know where the problem is. Help me.
Thanks in advance.
Update:-
full stacktrace is
Process: com.nitkkr.sanjay.notes, PID: 32750
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nitkkr.sanjay.notes/com.nitkkr.sanjay.notes.homeScreen.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.nitkkr.sanjay.notes.homeScreen.HomeScreenVM
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3536)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3708)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
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:2143)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:236)
at android.app.ActivityThread.main(ActivityThread.java:8087)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:656)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:967)
Caused by: java.lang.RuntimeException: Cannot create an instance of class com.nitkkr.sanjay.notes.homeScreen.HomeScreenVM
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:315)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:273)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:182)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:151)
at com.nitkkr.sanjay.notes.homeScreen.MainActivity.setViewModel(MainActivity.kt:29)
at com.nitkkr.sanjay.notes.homeScreen.MainActivity.onCreate(MainActivity.kt:17)
at android.app.Activity.performCreate(Activity.java:8157)
at android.app.Activity.performCreate(Activity.java:8129)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1310)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3509)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3708)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
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:2143)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:236)
at android.app.ActivityThread.main(ActivityThread.java:8087)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:656)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:967)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:307)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:273)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:182)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:151)
at com.nitkkr.sanjay.notes.homeScreen.MainActivity.setViewModel(MainActivity.kt:29)
at com.nitkkr.sanjay.notes.homeScreen.MainActivity.onCreate(MainActivity.kt:17)
at android.app.Activity.performCreate(Activity.java:8157)
at android.app.Activity.performCreate(Activity.java:8129)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1310)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3509)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3708)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
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:2143)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:236)
at android.app.ActivityThread.main(ActivityThread.java:8087)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:656)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:967)
Caused by: java.lang.RuntimeException: cannot find implementation for com.nitkkr.sanjay.notes.data.database.NoteDatabase. NoteDatabase_Impl does not exist
at androidx.room.Room.getGeneratedImplementation(Room.java:100)
at androidx.room.RoomDatabase$Builder.build(RoomDatabase.java:1486)
at com.nitkkr.sanjay.notes.data.database.NoteDatabase$Companion.getInstance(NoteDatabase.kt:24)
at com.nitkkr.sanjay.notes.data.database.NoteRepository.<init>(NoteRepository.kt:11)
at com.nitkkr.sanjay.notes.homeScreen.HomeScreenVM.<init>(HomeScreenVM.kt:12)
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:307)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:273)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:182)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:151)
at com.nitkkr.sanjay.notes.homeScreen.MainActivity.setViewModel(MainActivity.kt:29)
at com.nitkkr.sanjay.notes.homeScreen.MainActivity.onCreate(MainActivity.kt:17)
at android.app.Activity.performCreate(Activity.java:8157)
at android.app.Activity.performCreate(Activity.java:8129)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1310)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3509)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3708)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
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:2143)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:236)
at android.app.ActivityThread.main(ActivityThread.java:8087)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:656)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:967)
viewModel =ViewModelProvider(
this,
HomeScreenViewModelFactory(application)
).get(HomeScreenVM::class.java)
Use this i hope it will work.
Related
I'm currently working on a project to practice dependency injection with Dagger-Hilt, however I can't get my ViewModel to instantiate, I've already looked at some other questions on the same topic, most point the issue to Gradle but that didn't fix it for me, all errors in the Stacktrace are from internal classes except for the 2 lines that involve my ViewModel within the MainActivity
Here is the Stacktrace:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.practiceproject, PID: 9873
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.practiceproject/com.example.practiceproject.ui.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.example.practiceproject.ui.viewmodel.DogViewModel
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.example.practiceproject.ui.viewmodel.DogViewModel
at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:221)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:278)
at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:112)
at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:146)
at dagger.hilt.android.internal.lifecycle.HiltViewModelFactory.create(HiltViewModelFactory.java:111)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
at androidx.lifecycle.ViewModelLazy.getValue(ViewModelProvider.kt:54)
at androidx.lifecycle.ViewModelLazy.getValue(ViewModelProvider.kt:41)
at com.example.practiceproject.ui.MainActivity.getDogViewModel(MainActivity.kt:15)
at com.example.practiceproject.ui.MainActivity.onCreate(MainActivity.kt:22)
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.example.practiceproject.ui.viewmodel.DogViewModel> 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$AndroidViewModelFactory.create(ViewModelProvider.java:278)
at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:112)
at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:146)
at dagger.hilt.android.internal.lifecycle.HiltViewModelFactory.create(HiltViewModelFactory.java:111)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
at androidx.lifecycle.ViewModelLazy.getValue(ViewModelProvider.kt:54)
at androidx.lifecycle.ViewModelLazy.getValue(ViewModelProvider.kt:41)
at com.example.practiceproject.ui.MainActivity.getDogViewModel(MainActivity.kt:15)
at com.example.practiceproject.ui.MainActivity.onCreate(MainActivity.kt:22)
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)
Here is the ViewModel:
class DogViewModel #Inject constructor(
private val getDefaultImages: GetDefaultImages
) : ViewModel() {
val dogModel = MutableLiveData<DogModel>()
val isLoading = MutableLiveData<Boolean>()
fun onCreate() {
viewModelScope.launch {
isLoading.value = true
val result = getDefaultImages()
if(!result.isNullOrEmpty()) {
dogModel.value = result[0]
isLoading.value = false
}
}
}
And this is where I'm declaring it:
#AndroidEntryPoint
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private val dogViewModel: DogViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
dogViewModel.onCreate()
dogViewModel.dogModel.observe(this) {
initRecyclerView(it)
}
}
You should add #HiltViewModel annotation on top of your view model.
Make sure you have written #AndroidEntryPoint above your Fragment or Activity class.
You have to write #HiltViewModel above your ViewModel Class.
Also make sure you are providing all the dependencies written in ViewModel like repositories, etc.
If don't use getDefaultImages object in DogViewModel you can remove it and it will work. If you use it you need to pass an instance of GetDefaultImages class to the DogViewModel using ViewModelProvider.Factory:
#Suppress("UNCHECKED_CAST")
private val factory: ViewModelProvider.Factory = object : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return DogViewModel(GetDefaultImages()) as T
}
}
private val dogViewModel: MyViewModel by viewModels { factory }
I have an app now published on the play store. In debug, the app runs perfectly but when I tried to download the release app crashes instantly and it gives me this error.
2021-03-04 15:02:40.195 15100-15100/com.uhi5d.spotibud E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.uhi5d.spotibud, PID: 15100
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.uhi5d.spotibud/com.uhi5d.spotibud.load.ContentActivity}: java.lang.NoSuchMethodException: d.e.a.e.b.<init> [interface c.p.i, class android.content.Context]
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3310)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3459)
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:2046)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:225)
at android.app.ActivityThread.main(ActivityThread.java:7564)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Caused by: java.lang.NoSuchMethodException: d.e.a.e.b.<init> [interface c.p.i, class android.content.Context]
at java.lang.Class.getConstructor0(Class.java:2332)
at java.lang.Class.getConstructor(Class.java:1728)
at d.e.a.e.a.a(CustomViewModelFactory.kt:10)
at c.p.u.b(ViewModelProvider.java:187)
at c.p.u.a(ViewModelProvider.java:150)
at com.uhi5d.spotibud.load.ContentActivity.onCreate(ContentActivity.kt:33)
at android.app.Activity.performCreate(Activity.java:7916)
at android.app.Activity.performCreate(Activity.java:7903)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1307)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3285)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3459)
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:2046)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:225)
at android.app.ActivityThread.main(ActivityThread.java:7564)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
My ViewModel factory
public class CustomViewModelFactory(val lifecycleOwner: LifecycleOwner,public val context: Context):ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return modelClass.getConstructor(LifecycleOwner::class.java,Context::class.java).newInstance(lifecycleOwner,context)
}
}
And error part
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_content)
// ViewModel components
factory = CustomViewModelFactory(this,this)
viewmodel = ViewModelProvider(this, factory!!).get(MainViewModel::class.java)
I created Viewmodel instance and it worked few times, now it is showing error while initializing userPermissionViewModel in MainActivity.
I am using DataStore to save data and try to observer the same.
I even tried initializing as below, but no luck
userPermissionsViewModel = ViewModelProvider(this,ViewModelProvider.AndroidViewModelFactory.getInstance(this.application)).get(UserPermissionsViewModel::class.java)
Error Log
2020-12-11 16:13:40.785 13161-13161/com.lobostaffing.app E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.lobostaffing.app, PID: 13161
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.lobostaffing.app/com.lobostaffing.app.mvvm.ui.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.lobostaffing.app.mvvm.viewmodels.UserPermissionsViewModel
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
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:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.RuntimeException: Cannot create an instance of class com.lobostaffing.app.mvvm.viewmodels.UserPermissionsViewModel
at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:221)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:278)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
at com.lobostaffing.app.mvvm.ui.MainActivity.onCreate(MainActivity.kt:231)
at android.app.Activity.performCreate(Activity.java:8000)
at android.app.Activity.performCreate(Activity.java:7984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
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:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.InstantiationException: java.lang.Class<com.lobostaffing.app.mvvm.viewmodels.UserPermissionsViewModel> 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$AndroidViewModelFactory.create(ViewModelProvider.java:278)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
at com.lobostaffing.app.mvvm.ui.MainActivity.onCreate(MainActivity.kt:231)
at android.app.Activity.performCreate(Activity.java:8000)
at android.app.Activity.performCreate(Activity.java:7984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
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:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
MainActivity.kt
userPermissionsViewModel = ViewModelProvider(this).get(UserPermissionsViewModel::class.java)
userPermissionsViewModel.readFromDataStore.observe(this, { userDetailModel ->
setupNavDrawer(userDetailModel)
})
UserPermissionsViewModel.kt
class UserPermissionsViewModel(application: Application): ViewModel() {
private val userPermissionsRepo = UserPermissionsRepo(application)
val readFromDataStore = userPermissionsRepo.userDetailModel.asLiveData()
fun saveToDataStore(userDetailModel: UserDetailModel) = viewModelScope.launch(Dispatchers.IO){
userPermissionsRepo.saveUserPermissions(userDetailModel)
}}
Build.gradle
def archLifecycleVersion = '2.2.0'
//Lifecycle components
implementation "androidx.lifecycle:lifecycle-extensions:$archLifecycleVersion"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$archLifecycleVersion"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$archLifecycleVersion"
implementation "androidx.lifecycle:lifecycle-runtime-ktx:$archLifecycleVersion"
Try this
MainActivity:
class MainActivity : AppCompatActivity() {
private lateinit var userPermissionsViewModel: UserPermissionsViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
userPermissionsViewModel = ViewModelProvider(this).get(UserPermissionsViewModel::class.java)
}
}
And your viewModel:
class UserPermissionsViewModel(application: Application) : AndroidViewModel(application) {
private val userPermissionsRepo = UserPermissionsRepo(application)
}
Initialize your viewmodel like this
yourViewModelInstance = new ViewModelProvider(this).get(YourViewModelClass.class);
When you need an application context in the ViewModel it should extend AndroidViewModel.
ViewModel with context:
class UserPermissionsViewModel(application: Application) : AndroidViewModel(application)
or without context
class UserPermissionsViewModel : ViewModel()
When a regular ViewModel has any constructor paramaters, the default ViewModelFactory does not know how to create it.
Try to add the right dependencies
//lifecycle
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.2.0"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.2.0"
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)
}
}
this might help
viewModel= ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(RecyclerActivityViewModel::class.java)
When I set my application to background and open it again I have a crash:
java.lang.RuntimeException: Unable to destroy activity {MainActivity}: java.util.ConcurrentModificationException
I'm using navigation graph scope for storing viewmodel
fun <T : ViewModel> getViewModelForGraph(
graphId: Int,
clazz: Class<T>,
fragment: Fragment
): T {
val navController = NavHostFragment.findNavController(fragment)
val vmFactory = object : ViewModelProvider.Factory {
override fun <U : ViewModel?> create(modelClass: Class<U>): U =
Factory.getComponent(clazz) as U
}
return ViewModelProvider(
navController.getViewModelStoreOwner(graphId),
vmFactory
).get(clazz)
}
and I'm getting my viewmodel from fragment this way:
getViewModelForGraph(
R.id.my_sub_graph,
MyViewModel::class.java,
this
)
.getViewModelForGraph(
R.id.mySubGraph,
MyViewModel::class.java,
this
)
And problem resolves when I'm getViewModelForGraph and just attaching my viewmodel to the activity.
Am I using navGraph viewmodel storage in a wrong way?
full stackTrace
java.lang.RuntimeException: Unable to destroy activity {app/MainActivity}: java.util.ConcurrentModificationException
at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:4941)
at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:4970)
at android.app.servertransaction.DestroyActivityItem.execute(DestroyActivityItem.java:44)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:176)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
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.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextNode(HashMap.java:1441)
at java.util.HashMap$KeyIterator.next(HashMap.java:1465)
at androidx.navigation.NavControllerViewModel.onCleared(NavControllerViewModel.java:62)
at androidx.lifecycle.ViewModel.clear(ViewModel.java:139)
at androidx.lifecycle.ViewModelStore.clear(ViewModelStore.java:62)
at androidx.fragment.app.FragmentManagerViewModel.clearNonConfigState(FragmentManagerViewModel.java:160)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1026)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2659)
at androidx.fragment.app.FragmentManagerImpl.dispatchDestroy(FragmentManagerImpl.java:2644)
at androidx.fragment.app.FragmentController.dispatchDestroy(FragmentController.java:329)
at androidx.fragment.app.FragmentActivity.onDestroy(FragmentActivity.java:366)
at androidx.appcompat.app.AppCompatActivity.onDestroy(AppCompatActivity.java:210)
at android.app.Activity.performDestroy(Activity.java:8048)
at android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1341)
at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:4926)
at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:4970)
at android.app.servertransaction.DestroyActivityItem.execute(DestroyActivityItem.java:44)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:176)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
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)