天天看點

Android Room By Kotlin

最近在kotlin環境下,寫了一個room資料庫的demo,各種情況跑了一下,在此總結一下。

涉及情況:增、删、改、查、排序

1、環境搭建

1.1、Android Studio下,建立一個kotlin項目,

1.2、去app的build.gradle中進行一些配置

頂部增加

apply plugin: 'kotlin-kapt'

1

然後

defaultConfig {

        ......

        javaCompileOptions {

            annotationProcessorOptions {

                arguments = ["room.schemaLocation":

                                     "$projectDir/schemas".toString()]

            }

        }

}

1

2

3

4

5

6

7

8

9

1.3、導入依賴

implementation 'android.arch.persistence.room:runtime:1.1.1'

kapt 'android.arch.persistence.room:compiler:1.1.1'

1

2

2、建立一個Application,用于提供全局上下文

class MyApplication : Application() {

    companion object {

        var instance: MyApplication by Delegates.notNull()

        fun instance() = instance

    }

    override fun onCreate() {

        super.onCreate()

        instance = this

    }

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

3、分别建立Student和Teacher(我寫了2張表)

import android.arch.persistence.room.ColumnInfo

import android.arch.persistence.room.Entity

import android.arch.persistence.room.PrimaryKey

@Entity(tableName = "Student")

data class Student(

    @PrimaryKey(autoGenerate = true)

    var studentID: Int?,

    @ColumnInfo(name = "s_name")

    var studentName: String?,

    @ColumnInfo(name = "s_type")

    var studentType: String?

)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

import android.arch.persistence.room.ColumnInfo

import android.arch.persistence.room.Entity

import android.arch.persistence.room.PrimaryKey

@Entity(tableName = "Teacher")

data class Teacher(

    @PrimaryKey(autoGenerate = true)

    var teacherID: Int?,

    @ColumnInfo(name = "t_name")

    var teacherName: String?,

    //教學年限

    @ColumnInfo(name = "t_year")

    var teachYear: Int?

)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

4、與之對應的,分别建立StudentDao和TeacherDao

import android.arch.persistence.room.*

@Dao

interface BaseDao<T> {

    @Insert(onConflict = OnConflictStrategy.REPLACE)

    fun insertAll(list: MutableList<T>)

    @Delete

    fun delete(element: T)

    @Delete

    fun deleteList(elements:MutableList<T>)

    @Delete

    fun deleteSome(vararg elements:T)

    @Update

    fun update(element: T)

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

import android.arch.persistence.room.*

@Dao

interface StudentDao:BaseDao<Student> {

    @Insert(onConflict = OnConflictStrategy.REPLACE)

    fun insert(element:Student)

    @Query("select * from Student")

    fun getAllStudents():MutableList<Student>

    @Query("select * from Student where studentID = :studentID")

    fun getStudnet(studentID:Int):Student

    @Query("select * from Student order by studentID desc ")

    fun getAllByDateDesc():MutableList<Student>

    @Query("delete from Student")

    fun deleteAll()

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

import android.arch.persistence.room.*

@Dao

interface TeacherDao:BaseDao<Teacher> {

    @Insert

    fun insert(element:Teacher)

    @Query("select * from Teacher")

    fun getAllTeachers():MutableList<Teacher>

    @Query("select * from Teacher where teacherID = :teacherID")

    fun getTeacher(teacherID:Int):Teacher

    @Query("select * from Teacher order by t_year desc ")

    fun getAllByDateDesc():MutableList<Teacher>

    @Query("delete from Teacher")

    fun deleteAll()

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

這裡,注意下StudentDao和TeacherDao中,insert上面的注解,有差別,後面會說到

5、接下來,建立AppDataBase

import android.arch.persistence.room.Database

import android.arch.persistence.room.RoomDatabase

import android.arch.persistence.room.Room

@Database(entities = [Student::class, Teacher::class], version = 1)

abstract class AppDataBase : RoomDatabase() {

    abstract fun getStudentDao(): StudentDao

    abstract fun getTeacherDao(): TeacherDao

    companion object {

        val instance = Single.sin

    }

    private object Single {

        val sin :AppDataBase= Room.databaseBuilder(

            MyApplication.instance(),

            AppDataBase::class.java,

            "User.db"

        )

            .allowMainThreadQueries()

            .build()

    }

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

這裡,我用的是 靜态内部類 的單例,還可以寫作

import android.arch.persistence.room.Database

import android.arch.persistence.room.RoomDatabase

import android.arch.persistence.room.Room

@Database(entities = [Student::class, Teacher::class], version = 1)

abstract class AppDataBase : RoomDatabase() {

    abstract fun getStudentDao(): StudentDao

    abstract fun getTeacherDao(): TeacherDao

    companion object {

        @Volatile

        private var instance: AppDataBase? = null

        fun getDBInstace(): AppDataBase {

            if (instance == null) {

                synchronized(AppDataBase::class) {

                    if (instance == null) {

                        instance = Room.databaseBuilder(

                            MyApplication.instance(),

                            AppDataBase::class.java,

                            "User.db"

                        )

                            .allowMainThreadQueries()

                            .build()

                    }

                }

            }

            return instance!!

        }

    }

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

這裡,不做讨論,kotlin的單例,也有多種寫法。

到此為止,準備工作,都做完了。開始實際的使用:

Activity中:

val sDao: StudentDao = AppDataBase.instance.getStudentDao()

var s_1 = Student(1, "s1", "國小")

var s_2 = Student(2, "s2", "國小")

var s_3 = Student(3, "s3", "國小")

var s_6 = Student(6, "s6", "大學")

var s_5 = Student(5, "s5", "大學")

var s_4 = Student(4, "s4", "大學")

var sList: MutableList<Student> = mutableListOf<Student>()

sList.add(s_1)

sList.add(s_2)

sList.add(s_3)

sList.add(s_6)

sList.add(s_5)

sList.add(s_4)

//可以直接把list傳進去,也可以一個一個單獨添加

sDao.insertAll(sList)

var sList_select_1: MutableList<Student> = sDao.getAllStudents()

for (i in sList_select_1.indices) {

     println(sList_select_1.get(i))

}

日志:

