CoroutineWorker doesn't start - android

I tried to run the job, but I get one error all the time. code:
class UpdaterJob #Inject constructor(
private val context: Context,
workerParams: WorkerParameters
) :
CoroutineWorker(context, workerParams) {
override suspend fun doWork(): Result = //coroutineScope {
withContext(Dispatchers.IO) {
Result.success()
// }
}
companion object {
const val TAG = "UpdateChecker"
fun setupTask(context: Context) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val request = PeriodicWorkRequestBuilder<UpdaterJob>(
1, TimeUnit.DAYS,
1, TimeUnit.HOURS
)
.addTag(TAG)
.setConstraints(constraints)
.build()
// WorkManager.getInstance(context).enqueue(request)
WorkManager.getInstance(context)
.enqueueUniquePeriodicWork(TAG, ExistingPeriodicWorkPolicy.REPLACE, request)
}
fun cancelTask(context: Context) {
WorkManager.getInstance(context).cancelAllWorkByTag(TAG)
}
}
}
I tried to make my DaggerWorkerFactory, by Dagger2: Unable to inject dependencies in WorkManager , but I still get one and the same error, log:
2021-02-02 13:39:15.894 7542-7542/com.rulate.rulateapp.debug
E/AndroidRuntime: FATAL EXCEPTION: main Process:
com.rulate.rulateapp.debug, PID: 7542 java.lang.NoClassDefFoundError:
Failed resolution of:
Landroidx/work/impl/utils/futures/AbstractFuture;
at androidx.work.impl.WorkManagerImpl.initialize(WorkManagerImpl.java:181)
at androidx.work.WorkManager.initialize(WorkManager.java:210)
at com.rulater.rulateapp.ui.App.configureWorkManager(App.kt:60)
at com.rulater.rulateapp.ui.App.onCreate(App.kt:47)
at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1192)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6712)
at android.app.ActivityThread.access$1300(ActivityThread.java:237)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1913)
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.ClassNotFoundException:
androidx.work.impl.utils.futures.AbstractFuture
at java.lang.VMClassLoader.findLoadedClass(Native Method)
at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:738)
at java.lang.ClassLoader.loadClass(ClassLoader.java:363)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at androidx.work.impl.WorkManagerImpl.initialize(WorkManagerImpl.java:181) 
at androidx.work.WorkManager.initialize(WorkManager.java:210) 
at com.rulater.rulateapp.ui.App.configureWorkManager(App.kt:60) 
at com.rulater.rulateapp.ui.App.onCreate(App.kt:47) 
at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1192) 
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6712) 
at android.app.ActivityThread.access$1300(ActivityThread.java:237) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1913) 
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.NoClassDefFoundError: Failed resolution of:
Lcom/google/common/util/concurrent/ListenableFuture;
at androidx.work.impl.WorkManagerImpl.initialize(WorkManagerImpl.java:181) 
at androidx.work.WorkManager.initialize(WorkManager.java:210) 
at com.rulater.rulateapp.ui.App.configureWorkManager(App.kt:60) 
at com.rulater.rulateapp.ui.App.onCreate(App.kt:47) 
at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1192) 
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6712) 
at android.app.ActivityThread.access$1300(ActivityThread.java:237) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1913) 
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.ClassNotFoundException: Didn't find class
"com.google.common.util.concurrent.ListenableFuture" on path:
DexPathList[[zip file
"/data/app/~~hUB4V6hTR0qg-4tdmVBeBg==/com.rulate.rulateapp.debug-qn72fwjfGyiwIXEoVyVyTw==/base.apk"],nativeLibraryDirectories=[/data/app/~~hUB4V6hTR0qg-4tdmVBeBg==/com.rulate.rulateapp.debug-qn72fwjfGyiwIXEoVyVyTw==/lib/x86,
/data/app/~~hUB4V6hTR0qg-4tdmVBeBg==/com.rulate.rulateapp.debug-qn72fwjfGyiwIXEoVyVyTw==/base.apk!/lib/x86,
/system/lib, /system_ext/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:207)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at androidx.work.impl.WorkManagerImpl.initialize(WorkManagerImpl.java:181) 
at androidx.work.WorkManager.initialize(WorkManager.java:210) 
at com.rulater.rulateapp.ui.App.configureWorkManager(App.kt:60) 
at com.rulater.rulateapp.ui.App.onCreate(App.kt:47) 
at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1192) 
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6712) 
at android.app.ActivityThread.access$1300(ActivityThread.java:237) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1913) 
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)

Have you tried explicitly adding guava to your build.gradle dependencies:
implementation 'com.google.guava:guava:28.2-android'

Related

Unable to create androidviewmodel instance [duplicate]

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.

Android : WindowInsetsAnimationCallback error during exec

