i'm trying to make simple to do app with room data base with mvvm when i try to provider the view model in the list fragment always getting an error for the miss type of the view model provider because he wants a view model store owner type and i'm giving him a THIS of the fragment and i have implementation every thing of model and tried every thing to fix it and still
CodePudding user response:
Why don't you try to use the by viewModels
property delegate?
Something like this
private val viewModel: HomeViewModel by viewModels {
HomeViewModelFactory(AppDatabase.getInstance(requireActivity().application).databaseDao)
}
If you pass arguments to the viewModel you should have a ViewModelFactory as I have (I pass down the Database Dao to the VM). Otherwise it should be really simple to use the property delegate.
Here's an example of my ViewModelFactory class
class HomeViewModelFactory(private val dataSource: DatabaseDao) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(HomeViewModel::class.java))
return HomeViewModel(dataSource) as T
throw IllegalArgumentException("Unknown ViewModel class")
}
}
CodePudding user response:
class listfragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val xml= inflater.inflate(R.layout.fragment_listfragment, container, false)
val list=ArrayList<shopinglist>()
viewmodel= ViewModelProvider(this).get(Listviewmodel::class.java)
error is here
xml.recyclerView.layoutManager= LinearLayoutManager(context, RecyclerView.VERTICAL,false)
xml.recyclerView.adapter=Customadapterforrecyle(this,list)
xml.btnlist.setOnClickListener {
Blockquote
}
return xml
}
}
class Listviewmodel(application: Application): AndroidViewModel(application) {
lateinit var readallitem : LiveData<List<shopinglist>>
lateinit var Reposotory:repository
init {
val dao=database.getdatabase(application).getlistgdao()
Reposotory=repository(dao)
readallitem=Reposotory.getallitem()
}
fun insert(item:shopinglist)=CoroutineScope(Dispatchers.IO).launch {
Reposotory.insert(item)
}
fun delete(item:shopinglist)=CoroutineScope(Dispatchers.IO).launch {
Reposotory.delete(item)
}
}