我正在尝试使用recyclerview和房间库制作一个简单的ToDoList应用程序。我正在关注android开发人员codelab使用room和mvvm架构,我似乎遇到了麻烦。我已经设置了应用程序的每一层,但在尝试使用ViewModelProvider实例化ViewModel时出错。这是我的ViewModel类中的代码。
class TaskViewModel(application: Application) : AndroidViewModel(application) {
private val repository : TaskRepository
val allTasks : LiveData<List<Task>>
init{
val tasksDao = TaskRoomDatabase.getDatabase(application)!!.taskDao()
repository = TaskRepository(tasksDao)
allTasks = repository.allTasks
}
fun saveTask(task : Task) = viewModelScope.launch(Dispatchers.IO){
repository.saveTask(task)
}
}
这是我的MainFragment中的代码,我正试图从中初始化ViewModel:
class MainFragment() : Fragment() {
private lateinit var recyclerView : RecyclerView
private lateinit var sharedTaskViewModel : TaskViewModel
private lateinit var fab : FloatingActionButton
var tasks = emptyList<Task>()
private lateinit var adapter : MainRecyclerViewAdapter
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_main, container, false)
fab = view.findViewById(R.id.floatingActionButton)
//Initialize the recyclerview
recyclerView = view.findViewById(R.id.main_recyclerview)
adapter = MainRecyclerViewAdapter()
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(view.context)
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
sharedTaskViewModel = ViewModelProvider(this).get(TaskViewModel::class.java)
fab.setOnClickListener {
fragmentManager!!.beginTransaction().apply {
replace(R.id.fl_fragment_main, NewTaskFragment())
commit()
}
}
}
}
当我运行代码时,我会收到以下消息:
2020-08-09 11:31:00.734 27860-27860/com.robybp.todolist E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.robybp.todolist, PID: 27860
java.lang.RuntimeException: Cannot create an instance of class com.robybp.todolist.view_models.TaskViewModel
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.robybp.todolist.view.fragments.MainFragment.onViewCreated(MainFragment.kt:45)
Caused by: java.lang.InstantiationException: java.lang.Class<com.robybp.todolist.view_models.TaskViewModel> has no zero argument constructor
at java.lang.Class.newInstance(Native Method)
如果问题可能是";Obste";但我只是对room和mvvm体系结构比较熟悉。感谢您的理解。
尝试替换:
sharedTaskViewModel = ViewModelProvider(this).get(TaskViewModel::class.java)
带有
sharedTaskViewModel = ViewModelProvider.AndroidViewModelFactory(application)
.create(TaskViewModel::class.java)