Search code examples
kotlinandroid-sqlitesqliteopenhelper

facing issue in login and registration in android studio using SQLite + kotlin


I try to login. after registration had done. When I try to login it shows invalid password and username. But, I mention the correct password and username

github file

package com.example.app

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity


class RegisterActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_register)

        val regUserName = findViewById<EditText>(R.id.regUuserNameSection)
        val regEmail = findViewById<EditText>(R.id.regemailSection)
        val regPassword = findViewById<EditText>(R.id.regpasswordSection)
        val confirm = findViewById<EditText>(R.id.regConformPasswordSection)
        val regButton = findViewById<Button>(R.id.regButton)
        val loginText = findViewById<TextView>(R.id.registration)

        loginText.setOnClickListener(
            View.OnClickListener {
                val intent = Intent(this, LoginActivity::class.java)
                startActivity(intent)
            }

        )

        regButton.setOnClickListener(
            View.OnClickListener {
                val username = regUserName.text.toString()
                val email = regEmail.text.toString()
                val password = regPassword.text.toString()
                val conform = confirm.text.toString()
                val db = Data(applicationContext, "healthcare", null, 1)


                if(username.isEmpty() || email.isEmpty() || password.isEmpty() || conform.isEmpty()) {
                    Toast.makeText(this, "Please fill the details", Toast.LENGTH_SHORT).show()
                }
                else {
                    // comparing two passwords are same using compareTo
                    if(password.compareTo(conform) == 0) {
                        if(isValid(password)){
                            db.register(username, email, password)
                            Toast.makeText(this, "Record Inserted", Toast.LENGTH_SHORT).show()
                            val intent = Intent(this, LoginActivity::class.java)
                            startActivity(intent)
                        }
                        else {
                            Toast.makeText(this, "Password must contain at least 8 characters, One UpperCase letter, digit and special symbol", Toast.LENGTH_SHORT).show()
                        }
                    }
                    else {
                        Toast.makeText(this, "password and confirm password didn't match", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        )

    }
    private fun isValid(password : String) : Boolean {
        val passwordRegex = Regex("^(?=.*[A-Z])(?=.*[!@#\$&*])(?=.*[0-9])(?=.{9,17}).*$")
        return password.matches(passwordRegex)
    }
}


package com.example.app

import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity


class LoginActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        val edUserName : EditText = findViewById(R.id.regUuserNameSection)
        val edPassword : EditText = findViewById(R.id.regConformPasswordSection)
        val loginButton : Button = findViewById(R.id.regButton)
        val newRegister = findViewById<TextView>(R.id.registration)
        val db = Data(applicationContext, "healthcare", null, 1)
        loginButton.setOnClickListener {
            val username = edUserName.text.toString()
            val password = edPassword.text.toString()
            if ((username.isEmpty()) || (password.isEmpty())) {
                Toast.makeText(this, "fill the details!", Toast.LENGTH_SHORT).show()
            }
            else {
                if(db.login(username, password) == 1) {
                    Toast.makeText(this, "login success!", Toast.LENGTH_SHORT).show()
                    val sharedPref = getSharedPreferences("share_prefs", Context.MODE_PRIVATE)
                    val editor : SharedPreferences.Editor = sharedPref.edit()
                    editor.putString("username", username)
                    editor.apply()
                    startActivity(Intent(this, HomeActivity::class.java))
                }
                else {
                    Toast.makeText(this, "Invalid Username and Password", Toast.LENGTH_SHORT).show()
                }

            }

        }

        newRegister.setOnClickListener {
            val intent = Intent(this, RegisterActivity::class.java)
            startActivity(intent)
        }

    }
}
package com.example.app

import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper

class Data(
    context: Context?,
    name: String?,
    factory: SQLiteDatabase.CursorFactory?,
    version: Int
) : SQLiteOpenHelper(context, name, factory, version) {
    override fun onCreate(p0: SQLiteDatabase) {
        val query = "CREATE TABLE $TABLE_NAME ($USERNAME_COL TEXT, $PASSWORD_COL TEXT, $EMAIL_COL TEXT)"
        p0.execSQL(query)
    }

    override fun onUpgrade(p0: SQLiteDatabase?, p1: Int, p2: Int) {
        TODO("Not yet implemented")
    }

    fun register(username: String, password: String, email: String) {
        val cv = ContentValues()
        cv.put(USERNAME_COL, username)
        cv.put(PASSWORD_COL, password)
        cv.put(EMAIL_COL, email)

        val db = this.writableDatabase
        db.insert(TABLE_NAME, null, cv)
        db.close()
    }

    fun login(username: String, password: String) :Int {
        var result = 0
        val str : Array<String> = arrayOf(username, password)
        val db = this.readableDatabase
        val cursor = db.rawQuery("SELECT * FROM $TABLE_NAME WHERE $USERNAME_COL =? AND $PASSWORD_COL =?", str)
        if(cursor.moveToFirst()) {
            cursor.close()
            result = 1
        }
        cursor.close()
        return result
    }
    companion object {
        const val TABLE_NAME = "users"
        const val USERNAME_COL = "username"
        const val PASSWORD_COL = "password"
        const val EMAIL_COL = "email"

    }
}

kindly help me, to sort out this problem Or any given suggestion code to work with sqlite or kotlin code for login and registration


Solution

  • Consider the following:-

    db.register(username, email, password)
    

    And the actual register function:-

    fun register(username: String, password: String, email: String)
    

    When registering you are storing the email as the password and the password as the email. So

    So change db.register(username, email, password) to db.register(username, password, email)