Click here to Skip to main content
15,887,453 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
When i click the button to save user's informations, the app just close and i can't access the database to see if the infos got saved or not because of that. When i comment the "verifyUser(mail)" part, i only get the toast as an answer but the app close too. I really don't know what the bug is.

here is my code

package be.heh.projet_inventaire

import android.content.AsyncQueryHandler
import android.content.Intent
import android.os.AsyncTask
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Patterns
import android.view.View
import android.widget.Toast
import androidx.activity.viewModels
import be.heh.projet_inventaire.bd.MyDB
import be.heh.projet_inventaire.bd.User
import be.heh.projet_inventaire.bd.UserRecord
import kotlinx.android.synthetic.main.activity_main.bt_Inscription_Connexion
import kotlinx.android.synthetic.main.activity_main.bt_Inscription_main
import kotlinx.android.synthetic.main.activity_main.et_email
import kotlinx.android.synthetic.main.activity_main.et_pwd
import kotlinx.android.synthetic.main.activity_main.*
import java.lang.Exception

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        AsyncTask.execute {MyDB.getDatabase(this).userDao()}
        val viewModel: UserViewModel by viewModels()
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        et_email.addTextChangedListener(object : TextWatcher{
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun afterTextChanged(s: Editable?) {
                mailValidator(s.toString())
            }
        })

        et_pwd.addTextChangedListener(object : TextWatcher{
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun afterTextChanged(s: Editable?) {
                PwdValidator(s.toString())
            }
        })



    }

    fun xmlClickEvent(v: View) {
        when(v.id){
            bt_Inscription_main.id -> addUser()
            bt_Inscription_Connexion.id -> versConnexion()

        }
    }
    private fun validMail(email: String): Boolean {
        val emailPattern = Patterns.EMAIL_ADDRESS
        return emailPattern.matcher(email).matches()
    }
    private fun mailValidator(email: String): Boolean {
        if (validMail(email)) {
            tvEmailError.visibility = View.GONE
            return true
        } else {
            tvEmailError.text = "Adresse e-mail non valide"
            tvEmailError.visibility = View.VISIBLE
            return false
        }
    }
    private fun PwdValidator(password: String): Boolean {
        if (password.length >= 4) {
            tvPwdError.visibility = View.GONE//
            //tilPwd.error = null
            return true
        } else {
            //tilPwd.error = "Le mot de passe doit contenir au moins 4 caractères"
            tvPwdError.text = "Le mot de passe doit contenir au moins 4 caractères"
            tvPwdError.visibility = View.VISIBLE
            return false
        }
    }


    fun verifyUser(email: String) : Boolean{
        var user = UserRecord (0,"","","")
        AsyncTask.execute { user = MyDB.getDatabase(this).userDao().get(email) }
        if (user == null){return true}
        else(return false)
    }


    fun addUser(){
        try {
            val mail = et_email.text.toString()
            val pwd = et_pwd.text.toString()

            if(mailValidator(mail) && PwdValidator(pwd)){
                if(verifyUser(mail)) {
                    val u = User(
                        0, mail,
                        pwd
                    )
                    var role = ""
                    AsyncTask.execute{
                        val db = MyDB.getDatabase(this)
                        val dao = db.userDao()
                        val liste = dao.get()
                        if (liste.isEmpty()) {
                            role = "S_U"
                        } else {
                            role = "basic"
                        }
                        val u1 = UserRecord(0, u.email, u.pwd, role)
                        dao.insertUser(u1)
                    }

                    Toast.makeText(this, "user créé", Toast.LENGTH_LONG).show();
                   
                }
                else{
                    tvEmailError.text = "Cet utilisateur existe déjà"
                    tvEmailError.visibility = View.VISIBLE
                }
            }
            else{
                tvEmailError.text = "Entrez une adresse mail valide"
                tvEmailError.visibility = View.VISIBLE
                tvPwdError.text = "Le mot de passe doit contenir au moins 4 caractères"
                tvPwdError.visibility = View.VISIBLE
            }
        }
        catch (e:Exception){
            e.printStackTrace()
        }

    }

    fun versConnexion(){
        val connexion = Intent(this,ConnexionActivity::class.java)
        startActivity(connexion)
    }
}


