0

I have a problem with:

RecyclerView: No adapter attached; skipping layout

I can't define adapter in OnCreate because the list is not ready.

How I can define adapter in OnCreate? or what is a possible solution for resolve my problem?

  • 1
    Possible duplicate of [recyclerview No adapter attached; skipping layout](https://stackoverflow.com/questions/29141729/recyclerview-no-adapter-attached-skipping-layout) – shkschneider Mar 06 '19 at 11:01

2 Answers2

0

In onCreate I did:

  adapter = MyAdapter(this@MyActivity)
  adapter.data = ArrayList()

Then later I just set adapter.date = xxx

In my adapter I have:

class MyAdapter(val activity: MyActivity) :
        RecyclerView.Adapter<MyAdapter.BodyViewHolder>() {

    var data: MutableList<MyModel>? = null
        set(value) {
            field = value
            notifyDataSetChanged()
        }

    override fun getItemCount() = data?.size ?: 0

    fun ViewGroup.inflate(@LayoutRes layoutRes: Int, attachToRoot: Boolean = false): View {
        return LayoutInflater.from(context).inflate(layoutRes, this, attachToRoot)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BodyViewHolder {
        val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.my_layout, parent, false)
        return BodyViewHolder(view)
    }

    override fun onBindViewHolder(holder: BodyViewHolder, position: Int) {
        holder.bindValue(data?.get(position), activity)
    }

    class BodyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        fun bindValue(record: MyModel?, activity: MyActivity) {
            record?.let {
                itemView.mTextView.text = ....
            }
        }
    } 
}

Worth mentioning that the height of my recycler view is wrap_content

 <android.support.v7.widget.RecyclerView
            android:id="@+id/mRecyclerView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
Karim
  • 744
  • 5
  • 9
0

It's totally ok if you don't have data in onCreate. What you need to do is to define the adapter and bind it with your RecyclerView. Once you have data ready, add data to the list in adapter and notify it. Example as below

class MyAdapter: RecyclerView.Adapter<MyViewHolder>() {
    private val data = mutableListOf<MyModel>()

    override fun getItemCount() = data.count()

    fun addData(data : MyModel) {
        // add single data the list or call addAll() to add a group of data. 
        // just remember not to replace the variable
    }

    fun clearData() {

    }

    fun deleteData(id: Int) {

    }
}
user1865027
  • 3,241
  • 5
  • 30
  • 65