    Student(studentID=1, studentName=s1, studentType=國小)

    Student(studentID=2, studentName=s2, studentType=國小)

    Student(studentID=3, studentName=s3, studentType=國小)

    Student(studentID=4, studentName=s4, studentType=大學)

    Student(studentID=5, studentName=s5, studentType=大學)

    Student(studentID=6, studentName=s6, studentType=大學)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

插入,查詢成功,接下來,對資料進行修改:

//注意,這裡我用的是insert,而不是 update

sDao.insert(Student(1, "s1", "大學"))

var sList_select_2: MutableList<Student> = sDao.getAllStudents()

for (i in sList_select_2.indices) {

    println(sList_select_2.get(i))

}

日志:

Student(studentID=1, studentName=s1, studentType=大學)//這條資料變了

Student(studentID=2, studentName=s2, studentType=國小)

Student(studentID=3, studentName=s3, studentType=國小)

Student(studentID=4, studentName=s4, studentType=大學)

Student(studentID=5, studentName=s5, studentType=大學)

Student(studentID=6, studentName=s6, studentType=大學)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

接下來,對資料進行删除試試

sDao.deleteSome(Student(100, "s100", "高中"), s_6)

var sList_select_3: MutableList<Student> = sDao.getAllStudents()

for (i in sList_select_3.indices) {

    println(sList_select_3.get(i))

}

日志:

Student(studentID = 1, studentName = s1, studentType = 大學)

Student(studentID = 2, studentName = s2, studentType = 國小)

Student(studentID = 3, studentName = s3, studentType = 國小)

Student(studentID = 4, studentName = s4, studentType = 大學)

Student(studentID = 5, studentName = s5, studentType = 大學)

1

2

3

4

5

6

7

8

9

10

11

12

13

從删除可以看出,删除不存在的Student資料,不會報錯,隻是沒有效果,删除存在的資料,就是正常删除

接下來,對Teacher表進行一些操作

val tDao: TeacherDao = AppDataBase.instance.getTeacherDao()

var t_1 = Teacher(1, "t1", 10)

var t_2 = Teacher(2, "t2", 5)

var t_3 = Teacher(3, "t3", 3)

var t_4 = Teacher(4, "t4", 14)

var t_5 = Teacher(5, "t5", 22)

var tList: MutableList<Teacher> = mutableListOf<Teacher>()

tList.add(t_1)

tList.add(t_2)

tList.add(t_3)

tList.add(t_4)

tList.add(t_5)

tDao.insertAll(tList)

var tList_select_1: MutableList<Teacher> = tDao.getAllTeachers()

for (i in tList_select_1.indices) {

    println(tList_select_1.get(i))

}

日志:

Teacher(teacherID=1, teacherName=t1, teachYear=10)

Teacher(teacherID=2, teacherName=t2, teachYear=5)

Teacher(teacherID=3, teacherName=t3, teachYear=3)

Teacher(teacherID=4, teacherName=t4, teachYear=14)

Teacher(teacherID=5, teacherName=t5, teachYear=22)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

對教師資料進行排序(按照教學年限)

var tList_select_2: MutableList<Teacher> = tDao.getAllByDateDesc()

for (i in tList_select_2.indices) {

    println(tList_select_2.get(i))

}

日志:

Teacher(teacherID=5, teacherName=t5, teachYear=22)

Teacher(teacherID=4, teacherName=t4, teachYear=14)

Teacher(teacherID=1, teacherName=t1, teachYear=10)

Teacher(teacherID=2, teacherName=t2, teachYear=5)

Teacher(teacherID=3, teacherName=t3, teachYear=3)

1

2

3

4

5

6

7

8

9

10

11

12

現在,要對 ID=1 的老師做修改,把他的教學年限,改成11,還是用之前Student的那種寫法:

tDao.insert(Teacher(1,"t1",11))

報錯:

Caused by: android.database.sqlite.SQLiteConstraintException:

    UNIQUE constraint failed: Teacher.teacherID 

    (Sqlite code 1555 SQLITE_CONSTRAINT_PRIMARYKEY),

    (OS error - 2:No such file or directory)

1

2

3

4

5

6

7

到這來,應該知道,insert上面那句注解

@Insert(onConflict = OnConflictStrategy.REPLACE)

1

的含義和作用了吧!

如果沒有這個注解,插入已有資料,會報錯!如果有這個注解,插入以後資料,僅僅是替換。

因為Teacher沒有加這個注解,用update試試

tDao.update(Teacher(1, "t1", 11))

var tList_select_3: MutableList<Teacher> = tDao.getAllTeachers()

for (i in tList_select_3.indices) {

    println(tList_select_3.get(i))

}

日志:

Teacher(teacherID=1, teacherName=t1, teachYear=11)

Teacher(teacherID=2, teacherName=t2, teachYear=5)

Teacher(teacherID=3, teacherName=t3, teachYear=3)

Teacher(teacherID=4, teacherName=t4, teachYear=14)

Teacher(teacherID=5, teacherName=t5, teachYear=22)

————————————————

版權聲明:本文為CSDN部落客「夜盡天明89」的原創文章,遵循CC 4.0 BY-SA版權協定,轉載請附上原文出處連結及本聲明。

原文連結:https://blog.csdn.net/u014620028/article/details/90719716