赞
踩
//在plugin中加入kapt插件,否则会报错 apply plugin :'kotlin-kapt' //在depedence中加入room数据库的依赖 implementation ("androidx.room:room-runtime:2.3.0") annotationProcessor ("androidx.room:room-compiler:2.3.0") implementation ("androidx.room:room-ktx:2.3.0") kapt ("androidx.room:room-compiler:2.3.0") //协程的依赖 implementation ("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.1") //引入lifecycle的依赖 implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.3.1")
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
class User(var username: String, var password: String) {
@PrimaryKey(autoGenerate = true)
var id: Long = 0
override fun toString(): String {
return "id为:${id}用户名为:$username:密码为$password"
}
}
import androidx.room.* import com.mykotlintest.database.entity.User @Dao interface UserDao { @Insert fun insertUser(user: User):Long @Update fun updateUser(user:User):Int @Query("select * from User") fun queryAllUser():List<User> @Delete() fun deleteUser(user: User):Int @Query("delete from User where username=:name") fun deleteByName(name:String):Int @Query("select id,username,password from User where username=:name") fun queryUserByName(name:String):User //验证密码对不对所以需要进行一个按照密码和用户名的查询 @Query("select id,username,password from User where username=:name and password=:password") fun queryUserByName(name:String,password:String):User }
import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import androidx.room.migration.Migration import androidx.sqlite.db.SupportSQLiteDatabase import com.mykotlintest.database.dao.FriendDao import com.mykotlintest.database.dao.MessageDao import com.mykotlintest.database.dao.UserDao import com.mykotlintest.database.entity.Address import com..mykotlintest.database.entity.Friend import com.mykotlintest.database.entity.User import com.mykotlintest.entity.Messages @Database(version = 4, entities = [User::class,Friend::class,Messages::class], exportSchema = false) abstract class AppDatabase : RoomDatabase() { abstract fun userDao(): UserDao //abstract fun addressDao(): AddressDao abstract fun friendDao():FriendDao abstract fun messageDao():MessageDao companion object { private var instance: AppDatabase? = null //新增表时只需要将Migrate重写,然后重写方法,migrate, /* private var Migrate_1_2=object : Migration(1,2){ override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("create table Address (id integer primary key autoincrement not null, name text not null, image text not null)" ) } }*/ //新增一个friend表,用来在address界面点击friendList时,展现出friend的具体信息是什么 private var Migrate_2_3=object : Migration(2,3){ override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("create table Friend(id integer primary key autoincrement not null, name text not null,gender integer not null,nickname text not null," + "wechatNum text not null,address text not null,avatar integer not null)" ) } } //新增了一个消息表。里面存放了和所有人的消息,根据用户的姓名和类别区分,如果是0.说明是发送的消息,如果是1,则是接收的消息 private var Migrate_3_4=object : Migration(3,4){ override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("create table Messages(id integer primary key autoincrement not null, name text not null,message text not null,type integer not null)" ) } } //kotlin的正规双重校验锁写法 fun getDatabaseSingleton2(context: Context): AppDatabase = instance ?: synchronized(AppDatabase::class.java) { instance ?: Room.databaseBuilder( context.applicationContext, AppDatabase::class.java, "app__lang_database" ).addMigrations( Migrate_2_3, Migrate_3_4).allowMainThreadQueries().build().also { instance = it } } //返回一个数据库实例,单利模式,如果没创建过,就新创建一个名字为app_lang_database的数据库 @Synchronized fun getDatabase(context: Context): AppDatabase { instance?.let { return it } return Room.databaseBuilder( context.applicationContext, AppDatabase::class.java, "app__lang_database" ).allowMainThreadQueries() .build().apply { instance = this } } //写一个双重校验的单利模式 fun getDatabaseSingleton(context: Context): AppDatabase { if (instance == null) { synchronized(AppDatabase::class.java) { if (instance == null) { instance = Room.databaseBuilder( context.applicationContext, AppDatabase::class.java, "app__lang_database" ).allowMainThreadQueries().build() .apply { instance = this } } } } return instance!! } } }
Database Navigator添加插件成功后,DBManager会出现在Android Studio的左上角
import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.text.method.HideReturnsTransformationMethod import android.text.method.PasswordTransformationMethod import android.view.MotionEvent import android.view.View import android.widget.Button import android.widget.EditText import android.widget.ImageView import android.widget.TextView import androidx.annotation.CallSuper import com.mykotlintest.database.dao.UserDao import com.mykotlintest.database.database.AppDatabase import com.mykotlintest.recycle.NewsMainActivity import com.mykotlintest.util.KeyboardSetting import com.mykotlintest.util.KeyboardUtils class MainActivity : AppCompatActivity() { var count = 0; var showPassword = false //private lateinit var password:EditText lateinit var name:EditText lateinit var btnGoToRegister:Button //创建出dao接口 private lateinit var userDao:UserDao override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) name =findViewById<EditText>(R.id.textOfName) name.setText(intent?.getStringExtra("username")) //实例化dao接口 userDao=AppDatabase.getDatabaseSingleton2(this).userDao() //这里需要想恢复出用户名 btnGoToRegister=findViewById(R.id.goToRegister) btnGoToRegister.setOnClickListener { startActivityForResult(Intent(this,RegisterActivity::class.java),1) } } //为当前确定登录按钮绑定监听事件 fun sureBtn1(view: View) { var name =findViewById<TextView>(R.id.textOfName) var password = findViewById<EditText>(R.id.textOfPassWord) var message = findViewById<TextView>(R.id.mess) var forgetPW=findViewById<TextView>(R.id.forgetPW) /* * 需要变化的资源,希望从一个锁定的状态变成一个解锁的状态,然后又可以点击后面的眼睛按钮,使密码进行显示 * */ var lockOpen = getDrawable(R.drawable.ic_baseline_lock_open_24) var text = name.text.toString() var text1 =password.text.toString() //从数据库中查找是否存在当前用户,判断用户名和密码是否正确 if (userDao.queryUserByName(text,text1)!=null) { var intent = Intent(this@MainActivity, ThanksActivity::class.java) intent.putExtra("name", text) //传递参数到另一个界面上 startActivity(intent) } else { count++ if (count < 10) { message.setText("密码或用户名有误,你还有${10 - count}次机会") password.setText("") forgetPW.setText("忘记密码?点击找回") } else { message.setText("已锁定,请在10分钟后重试") } } } }
一旦执行此activity,就会创建出数据库,此时数据库就会创建成功,表也会按照实体类的字段属性自动创建出一张表,然后根据安装后的插件DB Browser,就可以查看出自己创建的表内的信息。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。