I am working with MVVM architecture and I don't get it why am I having this error? My other classes have the same structure and they are working perfectly fine. Below i have shared the code for both my Fragment Class and the ViewModel Class along with the error
Error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.beyond.sellandtrack, PID: 5380
java.lang.RuntimeException: Cannot create an instance of class com.beyond.sellandtrack.screens.dashboard.DashboardViewModel
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:275)
at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:106)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:185)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
at com.beyond.sellandtrack.screens.dashboard.DashboardFragment.onCreateView(DashboardFragment.kt:33)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2698)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:320)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1187)
at androidx.fragment.app.FragmentManager.addAddedFragments(FragmentManager.java:2224)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1997)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1953)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1849)
at androidx.fragment.app.FragmentManager$4.run(FragmentManager.java:413)
at android.os.Handler.handleCallback(Handler.java:809)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7555)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:469)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:963)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:267)
at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:106)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:185)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
at com.beyond.sellandtrack.screens.dashboard.DashboardFragment.onCreateView(DashboardFragment.kt:33)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2698)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:320)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1187)
at androidx.fragment.app.FragmentManager.addAddedFragments(FragmentManager.java:2224)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1997)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1953)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1849)
at androidx.fragment.app.FragmentManager$4.run(FragmentManager.java:413)
at android.os.Handler.handleCallback(Handler.java:809)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7555)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:469)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:963)
Caused by: kotlin.KotlinNullPointerException
at com.beyond.sellandtrack.screens.dashboard.DashboardViewModel.<init>(DashboardViewModel.kt:20)
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:267)
at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:106)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:185)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
at com.beyond.sellandtrack.screens.dashboard.DashboardFragment.onCreateView(DashboardFragment.kt:33)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2698)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:320)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1187)
at androidx.fragment.app.FragmentManager.addAddedFragments(FragmentManager.java:2224)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1997)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1953)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1849)
at androidx.fragment.app.FragmentManager$4.run(FragmentManager.java:413)
at android.os.Handler.handleCallback(Handler.java:809)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7555)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:469)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:963)
I/Process: Sending signal. PID: 5380 SIG: 9
Disconnected from the target VM, address: 'localhost:8600', transport: 'socket'
Fragment Class
class DashboardFragment : Fragment() {
private lateinit var dashboardViewModel: DashboardViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val binding = DataBindingUtil.inflate<FragmentDashboardBinding>(
inflater,R.layout.fragment_dashboard,container,false
)
dashboardViewModel= ViewModelProvider(this).get(DashboardViewModel::class.java)
ViewModel Class
class DashboardViewModel(application: Application) : AndroidViewModel(application) {
lateinit var user: User
private var auth : FirebaseAuth = FirebaseAuth.getInstance()
private var repository: Repository = Repository()
init {
user = repository.getUserData()!!
}
You need to check if the getUserData is not null. in init block
init {
user = repository.getUserData()!! //you are forcefully marking this as non null
}
check if the getUserData() is returning null here or not. Which is null most probably and that's why it's failing
I think you should try Koin to inject and create instance of ViewModel.
Its easy to use and syntax is brief.
https://insert-koin.io/.
// Injected by constructor
class MyViewModel(val repo : MyRepository) : ViewModel()
// declared ViewModel using the viewModel keyword
val myModule : Module = module {
viewModel { MyViewModel(get()) }
single { MyRepository() }
}
// Just get it
class MyActivity() : AppCompatActivity() {
// lazy inject MyViewModel
val myViewModel : MyViewModel by viewModel()
}
I think your DashboardViewModel class should extending from ViewModel() not AndroidViewModel()
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0"
import androidx.lifecycle.ViewModel
class DashboardViewModel : ViewModel()
Related
SOLVED - kapt "androidx.room:room-compiler:$room_version" missing in build.gradle
When i'm adding ViewModelProvider to my code, after opening a fragment in which it's added, my app immediately closes. Below i've provided the whole fragment class and error message. I've tracked the issue, and the application worked perfectly fine, before adding just one line with ViewModelProvider. Any idea why it's happening?
AddFragment
class AddFragment : Fragment() {
private var _binding: FragmentAddBinding? = null
private val binding get() = _binding!!
private lateinit var mTaskViewModel: TaskViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?,
): View? {
// Inflate the layout for this fragment
_binding = FragmentAddBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mTaskViewModel = ViewModelProvider(this)[TaskViewModel::class.java]
binding.newTaskButton.setOnClickListener { insertToDatabase() }
}
private fun insertToDatabase() {
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
ERROR
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.randoo, PID: 25691
java.lang.RuntimeException: Cannot create an instance of class com.example.randoo.data.TaskViewModel
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:320)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:304)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:278)
at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.kt:128)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:187)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:153)
at com.example.randoo.fragments.AddFragment.onViewCreated(AddFragment.kt:33)
at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:3128)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:552)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1890)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1814)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1751)
at androidx.fragment.app.FragmentManager$5.run(FragmentManager.java:538)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7839)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
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:312)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:304)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:278)
at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.kt:128)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:187)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:153)
at com.example.randoo.fragments.AddFragment.onViewCreated(AddFragment.kt:33)
at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:3128)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:552)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1890)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1814)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1751)
at androidx.fragment.app.FragmentManager$5.run(FragmentManager.java:538)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7839)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
Caused by: java.lang.RuntimeException: cannot find implementation for com.example.randoo.data.TaskDatabase. TaskDatabase_Impl does not exist
at androidx.room.Room.getGeneratedImplementation(Room.java:100)
at androidx.room.RoomDatabase$Builder.build(RoomDatabase.java:1486)
at com.example.randoo.data.TaskDatabase$Companion.getDatabase(TaskDatabase.kt:28)
at com.example.randoo.data.TaskViewModel.<init>(TaskViewModel.kt:17)
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:312)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:304)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:278)
at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.kt:128)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:187)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:153)
at com.example.randoo.fragments.AddFragment.onViewCreated(AddFragment.kt:33)
at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:3128)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:552)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1890)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1814)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1751)
at androidx.fragment.app.FragmentManager$5.run(FragmentManager.java:538)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7839)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
TaskDatabase
#Database(entities = [Task::class], version = 1, exportSchema = false)
abstract class TaskDatabase : RoomDatabase() {
abstract fun taskDao(): TaskDao
companion object {
#Volatile
private var INSTANCE: TaskDatabase? = null
fun getDatabase(context: Context): TaskDatabase{
val tempInstance = INSTANCE
if (tempInstance != null){
return tempInstance
}
synchronized(this){
val instance = Room.databaseBuilder(
context.applicationContext,
TaskDatabase::class.java,
"task_database"
).build()
INSTANCE = instance
return instance
}
}
}
}
I need to handle screen rotation so I read about saved state and I tried to implement it bit I cant !
here is the fragment screen :
#AndroidEntryPoint
class ImagePickerFragment : Fragment() {
private lateinit var imagePickerBinding: FragmentImagePickerBinding
private val imagePickerViewModel: ImagePickerViewModel by viewModels {
SavedStateViewModelFactory(activity?.applicationContext as Application, this)
}
private lateinit var imagePickerAdapter: ImagePickerAdapter
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
imagePickerBinding = FragmentImagePickerBinding.inflate(inflater, container, false)
imagePickerBinding.lifecycleOwner = this
observeImageList()
observeSearchText()
observeImageClicked()
return imagePickerBinding.root
}
override fun onSaveInstanceState(outState: Bundle) {
imagePickerViewModel.trigger()
super.onSaveInstanceState(outState)
}
private fun observeImageList() {
imagePickerViewModel.observeImageListData.observe(
viewLifecycleOwner,
EventObserver { imageList ->
initializeImageList(imageList)
})
}
So here I should initialize viewModel with savedstate but this getting error :
09-23 13:10:38.621 26928-26928/com.payback.imagepicker E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.payback.imagepicker, PID: 26928
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.payback.imagepicker/com.payback.imagepicker.manager.base.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.payback.imagepicker.presentation.ui.image_picker.ImagePickerViewModel
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.RuntimeException: Cannot create an instance of class com.payback.imagepicker.presentation.ui.image_picker.ImagePickerViewModel
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.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 com.payback.imagepicker.presentation.ui.image_picker.ImagePickerFragment.getImagePickerViewModel(ImagePickerFragment.kt:30)
at com.payback.imagepicker.presentation.ui.image_picker.ImagePickerFragment.observeImageList(ImagePickerFragment.kt:73)
at com.payback.imagepicker.presentation.ui.image_picker.ImagePickerFragment.onCreateView(ImagePickerFragment.kt:45)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2963)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:518)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:282)
at androidx.fragment.app.FragmentStore.moveToExpectedState(FragmentStore.java:112)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1647)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:3128)
at androidx.fragment.app.FragmentManager.dispatchViewCreated(FragmentManager.java:3065)
at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:2988)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:546)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:282)
at androidx.fragment.app.FragmentStore.moveToExpectedState(FragmentStore.java:112)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1647)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:3128)
at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:3072)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:251)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:502)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:246)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1237)
at android.app.Activity.performStart(Activity.java:6253)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.InstantiationException: java.lang.Class<com.payback.imagepicker.presentation.ui.image_picker.ImagePickerViewModel> has no zero argument constructor
at java.lang.Class.newInstance(Native Method)
at androidx.lifecycle.ViewModelProvider$NewInstanceFact
09-23 13:15:38.690 26928-26928/com.payback.imagepicker I/Process: Sending signal. PID: 26928 SIG: 9
And this is My view model :
#HiltViewModel
class ImagePickerViewModel #Inject constructor(
private val imageListUseCase: ImageListUseCase,
private val responseManager: ResponseManager,
private val savedStateHandle: SavedStateHandle
) : BaseViewModel() {
private val _observeImageListData :
MutableLiveData<Event<ArrayList<Image>>> = savedStateHandle.getLiveData("key")
fun trigger() {
savedStateHandle.set("key", _observeImageClicked.value)
}
Please can any one help me ? I cant understand it well or implement it right so what's wrong?
All of build.gradle files have:
implementation "com.google.dagger:hilt-android:2.28.3-alpha"
kapt "com.google.dagger:hilt-android-compiler:2.28.3-alpha"
implementation "androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha02"
kapt "androidx.hilt:hilt-compiler:1.0.0-alpha02"
kapt "com.google.dagger:hilt-android-compiler:2.28.3-alpha"
implementation "javax.inject:javax.inject:1"
Root's build.gradle:
classpath "com.google.dagger:hilt-android-gradle-plugin:2.28.3-alpha"
App's build.gradle:
android {
...
defaultConfig {
...
javaCompileOptions.annotationProcessorOptions.arguments +=
["room.schemaLocation": "$projectDir/schemas".toString()]
}
MyApplication:
#HiltAndroidApp
class MyApplication : MultiDexApplication() {
override fun onCreate() {
super.onCreate()
Timber.plant(Timber.DebugTree())
}
}
ApiModule:
#InstallIn(SingletonComponent::class) //#InstallIn(ApplicationComponent::class)
#Module
class ApiModule {
#Provides
fun products(retrofit: Retrofit): ProductsApi =
retrofit.create(ProductsApi::class.java)
}
ProductsListViewModel:
class ProductsListViewModel #ViewModelInject constructor(
private val getProductsListUseCase: GetProductsListUseCase
) : BaseViewModel() {
BaseViewModel:
open class BaseViewModel #ViewModelInject constructor() : ViewModel() {
ProductsListFragment:
import androidx.fragment.app.viewModels
//#AndroidEntryPoint
class ProductsListFragment : Fragment(R.layout.fragment_product_list) {
private val productsListViewModel: ProductsListViewModel by viewModels()
...
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
productsListViewModel.getProductsList() //Line 57
ProductsApi:
interface ProductsApi {
#GET("products")
fun getProducts(
#Query("page") page: Int = 1,
#Query("per_page") perPage: Int = 15
): Call<List<ProductResponse>>
}
AppModule:
#InstallIn(SingletonComponent::class) //#InstallIn(ApplicationComponent::class)
#Module
class AppModule {
#Provides
#Singleton
fun resources(application: Application): Resources = application.resources
#Provides
#Singleton
fun gson(): Gson = GsonBuilder().create()
#Provides
#Singleton
fun okHttpClient(baseHttpClient: BaseHttpClient): OkHttpClient = baseHttpClient.okHttpClient
#Provides
#Singleton
fun retrofit(baseRetrofit: BaseRetrofit): Retrofit = baseRetrofit.retrofit
}
RepositoryModule:
#InstallIn(SingletonComponent::class) //#InstallIn(ApplicationComponent::class)
#Module
class RepositoryModule {
#Suppress("PrivatePropertyName")
private val NETWORK_IO = Executors.newFixedThreadPool(5)
#Provides
fun products(productsRemoteDataSource: ProductsRemoteDataSource): ProductsRepository =
ProductsRepositoryImpl(productsRemoteDataSource, NETWORK_IO)
}
ProductsRepositoryImpl:
#Singleton
class ProductsRepositoryImpl #Inject constructor(
private val productsRemoteDataSource: ProductsRemoteDataSource,
private val networkExecutor: Executor
) : ProductsRepository {
ProductsRemoteDataSource:
#Singleton
class ProductsRemoteDataSource #Inject constructor(
private val productsApi: ProductsApi
) : BaseRemoteDataSource() {
MainActivity:
//#AndroidEntryPoint
class MainActivity : AppCompatActivity() {
Error:
2020-08-04 18:17:10.575 2047-2047/? E/LoadedApk: Unable to instantiate appComponentFactory
java.lang.ClassNotFoundException: Didn't find class "androidx.core.app.CoreComponentFactory" on path: DexPathList[[],nativeLibraryDirectories=[/system/priv-app/GoogleSdkSetup/lib/x86, /system/lib, /system/product/lib, /system/lib, /system/product/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:196)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at android.app.LoadedApk.createAppFactory(LoadedApk.java:256)
at android.app.LoadedApk.updateApplicationInfo(LoadedApk.java:370)
at android.app.ActivityThread.handleDispatchPackageBroadcast(ActivityThread.java:5951)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1941)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at com.android.server.SystemServer.run(SystemServer.java:541)
at com.android.server.SystemServer.main(SystemServer.java:349)
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:908)
2020-08-04 18:17:10.582 2047-2047/? E/LoadedApk: Unable to instantiate appComponentFactory
java.lang.ClassNotFoundException: Didn't find class "androidx.core.app.CoreComponentFactory" on path: DexPathList[[],nativeLibraryDirectories=[/system/priv-app/GoogleSdkSetup/lib/x86, /system/lib, /system/product/lib, /system/lib, /system/product/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:196)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at android.app.LoadedApk.createAppFactory(LoadedApk.java:256)
at android.app.LoadedApk.updateApplicationInfo(LoadedApk.java:370)
at android.app.ActivityThread.handleDispatchPackageBroadcast(ActivityThread.java:5951)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1941)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at com.android.server.SystemServer.run(SystemServer.java:541)
at com.android.server.SystemServer.main(SystemServer.java:349)
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:908)
2020-08-04 18:17:10.987 1799-2440/? E/GnssHAL_GnssInterface: gnssSvStatusCb: a: input svInfo.flags is 8
2020-08-04 18:17:10.987 1799-2440/? E/GnssHAL_GnssInterface: gnssSvStatusCb: b: input svInfo.flags is 8
2020-08-04 18:17:11.442 1817-2087/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
2020-08-04 18:17:11.442 1817-2087/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
2020-08-04 18:17:11.795 28568-28568/debug E/AndroidRuntime: FATAL EXCEPTION: main
Process: debug, PID: 28568
java.lang.RuntimeException: Cannot create an instance of class ProductsListViewModel
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.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 ProductsListFragment.getProductsListViewModel(Unknown Source:2)
at ProductsListFragment.setupViewModel(ProductsListFragment.kt:57)
at ProductsListFragment.onViewCreated(ProductsListFragment.kt:37)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:332)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1199)
at androidx.fragment.app.FragmentManager.addAddedFragments(FragmentManager.java:2236)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2009)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1965)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1861)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2641)
at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2589)
at androidx.fragment.app.Fragment.performActivityCreated(Fragment.java:2723)
at androidx.fragment.app.FragmentStateManager.activityCreated(FragmentStateManager.java:346)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1200)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1368)
at androidx.fragment.app.FragmentManager.moveFragmentToExpectedState(FragmentManager.java:1446)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1509)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2637)
at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2589)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:247)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:541)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:201)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1425)
at android.app.Activity.performStart(Activity.java:7825)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3294)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
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)
2020-08-04 18:17:11.795 28568-28568/debug E/AndroidRuntime: Caused by: java.lang.InstantiationException: java.lang.Class<ProductsListViewModel> has no zero argument constructor
at java.lang.Class.newInstance(Native Method)
at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:219)
... 42 more
2020-08-04 18:17:11.990 1799-2440/? E/GnssHAL_GnssInterface: gnssSvStatusCb: a: input svInfo.flags is 8
I had to remove all of APIs from dagger that is not hilt. I mean these:
implementation "com.google.dagger:dagger:$daggerVersion"
implementation "com.google.dagger:dagger-android-support:$daggerVersion"
kapt "com.google.dagger:dagger-android-processor:$daggerVersion"
kapt "com.google.dagger:dagger-compiler:$daggerVersion"
api "com.google.dagger:dagger-android:$daggerVersion"
api "com.google.dagger:dagger-android-support:$daggerVersion"
Then, uncomment all of #AndroidEntryPoint annotations.
(Before removing dagger APIs, if I put #AndroidEntryPoint, I was getting an error):
Did you forget to apply the Gradle Plugin?
Even with + in annotationProcessorOptions.arguments +=!
I'm doing this inside my onCreate method of MainActivity
journalViewModel = new ViewModelProvider(this).get(JournalViewModel.class);
and my ViewModel is as following:
public class JournalViewModel extends AndroidViewModel {
public JournalViewModel(#NonNull Application application) {
super(application);
repository = new JournalRepository(application);
journals = repository.getAllJournals();
}
}
However, I'm getting the error for this line,
journalViewModel = new ViewModelProvider(this).get(JournalViewModel.class);
saying,
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.diaryapp/com.example.diaryapp.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.example.diaryapp.JournalViewModel
As per my knowledge the constructor inside ViewModel shouldn't have any other parameter except the one in my code and both constructor and class should be public.
However, further inside my error logs, I get the error:
java.lang.InstantiationException: java.lang.Class<com.example.diaryapp.JournalViewModel> has no zero argument constructor
Here's the complete error log:
2020-03-23 21:37:18.986 8632-8632/com.example.diaryapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.diaryapp, PID: 8632
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.diaryapp/com.example.diaryapp.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.example.diaryapp.JournalViewModel
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2946)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6823)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: java.lang.RuntimeException: Cannot create an instance of class com.example.diaryapp.JournalViewModel
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.example.diaryapp.MainActivity.onCreate(MainActivity.java:40)
at android.app.Activity.performCreate(Activity.java:7224)
at android.app.Activity.performCreate(Activity.java:7213)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2926)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6823)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: java.lang.InstantiationException: java.lang.Class<com.example.diaryapp.JournalViewModel> 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.example.diaryapp.MainActivity.onCreate(MainActivity.java:40)
at android.app.Activity.performCreate(Activity.java:7224)
at android.app.Activity.performCreate(Activity.java:7213)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2926)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6823)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
You should obtain JournalViewModel like:
journalViewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(JournalViewModel.class);
instead of
journalViewModel = new ViewModelProvider(this).get(JournalViewModel.class);
Not sure about Java, but this worked for me in Kotlin.
You need to define a ViewModelProvidor.Factory:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewModelFactory.setApplication(application)
val journalViewModel = ViewModelProvider(this, viewModelFactory).get(JournalViewModel::class.java)
}
}
object viewModelFactory : ViewModelProvider.Factory {
lateinit var app : Application
fun setApplication(application: Application) {
app = application
}
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return JournalViewModel(app) as T
}
}
I got it working with the help of this answer.
Here's what I did in,
JournalFactory.java
public class JournalFactory extends ViewModelProvider.NewInstanceFactory {
private Application application;
public JournalFactory(#NonNull Application application) {
this.application = application;
}
#NonNull
#Override
public <T extends ViewModel> T create(#NonNull Class<T> modelClass) {
if (modelClass == JournalViewModel.class)
return (T) new JournalViewModel(application);
return null;
}
}
onCreate() method of MainActivity.java
journalViewModel = new ViewModelProvider(this, new JournalFactory(getApplication())).get(JournalViewModel.class);
I'm new to Kotlin and I created a constant array to use in spinner inside of fragment. When I try to run the code, the app crashes. I've tried to find a solution, but couldn't.
The really weird part, it worked perfectly yesterday when I worked on it, and today it's crashes.
this is my fragment:
class PersonalDetailsFragment : Fragment() {
private lateinit var listener: OnChangeFragmentListener
override fun onAttach(context: Context?) {
super.onAttach(context)
listener = getListenerOrThrowException(OnChangeFragmentListener::class.java)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val v = inflater.inflate(R.layout.fragment_personal_deatails, container, false)
v.spinnerAge.adapter = ArrayAdapter<Int>(context, android.R.layout.simple_list_item_1, LIST_AGE)
v.btnGoDetails.setOnClickListener { listener.changeFragment() }
return v
}
this is my Constant class:
class Constant {
companion object {
#JvmField val LIST_AGE = getAgeList()
private fun getAgeList(): Array<Int?> {
val array = arrayOfNulls<Int>(83)
for (i in array.indices){
var age = i + 17
array[i] = age
}
return array
}
}
Error Log:
2019-06-06 19:02:53.732 18331-18331/com.eldareini.kotlin.meet4match
E/tlin.meet4matc: No package ID 7f found for ID 0x7f0d0044.
2019-06-06 19:02:53.732 18331-18331/com.eldareini.kotlin.meet4match
D/AndroidRuntime: Shutting down VM
2019-06-06 19:02:53.736 18331-18331/com.eldareini.kotlin.meet4match E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.eldareini.kotlin.meet4match, PID: 18331
java.lang.ExceptionInInitializerError
at com.eldareini.kotlin.meet4match.signup.PersonalDetailsFragment.onCreateView(PersonalDetailsFragment.kt:57)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2439)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:802)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:733)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x7f0d0044
at android.content.res.Resources.getText(Resources.java:348)
at android.content.res.Resources.getString(Resources.java:441)
at com.eldareini.kotlin.meet4match.Constant.<clinit>(Constant.kt:69)
at com.eldareini.kotlin.meet4match.signup.PersonalDetailsFragment.onCreateView(PersonalDetailsFragment.kt:57)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2439)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:802)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:733)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)