There are a couple of approaches you can implement to save your list of barcode data in your database:
1. you can use custom TypeConverter
for your list of barcode objects, for example you can persist your list of objects as a single string in the following form (comma seperated values): "barcode1,qta1,barcode2,qta2,.."
, the implementation could be like this:
@Entity(tableName = "articoli_server_table")
@TypeConverters(BarcodeListConverter::class)
data class ArticoliServer(
@PrimaryKey(autoGenerate = false)
var codart: String,
var desc: String,
var prezzo_acq: Float,
var prezzo_vend: Float,
var barcode: List<barcode>?,
var qta: Float
)
data class barcode(
var barcode: String,
var qta: Float
)
object BarcodeListConverter {
@TypeConverter
fun toString(barcodeList: List<barcode>?): String? {
if (barcodeList == null) return null
val stringList = mutableListOf<String>()
barcodeList.forEach {
stringList.add(it.barcode)
stringList.add(it.qta.toString())
}
return stringList.joinToString(",")
}
@TypeConverter
fun toBarcodeList(str: String?): List<barcode>? {
if (str == null) return null
val barcodeList = mutableListOf<barcode>()
val strList = str.split(",")
for (i in strList.indices step 2) {
barcodeList.add(barcode(strList[i], strList[i + 1].toFloat()))
}
return barcodeList
}
}
2. You can create a new entity (DB table) in your database for your barcode entities, and create a one to many relationship between your ArticoliServer
and barcode
entities. You can check this page for more info about defining relationship with Room persistence library.
P.S I recommend you to implement the second approach in case you have many barcode objects to persist in DB.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…