I'm trying to know when the animation close of the softkeyboard is done. So i try to use this function :
val rootLayout = findViewById<ConstraintLayout>(R.id.root_layout)
rootLayout.setWindowInsetsAnimationCallback(object : WindowInsetsAnimation.Callback(DISPATCH_MODE_STOP) {
override fun onProgress(insets: WindowInsets, runningAnimations: MutableList<WindowInsetsAnimation>): WindowInsets {
//TODO("Not yet implemented")
return insets
}
override fun onEnd(animation: WindowInsetsAnimation) {
super.onEnd(animation)
val showingKeyboard = rootLayout.rootWindowInsets.isVisible(WindowInsets.Type.ime())
if (!showingKeyboard) {
println("Keyboard is now closed")
}
}
})
but when i launch the app on my phone (and several emu) i have to face to this error :
java.lang.NoClassDefFoundError: Failed resolution of: Landroid/view/WindowInsetsAnimation$Callback;
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1251)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3222)
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.ClassNotFoundException: Didn't find class "android.view.WindowInsetsAnimation$Callback" on path: DexPathList[[zip file "/data/app/com.example.buginsetsanimationlistener-wRvK7cMTAxdBF1RCG19tlA==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.buginsetsanimationlistener-wRvK7cMTAxdBF1RCG19tlA==/lib/arm64, /system/lib64, /system/product/lib64]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:230)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at java.lang.Class.newInstance(Native Method) 
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95) 
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45) 
at android.app.Instrumentation.newActivity(Instrumentation.java:1251) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3222) 
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) 
I don't understand what i should do, thanks for your answers !
I finally found my mystake. this method is for API 30+. But i've found another way to achieve my goal :
This is work when i close by myself the soft keyboard.
imm.hideSoftInputFromWindow(rootLayout.windowToken, 0, object : ResultReceiver(null) {
override fun onReceiveResult(resultCode: Int, resultData: Bundle?) {
if (resultCode == InputMethodManager.RESULT_UNCHANGED_HIDDEN ||
resultCode == InputMethodManager.RESULT_HIDDEN) {
//Soft has finished the animation
}
}
}
})
Hope this answer help someone :)

java.lang.RuntimeException: Cannot create an instance of class ViewModel [Kotlin]

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"

Android: ViewModel injected with hilt throws has no zero argument constructor"

I migrated my app from dagger2 to hilt manually. i didn't face any compilation or build errors.
but when I try to run my app, it crashes at the splash screen with this stack:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: pfe.usdb.dictili, PID: 7815
java.lang.RuntimeException: Unable to start activity ComponentInfo{pfe.usdb.dictili/pfe.usdb.dictili.view.auth.SplashScreen}: java.lang.RuntimeException: Cannot create an instance of class pfe.usdb.dictili.viewmodel.auth.AuthVModel
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 pfe.usdb.dictili.viewmodel.auth.AuthVModel
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:106)
at androidx.hilt.lifecycle.HiltViewModelFactory.create(HiltViewModelFactory.java:74)
at androidx.lifecycle.AbstractSavedStateViewModelFactory.create(AbstractSavedStateViewModelFactory.java:69)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:185)
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 pfe.usdb.dictili.view.auth.SplashScreen.getViewModel(Unknown Source:2)
at pfe.usdb.dictili.view.auth.SplashScreen.onCreate(SplashScreen.kt:46)
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<pfe.usdb.dictili.viewmodel.auth.AuthVModel> 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:106) 
at androidx.hilt.lifecycle.HiltViewModelFactory.create(HiltViewModelFactory.java:74) 
at androidx.lifecycle.AbstractSavedStateViewModelFactory.create(AbstractSavedStateViewModelFactory.java:69) 
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:185) 
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 pfe.usdb.dictili.view.auth.SplashScreen.getViewModel(Unknown Source:2) 
at pfe.usdb.dictili.view.auth.SplashScreen.onCreate(SplashScreen.kt:46) 
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) 
it says it cannot create an instance of that viewmodel because it doesn't have a zero argument constructor, but:
1- my viewmodel class is injected with hilt (BaseViewModel is abstract):
class AuthVModel #ViewModelInject constructor(
private val sharedPreferences: PreferencesRepository,
private val authRepository: AuthRepository
) : BaseViewModel()
2- my activity is annotated with AndroidEntryPoint (BaseActivity is abstract):
#AndroidEntryPoint
class SplashScreen : BaseActivity() {
private val viewModel: AuthVModel by viewModels()
3- the repositories the viewmodel is depending on are injected properly and android studio 4.1.1 is showing the injection icon on the left:
class AuthRepository #Inject constructor(
#NonAuthenticatedAuthenticationService private val unauthorizedService: AuthService,
#AuthenticatedAuthenticationService private val authorizedService: AuthService
)
class PreferencesRepository #Inject constructor(
private val sharedPreferences: SharedPreferences
)
I don't know what's happening here, this is not my first time working with this, since I built some apps recently just like this (some code is 100% copied from these projects).
Did you use the required dependency for jetpack components (ViewModel in your case) in your module's gradle.build file?
Namely:
kapt "androidx.hilt:hilt-compiler:$hiltJetpackVer"
implementation "androidx.hilt:hilt-lifecycle-viewmodel:$hiltJetpackVer"
Note that the version is different than the one used for the main hilt dependency.

java.lang.RuntimeException: Unable to destroy activity {MainActivity}: java.util.ConcurrentModificationException

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) 

Categories

Resources