Search code examples
androidkotlinandroid-recyclerviewdialogadapter

populating a RecyclerView in a Dialog


I have found a solution and its attached as an answer

I'm currently having trouble populating a layout in a dialog with information from my adapter. The data is fetched from the API and passed into my data class but since the recyclerview that I'm trying to reference is in the Dialog's layout file, not in the file i'm using to call said dialog, the view just returns an null.

Here is my code for context.

CheckboxActivity.kt (Just the callback) people_list is returning null

private val callbackGETUSERS = object : Callback<List<Users>> {
    override fun onFailure(call: Call<List<Users>>, t: Throwable) {
        Log.e("API-GET-USERS", "Problem GETTING USERS", t)        }

    override fun onResponse(call: Call<List<Users>>, response: Response<List<Users>>) {

        val result = UsersResult(response.body() ?: return run {
            Log.e("API-ME", "Problem calling USERS")
        })

        peopleList = result
        people_list.adapter = ManagePeopleAdapter(result)
    }

}

d_manage_people.xml (the dialog resource file)

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="16dp">

<TextView
        android:id="@+id/manage_people_title"
        android:gravity="center"
        android:height="24dp"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        style="@style/Subtitle1"
        android:text="Create Item"
        android:layout_marginBottom="16dp"
        android:layout_gravity="center"/>

<androidx.recyclerview.widget.RecyclerView
        android:id="@+id/people_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

</androidx.recyclerview.widget.RecyclerView>

and here is my error

java.lang.IllegalStateException: people_list must not be null

By the way I'm using a plugin that allows me to not use findViewById

Any help would be appreciated :)


Solution

  • The issue happened to be with me not attaching the view's context

    Instead of calling the Recycler View in the CallBack like

    people_list
    

    and then setting the adapter from there, I just had the callback call a function that then created the dialog and I used context from that to reach the RecyclerView

     val dialog = AlertDialog.Builder(this)
        val view = layoutInflater.inflate(R.layout.d_manage_people, null)
        dialog.setView(view)
    
        view.manage_people_title.text = "Manage People"
    
        val adapter = ManagePeopleAdapter(result)
        view.people_list.adapter = adapter
        view.people_list.layoutManager = LinearLayoutManager(this)