android 实体和POJO必须具有可用的公共构造函数,可以具有空构造函数或参数与字段匹配的构造函数

tpgth1q7  于 2022-12-31  发布在  Android
关注(0)|答案(1)|浏览(140)

我有一个商店应用程序,如果我们从一开始用户就需要注册(如果这个帐户已经在数据库中,他需要登录)。我有房间数据库与道,数据库类。
在唱起来的片段,我有2个提示电子邮件和密码编辑文本字段。
我已经有乐趣,这是检查领域的空。
我已经在我的片段中完成了数据库类的初始化。
当用户点击注册按钮(在注册片段中)时,他的数据将保存在房间数据库中,用户将转到下一个片段。
我猜我的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)
    }
}
}

常量文件

import UserRepository.UserRepository

lateinit var repository:UserRepository

类片段主视图模型

import 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
        }
    }
}
}

注册片段

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()
        }
    }
    }
}

单视图模型

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)
}
wljmcqd8

wljmcqd81#

您的问题是:-

@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>

但是那么房间会抱怨,因为它不知道如何处理电子邮件和密码参数,因为它们没有在查询中编码。

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)

相关问题