简体   繁体   中英

Room Pre populate data

I have edittext for email and password(loginfragment), my aim is to check if the password and email from database is correct.

If u clicking a button the database should readdata and find account by password and email.

I have dbfile in assets which I screenshoted.

在此处输入图像描述

When i click on button is crashed, if i have some symbols in spaces.

在此处输入图像描述

package Room.Database
import Room.DAO.DAO
import Room.Repository.Admindata
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase

@Database (entities = [Admindata::class], version = 2, exportSchema = true)
abstract class AdminDatabase:RoomDatabase(){
abstract fun getDAO(): DAO
companion object{
    fun getadminDB(context: Context):AdminDatabase{
        return Room.databaseBuilder(context.applicationContext,AdminDatabase::class.java,"admindatabase").createFromAsset("SQLDB/dbforpetproject.db").build()
    }
}
}

this is how my database looks like


DAO

package Room.DAO
import Room.Repository.Admindata
import androidx.room.Dao
import androidx.room.Query



@Dao
interface DAO {
  @Query("select * from admin_table where email = :email")
  suspend fun findbyEmail(email:String) : Admindata


  @Query("select * from admin_table  where password = :password")
  suspend fun findbypassword(password:String) : Admindata


}

Admindataclass(Entity)

package Room.Repository
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey


@Entity(tableName= "admin_table")
data class Admindata(
    @PrimaryKey
    val id:Int = 1,
    @ColumnInfo(name = "email")
    val email:String = "admin@gmail.com",
    @ColumnInfo(name = "password")
    val password:String = "12345678"
)

This is how my fragment looks like

package com.example.myapplication
import Room.Database.AdminDatabase
import Room.Repository.Admindata
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.example.myapplication.databinding.FragmentLoginBinding
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch


class LoginFragment : Fragment() {
private lateinit var binding : FragmentLoginBinding
private lateinit var db:AdminDatabase
private lateinit var admin:Admindata




val scope = CoroutineScope(CoroutineName("Scope"))
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    db = AdminDatabase.getadminDB(requireContext())

}
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
       binding = FragmentLoginBinding.inflate(inflater)
        return binding.root


    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.continuebutton.setOnClickListener {
            if(binding.EmailSpace.length() == 0){
                Toast.makeText(context,"The space is empty write email",Toast.LENGTH_SHORT).show()
            }

            if(binding.PasswordSpace.length() == 0){
                Toast.makeText(context,"The space is empty write password",Toast.LENGTH_SHORT).show()
            }
           if(binding.PasswordSpace.length() <8){
               Toast.makeText(context,"Password is too small",Toast.LENGTH_SHORT).show()
           }
      if(binding.EmailSpace.length() >0){ // my wrong realization
          scope.launch {
              findbyEmail(email = admin.email)
          } 
findNavController().navigate(R.id.action_loginFragment_to_lastfragment)
      }
else{
    Toast.makeText(context,"Email is wrong",Toast.LENGTH_SHORT).show()
} // my wrong realization
            if(binding.PasswordSpace.length() >0){ // my wrong realization
                scope.launch {
                    findbyPassword(password = admin.password)
                }
                findNavController().navigate(R.id.action_loginFragment_to_lastfragment)
            }
            else{
                Toast.makeText(context,"Password is wrong",Toast.LENGTH_SHORT).show() // my wrong realization
            }
        }
    }
    @Override
    private suspend fun findbyEmail(email:String){
        val tuple = db.getDAO().findbyEmail(email)
        if(tuple.email != email){
            Toast.makeText(context,"Email is wrong",Toast.LENGTH_SHORT).show()
        }
    }
    @Override
    private suspend fun findbyPassword(password:String){
        val tuple = db.getDAO().findbypassword(password)
        if(tuple.password != password){
            Toast.makeText(context,"Password is wrong",Toast.LENGTH_SHORT).show()
        }
    }
}

Considering that the email and password are available then all you need to know is whether or not the email and password combined are correct (exist).

Rather than running two queries you can combined both tests in a single query, furthermore you can return an indicator (eg and Int). Perhaps consider the following:-

@Query("SELECT count(*) FROM admin_table WHERE email=:email AND password=:password")
suspend fun findCredentialsExist(email: String,password: String):Int

You could then use something along the lines of

if (db.getDAO().findCredentialsExist(the_email, the_password) > 0) ....
  • count() is an aggregate function that will return the number of rows extracted per GROUP. As there is no GROUP BY clause in the query all of the extracted rows are the GROUP. Hence if no row matches the passed email and password, the count will be 0. If one or more rows match then the count will be 1 or greater.

  • if returning a single value from a query then Room allows that value to be a retrieved directly into one of the core objects that Room understands (Int, Byte, Long, String, Double....), rather than into a user defined object where the output column names have to be those expected by the user defined object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM