Search code examples
androidmvvmandroid-roomkotlin-coroutinesandroid-viewmodel

How to verify if a username and password exists in my room database?


I am practicing with the room database and it has been difficult for me to verify if a username and password exist in my database,(I am sure I have many errors for this reason I ask for your help) my code:

//User

  @Entity(tableName = "user_table")
    data class User(
            @PrimaryKey(autoGenerate = true)
            val id : Int ,
            val userName: String,
            val nameStudent: String,
            val grade: String,
            val password: String
    )

//UserDao v @Dao interface UserDao {

        @Insert(onConflict = OnConflictStrategy.IGNORE)
        suspend fun addUser(user: User)
    
 @Query("SELECT * FROM user_table WHERE userName LIKE :name AND password LIKE :password")
        fun readAllData(name: String, password: String): User
        
    }

//UserRepository

   class UserRepository(private val userDao: UserDao,val name:String, val passWord:String) {
    
    val readAllData: List<User> = userDao.readAllData(name, passWord)
    
    suspend fun adduser(user: User) {
        userDao.addUser(user)
    }

}

//UserViewModel

 class UserViewModel(application: Application,  name:String, passWord:String) : AndroidViewModel(application) {
    
    val readAllData: List<User>
    private val repository: UserRepository

    init {
        val userDao = UserDatabase.getDatabase(
            application
        ).userDao()
        repository = UserRepository(userDao,name,passWord)
        readAllData = repository.readAllData
    }

    fun addUser(user: User) {
        viewModelScope.launch(Dispatchers.IO) {
            repository.adduser(user)
        }
    }

}

//ViewModelFactory

class MyViewModelFactory(private var application: Application, private var name: String, private var passWord: String) :
    ViewModelProvider.Factory {
    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(UserViewModel::class.java)) {
            return UserViewModel(application, name, passWord) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}

//MainFragment

 override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        super.onViewCreated(view, savedInstanceState)
        binding = FragmentMainBinding.bind(view)

        val factory = MyViewModelFactory(Application(),"","")
        mUserViewModel = ViewModelProvider(this,factory).get(UserViewModel::class.java)

        val name = binding.textInputUser.editText?.text.toString()
        val passWord = binding.textInputPassword.editText?.text.toString()

        val x = context?.let { UserDatabase.getDatabase(it).userDao() }

        val y = x?.readAllData(name,passWord)

        binding.buttonIngresar.setOnClickListener {

            if (y != null) {
                findNavController().navigate(R.id.action_mainFragment_to_candidatesFragment)

            } else {
                Toast.makeText(context, "User does not exist", Toast.LENGTH_SHORT).show()
            }

        }

    }

Solution

  • @Dao
    interface UserDao {
    
        @Query("SELECT * FROM user_table WHERE userName LIKE :name AND password LIKE :password")
        fun readAllData(name: String, password: String): LiveData<User>
    
    }
    

    //UserRepository

    class UserRepository(private val userDao: UserDao) {
    
    
        var loginDatabase: UserDatabase? = null
        var readAllData: LiveData<User>? = null
    
        fun initializeDB(context: Context) : UserDatabase {
            return UserDatabase.getDatabase(context)
        }
    
        fun getLoginDetails(context: Context, username: String,password:String) : LiveData<User>? {
            loginDatabase = initializeDB(context)
            readAllData = loginDatabase!!.userDao().readAllData(username,password)
            return readAllData
        }
    
    }
    

    //UserViewModel

    class UserViewModel (application: Application): AndroidViewModel(application){
    
        var readAllData: LiveData<User>? = null
        val repository: UserRepository
        
        init {
            val userDao = UserDatabase.getDatabase(
                    application
            ).userDao()
            repository = UserRepository(userDao)
            readAllData = repository.readAllData
        }
        
       
        }
    
        fun getLoginDetails(context: Context, username: String,password:String) : LiveData<User>? {
    
            readAllData = repository.getLoginDetails(context,username,password)
            return readAllData
        }
    
    }
    

    //MainFragment

      class MainFragment : Fragment() {
    
        private lateinit var binding: FragmentMainBinding
        private lateinit var mUserViewModel: UserViewModel
    
        override fun onCreateView(
                inflater: LayoutInflater, container: ViewGroup?,
                savedInstanceState: Bundle?
        ): View? {
            // Inflate the layout for this fragment
            val view = inflater.inflate(R.layout.fragment_main, container, false)
    
            binding = FragmentMainBinding.bind(view)
    
            mUserViewModel = ViewModelProvider(this).get(UserViewModel::class.java)
    
            binding.buttonIngresar.setOnClickListener {
    
                val name = binding.textInputUser.editText?.text.toString()
                val passWord = binding.textInputPassword.editText?.text.toString()
                context?.let { it1 ->
                    mUserViewModel.getLoginDetails(it1, name, passWord)?.observe(viewLifecycleOwner, Observer {
    
                        if (it == null) {
                            Toast.makeText(context, "Not found", Toast.LENGTH_SHORT).show()
                        } else {
                            Toast.makeText(context, "Found", Toast.LENGTH_SHORT).show()
                        }
    
                    })
                }
            }
    
            return view
    
        }
        
    
    }