Search code examples
androidkotlinexpandablelistviewexpandablelistadapter

How to initialize Array<List<Model>> in Kotlin?


I have a JSON string which coming from rest API and I'm binding that into List<CategoryDO> object. I have all category/sub-category data into this list object List<CategoryDO> but I don't know how to separate sub-categories from those data into Array<List<CategoryDO>> format.

How can I add sub-category list into Array<List<CategoryDO>> object? How can I declare and initialize Array<List<CategoryDO>> in Kotlin?

All categories should be in List<CategoryDO> format and all sub-categories in Array<List<CategoryDO>> format.

For Example:

List<CategoryDO of Cat-1, CategoryDO of cat-2, ... etc>

Array<List<CategoryDO of SubCat-1 of Cat-1, CategoryDO of SubCat-2 of Cat-1>>, List<CategoryDO of SubCat-12 of Cat-2, CategoryDO of SubCat-22 of Cat-2>>, ...etc>>

CategoryDO data class:

data class CategoryDO(  @SerializedName("Id")
                    @Expose
                    var id: Long? = null,
                    @SerializedName("Name")
                    @Expose
                    var name: String? = null,
                    @SerializedName("SubCategories")
                    @Expose
                    var subCategories: List<CategoryDO>? = null)

Actually, I need to pass this separate Category/Sub-Category things to CategoryAdapter class.

CategoryAdapter class sample:

class CategoryAdapter : BaseExpandableListAdapter {
private var groupItem: List<CategoryDO>
private var contentItem: Array<List<CategoryDO>>
private var context: Context
private var imageOnClickListener: View.OnClickListener

constructor(context: Context, groupItem: List<CategoryDO>, contentItem: Array<List<CategoryDO>>, imageOnClickListener: View.OnClickListener) {
        this.groupItem = groupItem
        this.contentItem = contentItem
        this.context = context
        this.imageOnClickListener = imageOnClickListener
    }
  .
  .
  .
}

Solution

  • If you need to convert a List<CategoryDO> to an Array<List<CategoryDO>> where the inner List is the subcategory list from each CategoryDO, you can map over the original list and convert the results to an array...

    // Given
    val categories: List<CategoryDO> = TODO()
    
    val allSubCats: Array<List<CategoryDO>> = 
        categories.map { it. subCategories }.toTypedArray()