For Loop for Model class to take Products and Variants

Issue

Model Class :

Product List :

    data class ProductList (
    var error : Boolean? = null,
    var total : String? = null,
    var total_page_no : Int? = null,
    var current_page_no : Int? = null,
    var data : ArrayList<Products> = arrayListOf()
)

Products :

    @Entity(tableName = "Product")
    data class Products (

    @PrimaryKey(autoGenerate = false)
    @ColumnInfo(name = "id")
    var id : Int = 0,

    @ColumnInfo(name = "name")
    var name  : String? = null,

    @ColumnInfo(name = "variants")
    var variants : List<Variants> = listOf()            
)

Variants :

    @Entity(tableName = "Variant")
    data class Variants (

    @PrimaryKey(autoGenerate = false)
    @ColumnInfo(name = "id")
    var id : Int  = 0,

    @ColumnInfo(name = "product_id", index = true)
    var product_id : Int?  = null,

    @ColumnInfo(name = "measurement")
    var measurement : String?  = null,

    @ColumnInfo(name = "discounted_price")
    var discounted_price : String?  = null,

    @ColumnInfo(name = "cart_count")
    var cart_count : String?  = null,

    @ColumnInfo(name = "is_notify_me")
    var is_notify_me : Boolean? = null

)

Now i want to store all products in Products Variable like ( var products = listofallProducts )

and store all variants in Variants Variable like ( var variants = listofallVariants )

Am Already tried like this :

for (i in 0 until response.data.size) {
                    val product: Products = response.data.get(i)
                    for (j in 0 until product.variants.size) {
                        variants = product.variants.get(j)
                    }
                }

But it doesn’t work …

Solution

Since response.data returns list of Product you can easily get all products

val products: List<Product> = response.data

and to store all variants into a list we can do something like this

val variants: List<Variant> = response.data.map { it.variants }.flatten()

Answered By – Hussain

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published