Home > OS >  Viewmodelprovider context type missmatch in fragment
Viewmodelprovider context type missmatch in fragment

Time:08-21

i'm trying to make a simple todo app with room database and mvvm when i try to provider the view model in the fragment i'm always getting an error for the miss type of the view model provider contex 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

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 {
     


    }
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)
    }
}

CodePudding user response:

Make sure You have the appropriate Fragment imported. You might have the one from the android.app package:

import android.app.Fragment;

This one does not implement the ViewModelStoreOwner interface. On the other hand the Fragment from the androidx.fragment.app package does. Replace the previous import with this one:

import androidx.fragment.app.Fragment;
  • Related