【问题标题】:How to handle query method's return type room using Kotlin, Coroutines, ViewModel, LiveData如何使用 Kotlin、Coroutines、ViewModel、LiveData 处理查询方法的返回类型房间
【发布时间】:2021-12-28 01:50:02
【问题描述】:

如何使用 Kotlin、Coroutines、ViewModel、LiveData 处理查询方法的返回类型房间

构建失败,我收到很多指向我的 Dao 类的错误,错误是

错误 1:

不确定如何处理查询方法的返回类型(java.lang.Object)。 DELETE 查询方法必须返回 void 或 int( 删除的行)。

错误 2:

错误:查询方法参数应该是一个可以 转换为包含此类的数据库列或列表/数组 类型。您可以考虑为此添加一个类型适配器。 kotlin.coroutines.Continuation super kotlin.Unit> 延续);

错误 3:

错误:未使用的参数:继续 公共抽象 java.lang.Object clear(@org.jetbrains.annotations.NotNull()

错误 4:

错误:参数的类型必须是带有@Entity 注释的类或 它的集合/数组。 kotlin.coroutines.Continuation super kotlin.Unit> 延续);

错误 5:

错误:不确定如何处理插入方法的返回类型。 公共抽象 java.lang.Object insert(@org.jetbrains.annotations.NotNull()

**这是我的完整代码: https://drive.google.com/drive/folders/1qWoud5XogzkTmpa-GWxLJStfdUPSoV7r?usp=sharing

android kotlin - Coroutines Room ViewModel LiveData MainActivity.kt

package com.example.coroutine

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import kotlinx.android.synthetic.main.activity_main.*
import java.util.UUID
import kotlin.random.Random


class MainActivity : AppCompatActivity() {

    private lateinit var model: StudentViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // make text view text scrollable
        textView.movementMethod = ScrollingMovementMethod()

        // initialize the student view model
        model = ViewModelProvider(this).get(StudentViewModel::class.java)


        // observe the students live data
        model.students.observe(this, Observer { students->
                textView.text = "Students(${students.size})..."

                students.forEach {
                    textView.append("\n${it.id} | ${it.fullName} : ${it.result}")
                }
            }
        )


        btnInsert.setOnClickListener {
            // generate a new student
            val student = Student(
                null,
                UUID.randomUUID().toString(),
                Random.nextInt(100)
            )

            // insert new student into room database
            model.insert(student)
        }


        btnClear.setOnClickListener {
            // delete all students from room student table
            model.clear()
        }
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FAE6FA"
    tools:context=".MainActivity">

    <com.google.android.material.button.MaterialButton
        android:id="@+id/btnInsert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:backgroundTint="#8DB600"
        android:text="Insert"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/btnClear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:backgroundTint="#E52B50"
        android:text="Clear"
        app:layout_constraintBottom_toBottomOf="@+id/btnInsert"
        app:layout_constraintStart_toEndOf="@+id/btnInsert" />

    <com.google.android.material.textview.MaterialTextView
        android:id="@+id/textView"
        style="@style/TextAppearance.MaterialComponents.Subtitle1"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:textColor="#1B1811"
        android:textStyle="bold"
        android:padding="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnInsert"
        app:layout_constraintVertical_bias="1.0"
        tools:text="TextView" />

</androidx.constraintlayout.widget.ConstraintLayout>

RoomSingleton.kt

package com.example.coroutine

import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import android.content.Context

@Database(entities = [Student::class], version = 1)
abstract class RoomSingleton : RoomDatabase() {
    abstract fun studentDao():StudentDao

    companion object {
        private var INSTANCE: RoomSingleton? = null
        fun getInstance(context: Context): RoomSingleton {
            if (INSTANCE == null) {
                INSTANCE = Room.databaseBuilder(
                    context,
                    RoomSingleton::class.java,
                    "roomdb")
                    .build()
            }
            return INSTANCE as RoomSingleton
        }
    }
}

RoomDao.kt

package com.example.coroutine

import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query

@Dao
interface StudentDao{
    @Query("SELECT * FROM studentTbl ORDER BY id DESC")
    fun getStudents():LiveData<List<Student>>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(student:Student)

    @Query("DELETE FROM studentTbl")
    suspend fun clear()
}

RoomEntity.kt

package com.example.coroutine

import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey

@Entity(tableName = "studentTbl")
data class Student(
    @PrimaryKey
    var id:Long?,

    @ColumnInfo(name = "uuid")
    var fullName: String,

    @ColumnInfo(name = "result")
    var result:Int
)

StudentViewModel.kt

package com.example.coroutine

import androidx.lifecycle.AndroidViewModel
import android.app.Application
import androidx.lifecycle.LiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


class StudentViewModel(application:Application): AndroidViewModel(application){
    private val db:RoomSingleton = RoomSingleton.getInstance(application)

    internal val students : LiveData<List<Student>> = db.studentDao().getStudents()

    fun insert(student: Student){
        viewModelScope.launch(Dispatchers.IO) {
            db.studentDao().insert(student)
        }
    }

    fun clear(){
        viewModelScope.launch(Dispatchers.IO) {
            db.studentDao().clear()
        }
    }
}

【问题讨论】:

  • 请查看您是否可以创建一个公共 Github 存储库,以便我们可以重现您的错误并进行调试。驱动器上提供的文件无法导入到 AS。
  • 您是否从显示的代码中同时收到所有这些错误?我可以看到的一个问题是您有可为空的var id:Long?,表中的主键不能为空。删除这个? 并检查它是否修复了一些错误。
  • @ArpitShukla @PrimaryKey var id: Long? 不是问题。 Room 通过在生成的 INSERT SQL 中省略 id 列/值来解释 null,因此 SQLite 会生成 id。
  • @MikeT id 未设置为autoGenerate = true。为什么会SQLite generate the id
  • 因为我在评论中解释的内容,即 Room 知道。 autogenerate = true 不是要走的路。它是低效的,因为它引入了 AUTOINCREMENT。即 AUTOINCREMENT 关键字会带来额外的 CPU、内存、磁盘空间和磁盘 I/O 开销,如果不是严格需要,应避免使用。通常不需要。 根据sqlite.org/autoinc.html

标签: android kotlin android-room


【解决方案1】:

您在插入和删除方法中的关键字暂停问题。删除后你的错误就消失了。

@Insert(onConflict = OnConflictStrategy.REPLACE)
   fun insert(student:Student)

    @Query("DELETE FROM studentTbl")
   fun clear()

顺便说一句,您的构建仍然无法成功。要修复其他错误,您应该在应用 build.gradle 文件中的块插件上添加“kotlin-android-extensions”。

plugins {
    id 'com.android.application'
    id 'kotlin-android-extensions'
    id 'kotlin-android'
    id 'kotlin-kapt'
}

但此解决方案已被弃用,您应该改用 viewBinding。看一下这个。 https://developer.android.com/topic/libraries/view-binding/migration

【讨论】:

  • 我只是删除了方法 insert 和 delete 中的关键字suspend & 也更改为视图绑定,现在可以工作了,谢谢
【解决方案2】:

复制您的代码,禁止 gradle 文件,并对主要活动进行轻微调整。编译成功并运行插入和清除按钮似乎工作正常。

因此,要么您构建的 gradle 不正确,要么您需要对项目进行清理和/或重建。

例如:-

我使用的 MainActivity 将 Views 声明为 lateinit 的,而 findViewById 的则晚了:-

class MainActivity : AppCompatActivity() {

    private lateinit var model: StudentViewModel
    lateinit var textView: TextView
    lateinit var btnClear: Button
    lateinit var btnInsert: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        textView = this.findViewById(R.id.textView)
        btnClear = this.findViewById(R.id.btnClear)
        btnInsert = this.findViewById(R.id.btnInsert)

        // make text view text scrollable
        textView.movementMethod = ScrollingMovementMethod()

        // initialize the student view model
        model = ViewModelProvider(this).get(StudentViewModel::class.java)


        // observe the students live data
        model.students.observe(this, Observer { students->
            textView.text = "Students(${students.size})..."

            students.forEach {
                textView.append("\n${it.id} | ${it.fullName} : ${it.result}")
            }
        }
        )


        btnInsert.setOnClickListener {
            // generate a new student
            val student = Student(
                    null,
                    UUID.randomUUID().toString(),
                    Random.nextInt(100)
            )

            // insert new student into room database
            model.insert(student)
        }


        btnClear.setOnClickListener {
            // delete all students from room student table
            model.clear()
        }
    }
}

使用的构建 Gradle(模块):-

plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-kapt'
}

android {
    compileSdk 31

    defaultConfig {
        applicationId "a.a.so69998391kotlinroom_to_handle_query_return_types"
        minSdk 21
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
    implementation 'androidx.room:room-ktx:2.4.0-beta01'
    implementation 'androidx.room:room-runtime:2.4.0-beta01'
    implementation 'androidx.lifecycle:lifecycle-common:2.4.0'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-savedstate:2.4.0'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:2.4.0'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    kapt 'androidx.lifecycle:lifecycle-compiler:2.4.0'
    kapt 'androidx.room:room-compiler:2.4.0-beta01'
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-12
    • 2020-05-13
    • 2022-01-02
    • 2020-02-12
    • 2019-11-20
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    相关资源
    最近更新 更多