我正在尝试使用Kotlin在我的Fragment中使用Android体系结构组件创建ViewModel的实例,但出现下一个错误:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: campanoon.cronometrohiit, PID: 3871
java.lang.RuntimeException: Cannot create an instance of class campanoon.cronometrohiit.RoutinesViewModel
at android.arch.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:153)
我的ViewModel:
class RoutinesViewModel(application: Application) : ViewModel() {
private val routineDao = AppDatabase.getDatabase(application).routineDao()
fun generateSimpleList() : List<Routine> {
routineDao.insertRoutine(Routine(null,"Prueba 1", "00:10","00:30","30:00",3))
routineDao.insertRoutine(Routine(null,"Prueba 2", "00:15","00:30","15:00",2))
routineDao.insertRoutine(Routine(null,"Prueba 3", "00:20","00:30","20:00",5))
return routineDao.getRoutines()
}
}
我的片段:
class RoutinesFragment : Fragment() {
private lateinit var routinesViewModel : RoutinesViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val v : View = inflater.inflate(R.layout.fragment_routines, container, false)
routinesViewModel= ViewModelProviders.of(this).get(RoutinesViewModel::class.java)
return v
}
我不知道我在做什么错:(
答案 0 :(得分:1)
如果您需要将参数传递到ViewModel
的构造函数中,则需要使用ViewModel.Factory
open class RoutinesViewModelFactory(private val application: Application) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(RoutinesViewModel::class.java)) {
return RoutinesViewModel(application) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}
例如,如果您使用匕首,则会在片段中注入RoutinesViewModelFactory
实例
@Inject lateinit var routinesViewModelFactory: RoutinesViewModelFactory
,然后通过调用
检索ViewModel
实例
routinesViewModel = ViewModelProviders.of(this, RoutinesViewModelFactory).get(RoutinesViewModel::class.java)