【发布时间】:2021-12-27 19:40:42
【问题描述】:
我正在创建一个用户可以登录或注册帐户的应用。我已经创建了注册屏幕,它成功地将数据保存到数据库中。但是,我现在正在尝试集成一些验证。例如,用户名必须是唯一的,并且电子邮件不能已经存在。
我当然尝试编写一个自定义查询来打印出用户名列中的所有行,如下所示:
SELECT userName from cx_table
当然,我还尝试编写一个单独的自定义查询来打印出电子邮件列中的所有行,如下所示:
SELECT email from cx_table
然后我的方法是获取用户输入并将其与该列返回的值进行比较,如果存在,则打印一条错误消息。但是当我运行该应用程序时,我收到以下错误消息
The columns returned by the query does not have the fields [id,firstName,lastName,password,address,city,postalcode,email,phone] in com.cxpro.data.Customer even though they are annotated as non-null or primitive. Columns returned by the query: [userName]
这是我的房间数据库的所有代码:
Customer.kt
@Entity(tableName = "cx_table")
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
)
CustomerDao.kt
@Dao
interface CustomerDao {
@Insert(onConflict = OnConflictStrategy.IGNORE)
fun addCustomers(customer: Customer)
@Query("SELECT * FROM cx_table ORDER BY id ASC")
fun readAllData(): LiveData<List<Customer>>
@Query("SELECT userName FROM cx_table")
fun readUserName(): LiveData<List<Customer>>
}
CustomerDatabase.kt
@Database(entities = [Customer::class],version = 1, exportSchema = false)
abstract class CustomerDatabase: RoomDatabase() {
abstract fun customerDao(): CustomerDao
companion object{
@Volatile
private var INSTANCE: CustomerDatabase? = null
fun getDatabase(context: Context): CustomerDatabase{
val tempInstance = INSTANCE
if(tempInstance != null){
return tempInstance
}
synchronized(this){
val instance = Room.databaseBuilder(
context.applicationContext,
CustomerDatabase::class.java,
"customer_database"
).build()
INSTANCE = instance
return instance
}
}
}
}
CustomerRepository.kt
class CustomerRepository(private val customerDao: CustomerDao) {
val readAllData: LiveData<List<Customer>> = customerDao.readAllData()
val readUserName: LiveData<List<Customer>> = customerDao.readUserName()
suspend fun addCustomer(customer: Customer){
customerDao.addCustomers(customer)
}
}
CustomerViewModel.kt
class CustomerViewModel(application: Application): AndroidViewModel(application) {
val readAllData: LiveData<List<Customer>>
val readUserName: LiveData<List<Customer>>
private val repository: CustomerRepository
init {
val customerDao = CustomerDatabase.getDatabase(application).customerDao()
repository = CustomerRepository(customerDao)
readAllData = repository.readAllData
readUserName = repository.readUserName
}
fun addCustomer(customer: Customer){
viewModelScope.launch(Dispatchers.IO){
repository.addCustomer(customer)
}
}
}
如何验证表中不存在用户名和/或电子邮件?
【问题讨论】:
-
this 回答你的问题了吗?
-
不是真的,你觉得你能澄清一下吗?
标签: kotlin android-room