Gilson Lim
Gilson Lim

Reputation: 27

This error occur to me E/RecyclerView: No adapter attached; skipping layout

I get that my layoutManager and adapter seem to be null but i don't quite get why is it null.

here is the code for my GpsFragment.kt

class GpsFragment : Fragment() {

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    (context as AppCompatActivity).supportActionBar!!.title = "Gps"
    val root = inflater.inflate(R.layout.fragment_gps, container, false)

        showCars()

    return root
}

private fun showCars(){
    val cars = listOf(
        Cars("Bezza","0.17263","3.267834"),
        Cars("Bezza","0.17263","3.267834"),
        Cars("Bezza","0.17263","3.267834"),
        Cars("Bezza","0.17263","3.267834")
    )

    myCarlist?.layoutManager = LinearLayoutManager(activity)
    myCarlist?.adapter = CarAdapter(cars)
}

Here is the code for my model class Cars.kt

data class Cars(val name: String = "-",
            val latitude: String = "-",
            val longtitude: String = "-")

And this the code for my adapter CarAdapter.kt

class CarAdapter (private val cars : List<Cars>) : RecyclerView.Adapter<CarAdapter.CarViewHolder>(){

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CarViewHolder {
    val inflater = LayoutInflater.from(parent.context).inflate(R.layout.list_layout, parent, false)

    return  CarViewHolder(inflater)
}

override fun getItemCount() = cars.size

override fun onBindViewHolder(holder: CarViewHolder, position: Int) {
    val car = cars[position]

    holder.view.carname.text = car.name
    holder.view.latitude.text = car.latitude
    holder.view.longtitude.text = car.longtitude

}

class CarViewHolder(val view:View) : RecyclerView.ViewHolder(view)

}

Upvotes: 0

Views: 40

Answers (1)

Parth
Parth

Reputation: 791

try calling your method showcars() in onViewCreated insted oncreateView because

The docs for Fragment.onCreateView() now says:

It is recommended to only inflate the layout in this method and move logic that operates on the returned View to onViewCreated(View, Bundle).

Upvotes: 1

Related Questions