- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何使用 Kotlin、Coroutines、ViewModel、LiveData 处理查询方法的返回类型 room
构建失败,我收到很多指向我的 Dao 类的错误,错误是
错误1:
Not sure how to handle query method's return type (java.lang.Object).DELETE query methods must either return void or int (the number ofdeleted rows).
错误2:
error: Query method parameters should either be a type that can beconverted into a database column or a List / Array that contains suchtype. You can consider adding a Type Adapter for this.kotlin.coroutines.Continuation<? super kotlin.Unit> continuation);
错误3:
error: Unused parameter: continuationpublic abstract java.lang.Object clear(@org.jetbrains.annotations.NotNull()
错误4:
error: Type of the parameter must be a class annotated with @Entity ora collection/array of it.kotlin.coroutines.Continuation<? super kotlin.Unit> continuation);
错误5:
error: Not sure how to handle insert method's return type.public abstract java.lang.Object insert(@org.jetbrains.annotations.NotNull()
**这是我的完整代码: https://drive.google.com/drive/folders/1qWoud5XogzkTmpa-GWxLJStfdUPSoV7r?usp=sharing
android kotlin - 协程 Room ViewModel LiveDataMainActivity.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()
}
}
}
最佳答案
您的问题出在插入和删除方法中的关键字 suspend 中。删除后,您的错误就消失了。
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(student:Student)
@Query("DELETE FROM studentTbl")
fun clear()
顺便说一句,您的构建仍然无法成功。要修复其他错误,您应该在应用程序 build.gradle 文件中的 block 插件上添加“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
关于android - 如何使用 Kotlin、Coroutines、ViewModel、LiveData 处理查询方法的返回类型 room,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69998391/
import kotlinx.coroutines.* fun log(msg: String) = println("[${Thread.currentThread().name}] $msg")
我有一个长计算的外部库。这个库就是一切,但在过早停止方面是合作的。它被包装并在一个协程中启动。 我想从调用方终止进程。协程取消是合作的,所以它不起作用。有没有办法突然终止协程? 最佳答案 非挂起的协程
我是 Kotlin/Coroutines 的新手,我注意到两种不同的使用方式 CoroutineScope . 选项 1 如下,在任何函数中: CoroutineScope(Dispatchers.D
我对协同例程比较陌生,我正在尝试获取 Launch 协同例程将完成的行为: launch(UI) { val v1 = someDeferredType val v2 = v1.a
文档说: @asyncio.coroutine Decorator to mark generator-based coroutines. This enables the generator use
我在 kotest 中使用了 Funspec 测试风格,我得到了一个由框架自动注入(inject)的 coroutineScope,如下所示。 class MyTestSpec: FunSpec()
我想尝试从一个courtine 中暂停主线程。几个问题,但首先让我向您展示我正在使用的代码块作为测试: class MainActivity : Activity(), CoroutineScope
我不确定我是否理解 purescript-coroutines 中有一个 connect 和一个 pullFrom 函数的原因。 ,以及何时使用它们。看看这些类型,它们似乎已经习惯了改变“通信方向”(
我在不同的类(class_A、class_B)中有 2 个协程(co_A、co_B)由调度程序定期调用。在执行期间的某个时候,co_B 需要一个 co_A 在其运行期间正在计算的结果。 我想做的是这样
在 document , 如果方法也用@gen.coroutine 修饰,则不需要@web.asynchronous。像这样 @web.asynchronous @gen.coroutine def
目前在 pzmq 中有多种方法来实现文档中提到的异步 IO 循环。 http://pyzmq.readthedocs.io/en/latest/api/index.html 从纯性能的角度来看,文档中
看来我误解了当有许多套接字被打开时 Windows 如何在 TIME_WAIT 中处理套接字。如果在 TIME_WAIT 中挂出太多,它只会出错。 Linux 清理旧连接并成功(至少在我的盒子上,不确
我正在尝试对我使用 Kotlin 协程制作的 Presenter 进行单元测试,这也是我第一次使用 Mockito 每当我尝试运行单元测试时,它在协程中第一次尝试对我的 View 执行任何操作时都会收
我注意到 Boost.Coroutine2 for C++ 中删除了对对称协程的支持,所以我想了解 - 两者之间有什么区别? 最佳答案 Ana Lúcia de Moura 和 Roberto Ier
在Linux System Programming, 2nd Edition书中,协程与纤维之间的差异解释如下: 协程和纤维提供了比线程更轻的执行单元(前者是编程语言结构时的名称,后者是系统结构时的名
此示例已在另一个问题中用于说明如何使用协程来编写视频游戏中的过场动画: bob.walkto(jane) bob.lookat(jane) bob.say("How are you?") wait(2
我正在寻找实现 FSM 的方法,这导致我第一次遇到协程。 我看到了几个示例(here、here 和 here),它们暗示状态机可以由单个协程实现。然而,我注意到所有这些机器的共同点是,不包括循环,它们
我试图从ViewModel异步获取所有可启动的已安装应用程序。 这是我的ViewModel类的样子: class AppInstalledViewModel(application: Applicat
如何在kotlin中像多线程一样进行多次启动 我想让 first second 永远同时工作!! 喜欢这段代码... runBlocking { // first launch{
最近我正在按照这个 CodeLabs tutorial 学习 kotlin-coroutine 。经过一些实践后,我想知道我是否可以在 java 中编写相同的代码。所以首先我在 MyKotlinFra
我是一名优秀的程序员,十分优秀!