Kotlin 中的 Android SQLite 数据库
Android 带有一个数据库包的内置实现,它是 SQLite,这是一种开源 SQL 数据库,可在设备中以文本形式存储数据。在本文中,我们将看看 Android SQLite 在 Kotlin 中的实现。
SQLite 是一个独立的、高可靠性的、嵌入式的、功能齐全的、公共领域的 SQL 数据库引擎。它是世界上使用最广泛的数据库引擎。它是一个进程内库,其代码是公开的。它可以免费用于任何目的,商业或私人。它基本上是一个嵌入式 SQL 数据库引擎。 SQLite 可以轻松读写普通磁盘文件,因为它没有像 SQL 那样的任何单独的服务器。 SQLite 数据库文件格式是跨平台的,因此任何人都可以轻松地在 32 位和 64 位系统之间复制数据库。由于所有这些功能,它是作为应用程序文件格式的流行选择。
我们将在本文中构建什么?
我们将构建一个使用 SQLite 存储数据的简单应用程序,我们还将实现检索数据的方法。下面是一个示例视频,展示了我们将要做的事情。
分步实施
第 1 步:创建一个新项目
要在 Android Studio 中创建新项目,请参阅如何在 Android Studio 中创建/启动新项目。请注意,选择Kotlin作为编程语言。
第 2 步:授予访问 AndroidManifest.xml 文件中存储的权限
导航到app > AndroidManifest.xml并将以下代码添加到其中。
XML
XML
Kotlin
package com.release.gfg1
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
class DBHelper(context: Context, factory: SQLiteDatabase.CursorFactory?) :
SQLiteOpenHelper(context, DATABASE_NAME, factory, DATABASE_VERSION) {
// below is the method for creating a database by a sqlite query
override fun onCreate(db: SQLiteDatabase) {
// below is a sqlite query, where column names
// along with their data types is given
val query = ("CREATE TABLE " + TABLE_NAME + " ("
+ ID_COL + " INTEGER PRIMARY KEY, " +
NAME_COl + " TEXT," +
AGE_COL + " TEXT" + ")")
// we are calling sqlite
// method for executing our query
db.execSQL(query)
}
override fun onUpgrade(db: SQLiteDatabase, p1: Int, p2: Int) {
// this method is to check if table already exists
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME)
onCreate(db)
}
// This method is for adding data in our database
fun addName(name : String, age : String ){
// below we are creating
// a content values variable
val values = ContentValues()
// we are inserting our values
// in the form of key-value pair
values.put(NAME_COl, name)
values.put(AGE_COL, age)
// here we are creating a
// writable variable of
// our database as we want to
// insert value in our database
val db = this.writableDatabase
// all values are inserted into database
db.insert(TABLE_NAME, null, values)
// at last we are
// closing our database
db.close()
}
// below method is to get
// all data from our database
fun getName(): Cursor? {
// here we are creating a readable
// variable of our database
// as we want to read value from it
val db = this.readableDatabase
// below code returns a cursor to
// read data from the database
return db.rawQuery("SELECT * FROM " + TABLE_NAME, null)
}
companion object{
// here we have defined variables for our database
// below is variable for database name
private val DATABASE_NAME = "GEEKS_FOR_GEEKS"
// below is the variable for database version
private val DATABASE_VERSION = 1
// below is the variable for table name
val TABLE_NAME = "gfg_table"
// below is the variable for id column
val ID_COL = "id"
// below is the variable for name column
val NAME_COl = "name"
// below is the variable for age column
val AGE_COL = "age"
}
}
Kotlin
package com.release.gfg1
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// below code is to add on click
// listener to our add name button
addName.setOnClickListener{
// below we have created
// a new DBHelper class,
// and passed context to it
val db = DBHelper(this, null)
// creating variables for values
// in name and age edit texts
val name = enterName.text.toString()
val age = enterAge.text.toString()
// calling method to add
// name to our database
db.addName(name, age)
// Toast to message on the screen
Toast.makeText(this, name + " added to database", Toast.LENGTH_LONG).show()
// at last, clearing edit texts
enterName.text.clear()
enterAge.text.clear()
}
// below code is to add on click
// listener to our print name button
printName.setOnClickListener{
// creating a DBHelper class
// and passing context to it
val db = DBHelper(this, null)
// below is the variable for cursor
// we have called method to get
// all names from our database
// and add to name text view
val cursor = db.getName()
// moving the cursor to first position and
// appending value in the text view
cursor!!.moveToFirst()
Name.append(cursor.getString(cursor.getColumnIndex(DBHelper.NAME_COl)) + "\n")
Age.append(cursor.getString(cursor.getColumnIndex(DBHelper.AGE_COL)) + "\n")
// moving our cursor to next
// position and appending values
while(cursor.moveToNext()){
Name.append(cursor.getString(cursor.getColumnIndex(DBHelper.NAME_COl)) + "\n")
Age.append(cursor.getString(cursor.getColumnIndex(DBHelper.AGE_COL)) + "\n")
}
// at last we close our cursor
cursor.close()
}
}
}
步骤 3:使用 activity_main.xml 文件
导航到app > res > layout > activity_main.xml 。将以下代码添加到您的文件中。下面是activity_main.xml的代码。
XML
第 4 步:为 SQLite 操作创建一个新类
导航到app > Java > 您项目的包名称 > 右键单击它 > 新建 > Kotlin 类并将其命名为DBHelper并将以下代码添加到其中。为了使代码更易于理解,添加了注释。
科特林
package com.release.gfg1
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
class DBHelper(context: Context, factory: SQLiteDatabase.CursorFactory?) :
SQLiteOpenHelper(context, DATABASE_NAME, factory, DATABASE_VERSION) {
// below is the method for creating a database by a sqlite query
override fun onCreate(db: SQLiteDatabase) {
// below is a sqlite query, where column names
// along with their data types is given
val query = ("CREATE TABLE " + TABLE_NAME + " ("
+ ID_COL + " INTEGER PRIMARY KEY, " +
NAME_COl + " TEXT," +
AGE_COL + " TEXT" + ")")
// we are calling sqlite
// method for executing our query
db.execSQL(query)
}
override fun onUpgrade(db: SQLiteDatabase, p1: Int, p2: Int) {
// this method is to check if table already exists
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME)
onCreate(db)
}
// This method is for adding data in our database
fun addName(name : String, age : String ){
// below we are creating
// a content values variable
val values = ContentValues()
// we are inserting our values
// in the form of key-value pair
values.put(NAME_COl, name)
values.put(AGE_COL, age)
// here we are creating a
// writable variable of
// our database as we want to
// insert value in our database
val db = this.writableDatabase
// all values are inserted into database
db.insert(TABLE_NAME, null, values)
// at last we are
// closing our database
db.close()
}
// below method is to get
// all data from our database
fun getName(): Cursor? {
// here we are creating a readable
// variable of our database
// as we want to read value from it
val db = this.readableDatabase
// below code returns a cursor to
// read data from the database
return db.rawQuery("SELECT * FROM " + TABLE_NAME, null)
}
companion object{
// here we have defined variables for our database
// below is variable for database name
private val DATABASE_NAME = "GEEKS_FOR_GEEKS"
// below is the variable for database version
private val DATABASE_VERSION = 1
// below is the variable for table name
val TABLE_NAME = "gfg_table"
// below is the variable for id column
val ID_COL = "id"
// below is the variable for name column
val NAME_COl = "name"
// below is the variable for age column
val AGE_COL = "age"
}
}
第 5 步:使用 MainActivity.kt 文件
转到MainActivity.kt文件并参考以下代码。下面是MainActivity.kt文件的代码。代码中添加了注释以更详细地理解代码。
科特林
package com.release.gfg1
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// below code is to add on click
// listener to our add name button
addName.setOnClickListener{
// below we have created
// a new DBHelper class,
// and passed context to it
val db = DBHelper(this, null)
// creating variables for values
// in name and age edit texts
val name = enterName.text.toString()
val age = enterAge.text.toString()
// calling method to add
// name to our database
db.addName(name, age)
// Toast to message on the screen
Toast.makeText(this, name + " added to database", Toast.LENGTH_LONG).show()
// at last, clearing edit texts
enterName.text.clear()
enterAge.text.clear()
}
// below code is to add on click
// listener to our print name button
printName.setOnClickListener{
// creating a DBHelper class
// and passing context to it
val db = DBHelper(this, null)
// below is the variable for cursor
// we have called method to get
// all names from our database
// and add to name text view
val cursor = db.getName()
// moving the cursor to first position and
// appending value in the text view
cursor!!.moveToFirst()
Name.append(cursor.getString(cursor.getColumnIndex(DBHelper.NAME_COl)) + "\n")
Age.append(cursor.getString(cursor.getColumnIndex(DBHelper.AGE_COL)) + "\n")
// moving our cursor to next
// position and appending values
while(cursor.moveToNext()){
Name.append(cursor.getString(cursor.getColumnIndex(DBHelper.NAME_COl)) + "\n")
Age.append(cursor.getString(cursor.getColumnIndex(DBHelper.AGE_COL)) + "\n")
}
// at last we close our cursor
cursor.close()
}
}
}
现在运行您的应用程序并查看输出。
输出: