Продемонстрирую на полном примере
Создайте свою базу данных таким образом
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
class DBHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
override fun onCreate(db: SQLiteDatabase) {
val createProductsTable = ("CREATE TABLE " + Business.TABLE + "("
+ Business.idKey + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
+ Business.KEY_a + " TEXT, "
+ Business.KEY_b + " TEXT, "
+ Business.KEY_c + " TEXT, "
+ Business.KEY_d + " TEXT, "
+ Business.KEY_e + " TEXT )")
db.execSQL(createProductsTable)
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
db.execSQL("DROP TABLE IF EXISTS " + Business.TABLE)
onCreate(db)
}
companion object {
private val DATABASE_VERSION = 1
private val DATABASE_NAME = "business.db"
}
}
Затем создайте класс для упрощения CRUD -> Создать | Прочитать | Обновить | Удалить
class Business {
var a: String? = null
var b: String? = null
var c: String? = null
var d: String? = null
var e: String? = null
companion object {
const val TABLE = "Business"
const val rowIdKey = "_id"
const val idKey = "id"
const val KEY_a = "a"
const val KEY_b = "b"
const val KEY_c = "c"
const val KEY_d = "d"
const val KEY_e = "e"
}
}
Теперь приходит волшебство
import android.content.ContentValues
import android.content.Context
class SQLiteDatabaseCrud(context: Context) {
private val dbHelper: DBHelper = DBHelper(context)
fun updateCart(id: Int, mBusiness: Business) {
val db = dbHelper.writableDatabase
val valueToChange = mBusiness.e
val values = ContentValues().apply {
put(Business.KEY_e, valueToChange)
}
db.update(Business.TABLE, values, "id=$id", null)
db.close()
}
}
вы должны создать свой ProductsAdapter, который должен возвращать CursorAdapter
Поэтому в действии просто вызовите функцию, подобную этой
internal var cursor: Cursor? = null
internal lateinit var mProductsAdapter: ProductsAdapter
mSQLiteDatabaseCrud = SQLiteDatabaseCrud(this)
try {
val mBusiness = Business()
mProductsAdapter = ProductsAdapter(this, c = todoCursor, flags = 0)
lstProducts.adapter = mProductsAdapter
lstProducts.onItemClickListener = OnItemClickListener { parent, view, position, arg3 ->
val cur = mProductsAdapter.getItem(position) as Cursor
cur.moveToPosition(position)
val id = cur.getInt(cur.getColumnIndexOrThrow(Business.idKey))
mBusiness.e = "this will replace the 0 in a specific position"
mSQLiteDatabaseCrud?.updateCart(id ,mBusiness)
}
cursor = dataBaseMCRUD!!.productsList
mProductsAdapter.swapCursor(cursor)
} catch (e: Exception) {
Log.d("ExceptionAdapter :",""+e)
}