Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin showed type mismatch in fragment

I have a fragment with RecyclerAdapter inside it. I want to initialize the adapter in the onCreateView method but it throws the error of "Type mismatch. Required : Context , Found : FragmentActivity" in this statement

I have no idea why the first one showed this error and the second one did not contains compile time error.

Error shown

recyclerView!!.adapter = RestaurantMenuAdapter(activity)

No Error shown

recyclerView!!.layoutManager = LinearLayoutManager(activity)

Fragment.kt

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                          savedInstanceState: Bundle?): View? {
    // Inflate the layout for this fragment
    val view = inflater.inflate(R.layout.fragment_restaurant_menu, container, false)
    recyclerView = view.findViewById(R.id.restaurant_container)
    recyclerView!!.adapter = RestaurantMenuAdapter(activity)
    recyclerView!!.layoutManager = LinearLayoutManager(activity)

RecyclerAdapter.kt

class RestaurantMenuAdapter  (val context : Context) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val inflater = parent.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        return object : RecyclerView.ViewHolder(inflater.inflate(R.layout.item_menu1, parent, false)) {

        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {

    }

    override fun getItemCount(): Int {
        return 10
    }
}
like image 322
Long Ranger Avatar asked Jan 10 '18 08:01

Long Ranger


3 Answers

Change this to-:

recyclerView!!.adapter = RestaurantMenuAdapter(activity)

To-:

recyclerView!!.adapter = RestaurantMenuAdapter(activity.applicationContext)
like image 156
Shivam Oberoi Avatar answered Nov 13 '22 06:11

Shivam Oberoi


recyclerView!!.adapter = RestaurantMenuAdapter(this)

To

recyclerView!!.adapter = RestaurantMenuAdapter(this.requireActivity())
like image 45
Shivam Tripathi Avatar answered Nov 13 '22 04:11

Shivam Tripathi


Keep the adapter as it and just use "activity!!" where you are initializing adapter.

recyclerView.adapter = RestaurantMenuAdapter(activity!!)

Your adapter will remain same.

class RestaurantMenuAdapter  (val context : Context) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
    val inflater = parent.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
    return object : RecyclerView.ViewHolder(inflater.inflate(R.layout.item_menu1, parent, false)) {

    }
}

override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {

}

override fun getItemCount(): Int {
    return 10
}
}
like image 2
Nauman Ash Avatar answered Nov 13 '22 06:11

Nauman Ash