What I have tried:

I tried many things but i don't even know why it's not working so it was a bit random
Posted
Updated 25-Dec-23 4:23am
v2

Without the error message printed to the console window by the e.printStackTrace method in your trry/catch block, it's impossible for anyone to tell you what's going wrong.
 
Share this answer
 
Comments
eva joly fabiola yepgwa takedo 25-Dec-23 15:33pm    
the catch function is not called so I don't have the error but I have the logs, i didn't post it because i don't quite understand it
Logs :

KeyboardViewController.show():438 Requesting to show sub view with id 2131428318(key_pos_password_header_numbers) which doesn't exist in current keyboard view
                                                                                                    jyl
                                                                                                    	at klb.a(PG:195)
                                                                                                    	at bty.a(PG:4)
                                                                                                    	at com.google.android.apps.inputmethod.latin.keyboard.LatinPasswordKeyboard.a(PG:19)
                                                                                                    	at kfh.a(PG:15)
                                                                                                    	at kev.a(PG:31)
                                                                                                    	at kev.H(PG:26)
                                                                                                    	at kez.d(PG:10)
                                                                                                    	at kez.b(PG:108)
                                                                                                    	at com.android.inputmethod.latin.LatinIME.b(PG:339)
                                                                                                    	at dwq.onStartInputView(PG:786)
                                                                                                    	at android.inputmethodservice.InputMethodService.doStartInput(InputMethodService.java:2339)
                                                                                                    	at android.inputmethodservice.InputMethodService$InputMethodImpl.startInput(InputMethodService.java:620)
                                                                                                    	at android.inputmethodservice.InputMethodService$InputMethodImpl.dispatchStartInputWithToken(InputMethodService.java:649)
                                                                                                    	at android.inputmethodservice.IInputMethodWrapper.executeMessage(IInputMethodWrapper.java:199)
                                                                                                    	at com.android.internal.os.HandlerCaller$MyHandler.handleMessage(HandlerCaller.java:44)
                                                                                                    	at android.os.Handler.dispatchMessage(Handler.java:106)
                                                                                                    	at android.os.Looper.loop(Looper.java:223)
                                                                                                    	at android.app.ActivityThread.main(ActivityThread.java:7656)
                                                                                                    	at java.lang.reflect.Method.invoke(Native Method)
                                                                                                    	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
                                                                                                    	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)



FATAL EXCEPTION: AsyncTask #2
                                                                                                    Process: be.heh.projet_inventaire, PID: 12811
                                                                                                    java.lang.NullPointerException: Can't toast on a thread that has not called Looper.prepare()
                                                                                                    	at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:157)
                                                                                                    	at android.widget.Toast.getLooper(Toast.java:179)
                                                                                                    	at android.widget.Toast.<init>(Toast.java:164)
                                                                                                    	at android.widget.Toast.makeText(Toast.java:492)
                                                                                                    	at android.widget.Toast.makeText(Toast.java:480)
                                                                                                    	at be.heh.projet_inventaire.MainActivity.addUser$lambda-2(MainActivity.kt:127)
                                                                                                    	at be.heh.projet_inventaire.MainActivity.$r8$lambda$BkrwyiTzOFeXUe8qS3noNnSP7sk(Unknown Source:0)
                                                                                                    	at be.heh.projet_inventaire.MainActivity$$ExternalSyntheticLambda1.run(Unknown Source:6)
                                                                                                    	at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:305)
                                                                                                    	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
                                                                                                    	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
                                                                                                    	at java.lang.Thread.run(Thread.java:923)
 
Share this answer
 
Comments
Dave Kreskowiak 26-Dec-23 0:31am    
java.lang.NullPointerException: Can't toast on a thread that has not called Looper.prepare()

There you go.
eva joly fabiola yepgwa takedo 26-Dec-23 5:20am    
Thank you, the toast was in the asynctask function.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900