我有一个商店应用程序,如果我们从一开始就需要用户注册(如果这个帐户已经在数据库中,他需要登录)。我有房间数据库与dao,数据库类。
在唱歌片段我有2个edittext字段与提示电子邮件和密码。
我已经很有趣了,那就是检查字段是否为空。
我已经在我的片段中初始化了数据库类。
当用户点击按钮注册时(在注册片段中),他的数据将保存在房间db中,用户将转到下一个片段。
我猜我的DAO类有错误
代码如下:
UserModel
@Entity(tableName = "user_table")
data class UserModel(
@PrimaryKey(autoGenerate = true)
val id: Int?,
@ColumnInfo
val email: String? = "",
@ColumnInfo
val password:String? = ""
)
FragmentForActivityMain
class FragmentForActivityMain : Fragment(R.layout.fragment_for_activity_main) {
private lateinit var binding :FragmentForActivityMainBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentForActivityMainBinding.inflate(inflater,container,false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
init()
}
private fun init(){
val viewModel = ViewModelProvider(this).get(fragmentmainviewmodel::class.java)
viewModel.initdb()
binding.buttontogologin.setOnClickListener {
findNavController().navigate(R.id.action_fragmentForActivityMain_to_loginFragment)
}
binding.signupbutton.setOnClickListener {
findNavController().navigate(R.id.action_fragmentForActivityMain_to_signUpFragment)
}
}
}
Const文件
import UserRepository.UserRepository
lateinit var repository:UserRepository
类fragmentmainviewmodelimport Const.repository
import Room.Database.UserDB
import UserRepository.RepositoryAndDaoRealization
import android.app.Application
import androidx.lifecycle.AndroidViewModel
class fragmentmainviewmodel(application: Application):AndroidViewModel(application) {
val context = application
fun initdb(){
val daouser = UserDB.getadminDB(context).getDAO()
repository = RepositoryAndDaoRealization(daouser)
}
}
DAO类
@Dao
interface UserDAO {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertnewUser(user:UserModel)
@Query("select * from USER_TABLE where email like email and password like password")
suspend fun validationforuser(userModel: UserModel)
@Query("select * from user_table")
fun getAllUser():LiveData<List<UserModel>>
数据库
@Database (entities = [UserModel::class], version = 5, exportSchema = true)
abstract class UserDB:RoomDatabase(){
abstract fun getDAO(): UserDAO
companion object{
private var database : UserDB?= null
@Synchronized
fun getadminDB(context: Context):UserDB{
return if(database == null){
database= Room.databaseBuilder(context,UserDB::class.java,"UserDatabase").build()
database as UserDB
}else{
database as UserDB
}
}
}
}
SignUpFragment
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.example.myapplication.Model.UserModel
import com.example.myapplication.R
import com.example.myapplication.databinding.FragmentSignUpBinding
class SignUpFragment : Fragment() {
lateinit var binding:FragmentSignUpBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentSignUpBinding.inflate(inflater)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
init()
}
private fun init(){
val viewModel = ViewModelProvider(this).get(SingUpViewModel::class.java)
binding.signupbuttoninsignupfragment.setOnClickListener {
val espace = binding.EmailSpaceSignUp.text.toString()
val pspace = binding.PasswordSpaceSignUp.text.toString()
viewModel.insert(UserModel(email = espace, password = pspace, id = id )){}
findNavController().navigate(R.id.action_signUpFragment_to_lastfragment)
if(binding.EmailSpaceSignUp == null){
Toast.makeText(context,"Email space is empty , you need to write some data there",Toast.LENGTH_SHORT).show()
}
if(binding.PasswordSpaceSignUp == null){
Toast.makeText(context,"Password space is empty , you need to write some data there",Toast.LENGTH_SHORT).show()
}
if(binding.PasswordSpaceSignUp.length()<8){
Toast.makeText(context,"Password is too short",Toast.LENGTH_SHORT).show()
}
if(binding.EmailSpaceSignUp.length()<18){
Toast.makeText(context,"Email is too short",Toast.LENGTH_SHORT).show()
}
}
}
}
SingUpViewModel
class SingUpViewModel: ViewModel() {
fun insert(userModel: UserModel,onSuccess:()->Unit) =
viewModelScope.launch(Dispatchers.IO) {
repository.insertUser(userModel){
onSuccess()
}
}
}
Class RepositoryAndDaoRealization
class RepositoryAndDaoRealization(private var dao:UserDAO):UserRepository {
override val allusers: LiveData<List<UserModel>>
get() = dao.getAllUser()
override suspend fun insertUser(userModel: UserModel, onSuccess: () -> Unit) {
dao.insertnewUser(userModel)
onSuccess()
}
override suspend fun validateuser(userModel: UserModel, onSuccess: () -> Unit) {
dao.validationforuser(userModel)
onSuccess()
}
}
UserRepository
interface UserRepository {
val allusers:LiveData<List<UserModel>>
suspend fun insertUser(userModel: UserModel,onSuccess:()->Unit)
suspend fun validateuser(userModel: UserModel,onSuccess: () -> Unit)
}
您的问题是:-
@Query("select * from USER_TABLE where email like email and password like password")
suspend fun validationforuser(userModel: UserModel)
Room无法确定如何处理查询的输出。
所以你需要像这样:-
suspend fun validationforuser(userModel: UserModel): List<UserModel>
所以Room知道你想对查询的输出做什么。
然而,则Room将报错传递给函数的参数:-
error: Query method parameters should either be a type that can be converted into a database column or a List / Array that contains such type. You can consider adding a Type Adapter for this.
你可以用:-
@Query("select * from USER_TABLE where email like email and password like password")
suspend fun validationforuser(email: String, password: String): List<UserModel>
然后Room会抱怨,因为它不知道如何处理电子邮件和密码参数,因为它们没有在查询中编码。按:-
error: Unused parameters: email,password
那么你可以使用:-
@Query("select * from USER_TABLE where email like :email and password like :password")
suspend fun validationforuser(email: String, password: String): List<UserModel>
请注意,您应该传递来自UserModel的电子邮件和密码,而不是传递UserModel。
。
dao.validationforuser(userModel.email,userModel.password)