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 ...
CodePudding user response:
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()
CodePudding user response:
A variable can only reference one thing at a time. If you want multiple things, you should use a mutable collection type like MutableList as the value of your variable and then add each of the items to that collection.
In this case, product.variants is already a list so you could just make a List variable and copy it over without the for loop: variants = product.variants
.