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

Har*_*r S 2 android kotlin android-room

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

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

错误1:

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

错误2:

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

错误3:

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

错误4:

错误:参数的类型必须是用@Entity注释的类或其集合/数组。kotlin.coroutines.Continuation<? 超级 kotlin.Unit> 延续);

错误5:

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

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

android kotlin - 协程 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()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

活动主文件

<?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>
Run Code Online (Sandbox Code Playgroud)

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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()
}
Run Code Online (Sandbox Code Playgroud)

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
)
Run Code Online (Sandbox Code Playgroud)

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()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

A.R*_*ost 5

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

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

    @Query("DELETE FROM studentTbl")
   fun clear()
Run Code Online (Sandbox Code Playgroud)

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

plugins {
    id 'com.android.application'
    id 'kotlin-android-extensions'
    id 'kotlin-android'
    id 'kotlin-kapt'
}
Run Code Online (Sandbox Code Playgroud)

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

  • 我只是删除了插入和删除方法中的关键字 suspend ,并且还更改为视图绑定,现在正在工作,谢谢 (2认同)