在 Android Studio Kotlin 中从 SQLite 数据库中删除数据

Posted

技术标签:

【中文标题】在 Android Studio Kotlin 中从 SQLite 数据库中删除数据【英文标题】:Removing data from SQLite database in Android Studio Kotlin 【发布时间】:2021-12-11 07:43:48 【问题描述】:

我是使用 Kotlin 在 android Studio 中编码的新手,我觉得我的代码到处都是。现在,我正在尝试从存储药物信息(包括药物名称、强度和方向)的数据库中添加/删除。到目前为止,我已经成功添加到数据库中;但是,从数据库中删除选择让我很难过。

这是显示当前添加到列表中的药物列表:


import android.app.SearchManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.*
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.med_list.*
import kotlinx.android.synthetic.main.medication_info.view.*




class MedListActivity: AppCompatActivity() 

    var listOfMedication = ArrayList<Medication>()
    override fun onCreate(savedInstanceState: Bundle?) 
        super.onCreate(savedInstanceState)
        setContentView(R.layout.med_list)

        LoadQuery("%")

    
    fun LoadQuery(name:String)

        var dbManager = DatabaseManager(this)
        val projections = arrayOf("ID", "Medication", "Strength", "Directions")
        val selectionArgs=arrayOf(name)
        val cursor = dbManager.Query(projections, "Medication like ? ", selectionArgs, "Medication")
        listOfMedication.clear()
        if(cursor.moveToFirst())
            do
                val ID = cursor.getInt(0)
                val Medication = cursor.getString(cursor.getColumnIndex("Medication"))
                val Strength = cursor.getString(cursor.getColumnIndex("Strength"))
                val Directions = cursor.getString(cursor.getColumnIndex("Directions"))

            listOfMedication.add(Medication(ID, Medication, Strength, Directions))

            while (cursor.moveToNext())
        
        var MedicationAdapter = MedicationAdapter(listOfMedication)
        tvListMedication.adapter = MedicationAdapter

        
    
    override fun onCreateOptionsMenu(menu: Menu?): Boolean 

        menuInflater.inflate(R.menu.main_menu,menu)

        val sv = menu!!.findItem(R.id.app_bar_search).actionView as SearchView
        val sm = getSystemService(Context.SEARCH_SERVICE) as SearchManager
        sv.setSearchableInfo(sm.getSearchableInfo(componentName))
        sv.setOnQueryTextListener(object: SearchView.OnQueryTextListener 
            override fun onQueryTextSubmit(query: String?): Boolean 
                Toast.makeText(applicationContext, query, Toast.LENGTH_LONG).show()
                LoadQuery("%" + query + "%")
                return false
            

            override fun onQueryTextChange(p0: String?): Boolean 
                return false
            
        )


        return super.onCreateOptionsMenu(menu)
    

    override fun onOptionsItemSelected(item: MenuItem): Boolean 
        if (item != null) 
            when (item.itemId) 
                R.id.addMedButton -> 
                    var intent = Intent(this, AddToMedListActivity::class.java)
                    startActivity(intent)
                
            
        
            return super.onOptionsItemSelected(item)
    


    inner class MedicationAdapter : BaseAdapter 
        var listOfMedicationAdapter = ArrayList<Medication>()


        constructor(listOfMedicationAdapter: ArrayList<Medication>) : super() 
            this.listOfMedicationAdapter = listOfMedication
        

        override fun getCount(): Int 
            return listOfMedicationAdapter.size
        

        override fun getItem(p0: Int): Any 
            return listOfMedicationAdapter[p0]
        

        override fun getItemId(p0: Int): Long 
            return p0.toLong()
        

        override fun getView(p0: Int, p1: View?, p2: ViewGroup?): View 
          val medication = listOfMedicationAdapter[p0]
            var myView = layoutInflater.inflate(R.layout.medication_info,null)
            myView.tvName.text = medication.name!!
            myView.tvStrength.text = medication.strength!!
            myView.tvDirections.text = medication.directions!!
            return myView
        
    

这是我的数据库管理器


import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.database.sqlite.SQLiteQuery
import android.database.sqlite.SQLiteQueryBuilder
import android.widget.Toast

class DatabaseManager 
companion object 
    val dbName = "Medication List"
    val dbTable = "Medications"
    val colID = "ID"
    val colName = "Medication"
    val colStrength = "Strength"
    val colDirections = "Directions"
    val dbVersion = 1
    val sqlCreateTable = "CREATE TABLE IF NOT EXISTS " +
            dbTable + " (" +
            colID + " INTEGER PRIMARY KEY, " +
            colName + " TEXT, " +
            colStrength + " TEXT, " +
            colDirections + " TEXT);"

    var sqlDB: SQLiteDatabase? = null

    constructor(context:Context)
        var db = DataBaseHelperMedications(context)
        sqlDB = db.writableDatabase
    

    inner class DataBaseHelperMedications:SQLiteOpenHelper
        var context: Context?=null
        constructor(context: Context):super(context,dbName,null, dbVersion)
            this.context=context
        
        override fun onCreate(p0: SQLiteDatabase?) 
            p0!!.execSQL(sqlCreateTable)
            Toast.makeText(this.context, "database is created",Toast.LENGTH_LONG).show()
        

        override fun onUpgrade(p0: SQLiteDatabase?, p1: Int, p2: Int) 
            p0!!.execSQL("Drop table IF EXISTS " + dbTable)
        

    

    fun Insert(values:ContentValues):Long

        val ID = sqlDB!!.insert(dbTable, "",values)
        return ID
    

    fun Query(projection:Array<String>, selection:String, selectionArgs:Array<String>, sortOrder:String): Cursor 
        val qb= SQLiteQueryBuilder()
        qb.tables=dbTable
        val cursor = qb.query(sqlDB, projection, selection, selectionArgs, null, null, sortOrder)
        return cursor
    

以下是添加到药物清单中的活动:


import android.content.ContentValues
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.add_to_med_list.*

class AddToMedListActivity: AppCompatActivity() 
    val dbTable = "Medications"
    override fun onCreate(savedInstanceState: Bundle?) 
        super.onCreate(savedInstanceState)
        setContentView(R.layout.add_to_med_list)
    
    fun buAdd(view: View)
        finish()
        var dbManager = DatabaseManager(this)
        var values = ContentValues()
        values.put("Medication", editTextMedicationName.text.toString())
        values.put("Strength", editTextMedicationStrength.text.toString())
        values.put("Directions", editTextMedicationDirections.text.toString())

        val ID = dbManager.Insert(values)
        if (ID>0)
            Toast.makeText(this, "Medication is added", Toast.LENGTH_LONG).show()
        else
            Toast.makeText(this, "Cannot add Medication", Toast.LENGTH_LONG).show()
        
    

感谢您的帮助!

【问题讨论】:

【参考方案1】:

从数据库中删除选择让我很难过

您可以使用方便的delete 方法。

例如

fun Delete(id: Long):int
    /* returns # of rows deleted (would be 1 or 0 if id is primary key) */
    return sqlDB!!.delete(dbTable,"id=?",arrayOf(id)

【讨论】:

以上是关于在 Android Studio Kotlin 中从 SQLite 数据库中删除数据的主要内容,如果未能解决你的问题,请参考以下文章

Android@Kotlin 在Android studio 中配置Kotlin

android studio 怎么使用kotlin

android studio怎么用kotlin

如何在android Studio中更改Kotlin android项目的名称[重复]

Android首要开发语言:架构师详解在Android Studio上使用Kotlin

android studio安装和配置kotlin