转载请注明出处:http://blog.csdn.net/a512337862/article/details/78812332
1.本篇博客相关的项目介绍请参考基于kotlin实现的简单个人账户管理APP
2.本篇博客是介绍利用kotlin实现数据库相关。
3.因为第一次用kotlin写项目,对Anko不了解,所以没有使用Anko。
4.本篇博客只介绍代码涉及到的kotlin语法,基本的kotlin语法网上有很多,大家自行查询。
5.因为本人是kotlin初学者,博客如果有任何问题请指出。
Constant是一个常量类,保存了一些需要的使用的常量,数据库名称,表名,数据库表字段名等。
kotlin相关:
1.kotlin中var 用于声明可变变量,val 用于声明只读变量
2.Kotlin的class并不支持static变量,所以需要使用companion object来声明static变量
/**
* Author : BlackHao
* Time : 2017/8/30 15:58
* Description : 常量
*/
class Constant {
companion object {
val DB_NAME = "account.db"
val DB_VERSION = 1
val TABLE_NAME = "AccountTable"
//数据库表字段名
val NAME = "name"
val ACCOUNT = "account"
val PSW = "psw"
val NOTES = "notes"
val CREATE_TIME = "create_time"
val ID = "Id"
//数据库表字段名对应位置
val NAME_INDEX = 1
val ACCOUNT_INDEX = 2
val PSW_INDEX = 3
val NOTES_INDEX = 4
val CREATE_TIME_INDEX = 5
val ID_INDEX = 0
//导出数据库信息路径
val EXPORT_FILE_NAME = "AllAccountExport.txt"
//sp key 登录密码
val KEY_LOGIN_PSW = "psw"
//sp key 是否开启密码登录
val KEY_IS_PSW_LOGIN = "isPswLogin"
}
}
实体数据类,在kotlin中用data class表示:
AccountBean:依次表示账户类型,账户,密码,备注。
ImportBean:账户导入导出的时候是否需要导入导出。
kotlin相关:data class就是一个类中只包含一些数据字段,但构造函数至少有一个参数
/**
* Author : BlackHao
* Time : 2017/8/29 14:02
* Description : 账户信息实体类
*/
data class AccountBean(var name: String, var account: String, var psw: String, var notes: String?
, var createTime: String?, var id: Int) {
constructor() : this("", "", "", "", "", 0)
}
data class ImportBean(var isSelect: Boolean, var bean:AccountBean )
DbHelper是用于创建数据库,继承于SQLiteOpenHelper。这里只实现了创建数据库,没有实现更新。
kotlin相关:
1.kotlin继承用“:”表示
2.kotlin可以使用“${}”直接在string字符串中调用String变量或者常量。例如:val text =”hello ${Constant.NAME}”。
/**
* Author : BlackHao
* Time : 2017/8/30 14:16
* Description : 数据库初始化工具类
*/
class DbHelper(context: Context, DB_NAME: String, DB_VERSION: Int)
: SQLiteOpenHelper(context, DB_NAME, null, DB_VERSION) {
private val createSql = "create table if not exists ${Constant.TABLE_NAME} " +
"(${Constant.ID} integer primary key, ${Constant.NAME} text, ${Constant.ACCOUNT} text, " +
"${Constant.PSW} text, ${Constant.NOTES} text, ${Constant.CREATE_TIME} text)"
override fun onCreate(db: SQLiteDatabase?) = db!!.execSQL(createSql)
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
}
}
DbDao用于数据库的增删改查等的实现,具体的说明代码中都有注释。
kotlin相关:
1.初始化相关的代码可以放在以init关键字开头初始化代码块中
2.arrayListOf用于初始化ArrayList,例如:初始化一个String集合,val stringList = arrayListOf
3.
/**
* Author : BlackHao
* Time : 2017/8/30 15:50
* Description : 数据库操作工具类
*/
class DbDao(context: Context) {
private val dbHelper: DbHelper = DbHelper(context, Constant.DB_NAME, Constant.DB_VERSION)
//SQLiteDatabase
private val db: SQLiteDatabase
init {
db = dbHelper.writableDatabase
}
/**
* 新增账户信息
*/
fun addNewAccount(bean: AccountBean): Boolean {
//新增结果标识
val result: Boolean
db.beginTransaction()
result = try {
//SQLs语句
val sql = "insert into " + Constant.TABLE_NAME +
" (${Constant.NAME}, ${Constant.ACCOUNT}, ${Constant.PSW}, ${Constant.NOTES}, ${Constant.CREATE_TIME}) " +
"values ('${bean.name}', '${bean.account}',' ${bean.psw}', '${bean.notes}', '${bean.createTime}')"
db.execSQL(sql)
db.setTransactionSuccessful()
true
} catch (e: Exception) {
e.printStackTrace()
false
} finally {
//结束事物
db.endTransaction()
}
return result
}
/**
* 查询指定关键字的用户
*/
fun searchAccount(keyword: String): ArrayList {
val accountList = arrayListOf()
//获取游标
val cursor = db.query(Constant.TABLE_NAME, null, null, null, null, null, null)
////判断游标是否为空
if (cursor.moveToFirst()) {
//遍历
for (i in 0 until cursor.count) {
//移动游标
cursor.moveToPosition(i)
val name = cursor.getString(Constant.NAME_INDEX)
val account = cursor.getString(Constant.ACCOUNT_INDEX)
val psw = cursor.getString(Constant.PSW_INDEX)
val notes = cursor.getString(Constant.NOTES_INDEX)
val createTime = cursor.getString(Constant.CREATE_TIME_INDEX)
val id = cursor.getInt(Constant.ID_INDEX)
//判断是否包含keyWord
if (keyword.isEmpty()) {
accountList.add(AccountBean(name, account, psw, notes, createTime, id))
}else if ((name.isNotEmpty() && name.contains(keyword))
|| (account.isNotEmpty() && account.contains(keyword))){
accountList.add(AccountBean(name, account, psw, notes, createTime, id))
}
}
}
cursor.close()
return accountList
}
/**
*修改
*/
fun modifyAccount(bean: AccountBean?): Boolean {
//修改结果标识
val result: Boolean
db.beginTransaction()
result = try {
//SQL语句
val sql_modify = "update ${Constant.TABLE_NAME} " +
"set ${Constant.NAME} = '${bean?.name}', ${Constant.ACCOUNT} = '${bean?.account}'," +
"${Constant.PSW} = '${bean?.psw}', ${Constant.NOTES} = '${bean?.notes}'" +
" where ${Constant.ID} = ${bean!!.id}"
Log.e("TAG", sql_modify)
db.execSQL(sql_modify)
db.setTransactionSuccessful()
true
} catch (e: Exception) {
e.printStackTrace()
Log.e("TAG", e.toString())
false
} finally {
//结束事物
db.endTransaction()
}
return result
}
/**
* 删除
*/
fun delAccount(bean: AccountBean?): Boolean {
//删除结果标识
val result: Boolean
db.beginTransaction()
result = try {
//SQL语句
val sql_del = "delete from ${Constant.TABLE_NAME} where ${Constant.ID} = ${bean!!.id}"
db.execSQL(sql_del)
db.setTransactionSuccessful()
true
} catch (e: Exception) {
e.printStackTrace()
false
} finally {
//结束事物
db.endTransaction()
}
return result
}
/**
* 账户是否存在
*/
fun isAccountExist(bean: AccountBean): Boolean {
//删除结果标识
var result = false
if (bean.name.isEmpty()) {
bean.name = ""
}
val accountList = searchAccount(bean.name)
//遍历accountList,如果账户和名称一样,则认为是同一个账户
accountList.forEach {
if (bean.name == it.name && bean.account == it.account) {
result = true
}
}
return result
}
//关闭数据库
fun closeDb() {
try {
db.close()
} catch (e: Exception) {
e.printStackTrace()
}
}
}
1.因为文字功底有限,所以介绍性的文字不多,但是基本上每句代码都加了注释,理解起来应该不难,如果有任何问题,可以留言。
2.项目源码下载地址:http://download.csdn.net/download/a512337862/10151418