➜ Modelo y Tablas: Category, Product y Cart
Modelo y metodos : Category, Product y Cart | Modelo y metodos : Category, Product y Cart | Carrito de Compra Kotlin
- Category: Representa las categorías del bazar.
- id, nombre.
- Product: Representa los productos disponibles.
- id, nombre, categoría, precio, imagen.
- Cart: Gestiona los productos agregados al carrito.
- id, productoId, cantidad.
//product
class Product {
var id: Int = 0
var name: String = ""
var description:String=""
var price:Double=0.00
var stock:Int=0
var unit: String = ""
var image: String = ""
var category_id: Int = 0
constructor(){}
constructor(
id: Int,
name: String,
description: String,
price: Double,
stock: Int,
unit: String,
image: String,
category_id: Int
) {
this.id = id
this.name = name
this.description = description
this.price = price
this.stock = stock
this.unit = unit
this.image = image
this.category_id = category_id
}
}
// category
class Category {
var id: Int = 0
var name: String = ""
constructor(){}
constructor(id: Int, name: String) {
this.id = id
this.name = name
}
}
//// cart
class Cart {
var id:Int=0
var name: String=""
var price: Double= 0.0
var quantity: Int = 0
var unit:String=""
var image:String=""
constructor(id: Int, name: String, price: Double, quantity: Int, unit: String, image: String) {
this.id = id
this.name = name
this.price = price
this.quantity = quantity
this.unit = unit
this.image = image
}
constructor()
}
-
Métodos principales:
- onCreate: Crea las tablas cuando la base de datos se inicializa por primera vez.
- onUpgrade: Elimina las tablas si existe una actualización de la base de datos.
- insertCategory: Inserta una nueva categoría en la tabla
category. - insertProduct: Inserta un nuevo producto en la tabla
product. - getListProducts: Obtiene todos los productos que pertenecen a una categoría específica.
- addItem: Agrega un artículo al carrito.
- getCart: Devuelve todos los artículos del carrito.
- updateQuantity: Actualiza la cantidad de un artículo en el carrito.
- deleteItem: Elimina un artículo específico del carrito.
- delCart: Elimina todos los artículos del carrito.
// métodos
// insertar Category
fun insertCategory(category: Category):String{
val contenedor = ContentValues()
contenedor.put("_id", category.id)
contenedor.put("name", category.name)
val _DB = this.writableDatabase
var result = _DB.insert(TABLE_CATEGORY_NAME, null, contenedor)
if (result == -1.toLong()){
return "CATEGORY: ERROR"
}else{
return "CATEGORY: OK"
}
}
// insertar Product
fun insertProduct(product: Product):String{
val contenedor = ContentValues()
contenedor.put("_id", product.id)
contenedor.put("name", product.name)
contenedor.put("description", product.description)
contenedor.put("price", product.price)
contenedor.put("stock", product.stock)
contenedor.put("unit", product.unit)
contenedor.put("image", product.image)
contenedor.put("category_id", product.category_id)
val _DB = this.writableDatabase
var result = _DB.insert(TABLE_PRODUCT_NAME, null, contenedor)
if (result == -1.toLong()){
return "PRODUCT: ERROR"
}else{
return "PRODUCT: OK"
}
}
fun getListProducts(category_id:Int):MutableList<Product>{
val list:MutableList<Product> = ArrayList()
val _DB = this.readableDatabase
val sql = "SELECT * FROM $TABLE_PRODUCT_NAME WHERE category_id=$category_id"
val cursor = _DB.rawQuery(sql,null)
if(cursor.moveToFirst()){
do{
val product = Product()
product.id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"))
product.name = cursor.getString(cursor.getColumnIndexOrThrow("name"))
product.description = cursor.getString(cursor.getColumnIndexOrThrow("description"))
product.price = cursor.getDouble(cursor.getColumnIndexOrThrow("price"))
product.stock = cursor.getInt(cursor.getColumnIndexOrThrow("stock"))
product.unit = cursor.getString(cursor.getColumnIndexOrThrow("unit"))
product.image = cursor.getString(cursor.getColumnIndexOrThrow("image"))
product.category_id = cursor.getInt(cursor.getColumnIndexOrThrow("category_id"))
list.add(product)
}while (cursor.moveToNext())
}
return list
}
fun addItem(cart: Cart){
val values = ContentValues()
values.put("_id",cart.id)
values.put("name",cart.name)
values.put("price",cart.price)
values.put("quantity",cart.quantity)
values.put("unit",cart.unit)
values.put("image",cart.image)
val _DB = this.writableDatabase
_DB.insert(TABLE_CART_NAME,null,values)
_DB.close()
}
fun getCart(): Cursor?{
val _DB = this.readableDatabase
return _DB.rawQuery("SELECT * FROM $TABLE_CART_NAME",null)
}
fun updateQuantity(id:Int , qty:Int):Boolean{
val _DB = this.writableDatabase
val contentValues = ContentValues()
contentValues.put("_id",id)
contentValues.put("quantity",qty)
_DB.update(TABLE_CART_NAME,contentValues,"_id=?", arrayOf(id.toString()))
return true
}
fun deleteItem(id:Int):Int{
val _DB = this.writableDatabase
return _DB.delete(TABLE_CART_NAME,"_id = ? ", arrayOf(id.toString()))
}
fun delCart():Int{
val _DB = this.writableDatabase
return _DB.delete(TABLE_CART_NAME,null, null)
}
827 visitas
Capítulo 6 – ApiService »
Descarga el código del proyecto
Descarga el código fuente del proyecto adquiriendo el curso completo
Comprar