在Android Studio用Kotlin语言,根据Android数据存储的内容,综合应用SQLite数据库和SQLiteOpenHelper实现一个共享生词本应用程序,熟练掌握SQLite的操作。
时间: 2023-11-28 20:48:50 浏览: 140
基于SQLite数据库的Android应用.
首先,我们需要定义一个数据模型类来表示生词本的单词和解释,如下所示:
```kotlin
data class Word(val id: Long = -1, val word: String, val meaning: String)
```
接下来,我们需要创建一个类来管理SQLite数据库和表格的创建,更新和查询。这个类应该继承自SQLiteOpenHelper类,如下所示:
```kotlin
class WordDatabaseHelper(
context: Context,
name: String? = null,
factory: SQLiteDatabase.CursorFactory? = null,
version: Int = 1
) : SQLiteOpenHelper(context, name, factory, version) {
companion object {
private const val DATABASE_NAME = "word.db"
private const val DATABASE_VERSION = 1
const val TABLE_NAME = "words"
const val ID = "_id"
const val WORD = "word"
const val MEANING = "meaning"
}
override fun onCreate(db: SQLiteDatabase?) {
val createTableSql = """
CREATE TABLE $TABLE_NAME (
$ID INTEGER PRIMARY KEY AUTOINCREMENT,
$WORD TEXT NOT NULL,
$MEANING TEXT NOT NULL
)
""".trimIndent()
db?.execSQL(createTableSql)
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
val dropTableSql = "DROP TABLE IF EXISTS $TABLE_NAME"
db?.execSQL(dropTableSql)
onCreate(db)
}
}
```
在这个类中,我们定义了数据库的名称和版本,以及表格的名称和列名。在onCreate()方法中,我们创建了一个名为words的表格,并定义了三个列:_id,word和meaning。在onUpgrade()方法中,我们删除了旧表格并重新创建。
接下来,我们可以创建一个单例类来管理数据库的操作,如下所示:
```kotlin
object WordDatabaseManager {
private lateinit var dbHelper: WordDatabaseHelper
private lateinit var db: SQLiteDatabase
fun init(context: Context) {
dbHelper = WordDatabaseHelper(context, WordDatabaseHelper.DATABASE_NAME, null, WordDatabaseHelper.DATABASE_VERSION)
db = dbHelper.writableDatabase
}
fun insert(word: Word): Boolean {
val contentValues = ContentValues().apply {
put(WordDatabaseHelper.WORD, word.word)
put(WordDatabaseHelper.MEANING, word.meaning)
}
val result = db.insert(WordDatabaseHelper.TABLE_NAME, null, contentValues)
return result != -1L
}
fun queryAll(): List<Word> {
val cursor = db.query(
WordDatabaseHelper.TABLE_NAME,
arrayOf(WordDatabaseHelper.ID, WordDatabaseHelper.WORD, WordDatabaseHelper.MEANING),
null,
null,
null,
null,
null
)
val wordList = mutableListOf<Word>()
while (cursor.moveToNext()) {
val id = cursor.getLong(cursor.getColumnIndex(WordDatabaseHelper.ID))
val word = cursor.getString(cursor.getColumnIndex(WordDatabaseHelper.WORD))
val meaning = cursor.getString(cursor.getColumnIndex(WordDatabaseHelper.MEANING))
wordList.add(Word(id, word, meaning))
}
cursor.close()
return wordList
}
fun delete(id: Long): Boolean {
val result = db.delete(WordDatabaseHelper.TABLE_NAME, "${WordDatabaseHelper.ID} = ?", arrayOf(id.toString()))
return result > 0
}
}
```
在这个类中,我们使用WordDatabaseHelper类创建了一个数据库,并定义了三个常见的操作:插入,查询和删除。在insert()方法中,我们创建了一个ContentValues对象并将单词和解释添加到其中,然后使用insert()方法将其插入到数据库中。在queryAll()方法中,我们使用query()方法查询所有单词并返回它们的列表。在delete()方法中,我们使用delete()方法根据_id删除一个单词。
现在我们可以在Activity中使用这个类,如下所示:
```kotlin
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
WordDatabaseManager.init(this)
binding.btnAdd.setOnClickListener {
val word = binding.etWord.text.toString()
val meaning = binding.etMeaning.text.toString()
if (word.isNotEmpty() && meaning.isNotEmpty()) {
val result = WordDatabaseManager.insert(Word(word = word, meaning = meaning))
if (result) {
Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show()
binding.etWord.setText("")
binding.etMeaning.setText("")
} else {
Toast.makeText(this, "添加失败", Toast.LENGTH_SHORT).show()
}
} else {
Toast.makeText(this, "请输入单词和解释", Toast.LENGTH_SHORT).show()
}
}
binding.btnQuery.setOnClickListener {
val words = WordDatabaseManager.queryAll()
val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, words)
binding.lvWords.adapter = adapter
}
binding.lvWords.setOnItemClickListener { _, _, position, _ ->
val word = binding.lvWords.adapter.getItem(position) as Word
val dialog = AlertDialog.Builder(this)
.setTitle("删除单词")
.setMessage("确定要删除单词${word.word}吗?")
.setPositiveButton("确定") { _, _ ->
val result = WordDatabaseManager.delete(word.id)
if (result) {
Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show()
binding.btnQuery.performClick()
} else {
Toast.makeText(this, "删除失败", Toast.LENGTH_SHORT).show()
}
}
.setNegativeButton("取消", null)
.create()
dialog.show()
}
}
}
```
在这个Activity中,我们使用WordDatabaseManager类来执行添加,查询和删除操作,并使用ListView显示所有单词。当用户点击一个单词时,我们会显示一个对话框询问用户是否要删除该单词。
现在,我们已经成功地创建了一个共享生词本应用程序,并使用SQLite数据库和SQLiteOpenHelper实现了数据存储和管理。
阅读全文