【问题标题】:What is this Room DB Error, and how to resolve it?什么是 Room DB 错误,如何解决?
【发布时间】:2021-11-20 23:11:01
【问题描述】:

我不太确定如何组织这个问题的标题,但希望以下信息能增加价值和说明。

我已经创建了一个注册屏幕,并且正在使用 ROOM 数据库来存储用户。我成功地将它们添加到数据库中。我正在尝试对条目进行一些验证,因为我不希望用户拥有相同的用户名或电子邮件。这是我的代码:


Entity Class:

@Entity(tableName = "cx_table",
    indices = [
        Index(value = ["userName"],unique = true),
        Index(value = ["email"],unique = true)]
)
data class Customer(
    @PrimaryKey(autoGenerate = true)
    val id: Int,
    val firstName: String,
    val lastName: String,
    val userName: String,
    val password: String,
    val address: String,
    val city: String,
    val postalcode: String,
    val email: String,
    val phone: String
)

Data Access Object:

@Dao
interface CustomerDao {

    @Insert(onConflict = OnConflictStrategy.FAIL)
    suspend fun addCustomers(customer: Customer): Long
}

Repository Class:

class CustomerRepository(private val customerDao: CustomerDao) {
    val readAllData: LiveData<List<Customer>> = customerDao.readAllData()


    suspend fun addCustomer(customer: Customer): Boolean {
        try {
            customerDao.addCustomers(customer)
            return true
        }catch (ex: Exception){
            return false
        }
    }

}

ViewModel Class

class CustomerViewModel(application: Application): AndroidViewModel(application) {

    val readAllData: LiveData<List<Customer>>
    private val repository: CustomerRepository

    init {
        val customerDao = CustomerDatabase.getDatabase(application).customerDao()
        repository = CustomerRepository(customerDao)
        readAllData = repository.readAllData

    }

    suspend fun addCustomer(customer: Customer){
        viewModelScope.launch(Dispatchers.IO){
            repository.addCustomer(customer)
        }
    }

}

当我运行/构建这个应用程序时,我收到以下错误:

错误:type of the parameter must be a class annotated with @Entity or a collection/array of it

错误:Not sure how to handle insert methods return type


任何帮助或指导将不胜感激。

【问题讨论】:

    标签: kotlin android-room


    【解决方案1】:

    我认为您在 dao 中的关键字suspend 存在问题。删除它,您的问题将得到解决。

    @Dao
    interface CustomerDao {
    
        @Insert(onConflict = OnConflictStrategy.FAIL)
        fun addCustomers(customer: Customer): Long
    }
    

    【讨论】:

    • 这不起作用
    • 你能在 git、google drive 或其他东西中提供你的完整项目吗?
    【解决方案2】:

    您尚未在问题代码中添加customerDao.readAllData()。 从我最初的调试来看,您在该方法中似乎有返回类型问题,所以如果您也可以在您的问题中添加该代码或尝试 检查方法 customerDao.readAllData() 的返回类型。它必须是List&lt;Cutomer&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-30
      • 1970-01-01
      • 2021-12-24
      • 2016-11-18
      相关资源
      最近更新 更多