Home > Blockchain >  com.example.myapplication.MainActivity cannot be cast Android Studio kotlin
com.example.myapplication.MainActivity cannot be cast Android Studio kotlin

Time:05-25

I created a Login/Register Page and I get this error while trying to click Register Button.This method should send me to Register Page where I can register a new account.The problem is I get this error when I click the register button: android app code error

How can I resolve this error ?

Here is my code and other screenshots:

 class LoginFragment : Fragment() {

    private lateinit var username: EditText
    private lateinit var password: EditText
    private lateinit var fAuth: FirebaseAuth


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {

        val view = inflater.inflate(R.layout.fragment_login, container, false)

        username = view.findViewById(R.id.log_username)
        password = view.findViewById(R.id.log_password)
        fAuth = Firebase.auth



        view.findViewById<Button>(R.id.btn_register).setOnClickListener {

            val navRegister = activity as FragmentNav
            navRegister.navigateFrag(RegisterFragment(),false)

        }

        view.findViewById<Button>(R.id.btn_login).setOnClickListener {
            validateForm()
        }
        return view
    }

    private fun firebaseSignIn(){

        fAuth.signInWithEmailAndPassword(username.text.toString(),password.text.toString()).addOnCompleteListener{
            task ->
            if(task.isSuccessful){

            }else{


                Toast.makeText(context,"Register Successful",Toast.LENGTH_SHORT).show()

                var navHome = activity as FragmentNav
                navHome.navigateFrag(HomeFragment(),addToStack = true)



            }
        }
    }


    private fun validateForm() {

        val icon = AppCompatResources.getDrawable(requireContext(), R.drawable.erroricon)

        icon?.setBounds(0, 0, icon.intrinsicWidth, icon.intrinsicHeight)
        when {
            TextUtils.isEmpty(username.text.toString().trim()) -> {
                username.setError("Please Enter Username")
            }
            TextUtils.isEmpty(password.text.toString().trim()) -> {
                password.setError("Please Enter Password")
            }


            username.text.toString().isNotEmpty() &&
                    password.text.toString().isNotEmpty() -> {


                if (username.text.toString().matches(Regex("[a-zA-Z0-9._] @[a-z] \\\\. [a-z] "))) {

                    firebaseSignIn()




                } else {
                    username.setError("Please Enter Valid Email Id")
                }

            }
        }

    }

I get this error here: error

  FragmentNav {

    fun navigateFrag(fragment: Fragment, addToStack:Boolean )
}

Here is the navigation between buttons register/login :

 class LoginActivity : AppCompatActivity(R.layout.login_activity),FragmentNav {

    private lateinit var fAuth: FirebaseAuth

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.login_activity)

        fAuth = Firebase.auth

        val currentUser = fAuth.currentUser
        if(currentUser !=null){
            supportFragmentManager.beginTransaction()
                    .add(com.google.android.material.R.id.container,HomeFragment()).addToBackStack(null)
                    .commit()
        }

        supportFragmentManager.beginTransaction()
                .add(com.google.android.material.R.id.container,LoginFragment())
                .commit()


    }

    override fun navigateFrag(fragment: Fragment, addToStack: Boolean) {
        val transaction = supportFragmentManager
                .beginTransaction()
                .replace(com.google.android.material.R.id.container,fragment)

        if(addToStack){
            transaction.addToBackStack(null)
        }
        transaction.commit()


    }
}

CodePudding user response:

That interface is totally useless if you are not passing the MainActivity context to the LoginFragment. Change LoginFragment constructor to this:

class LoginFragment(private val mListener: FragmentNav) : Fragment()

and in onClick() of the register button, call navigateFrag like this:

mListener.navigateFrag(RegisterFragment(),false)

And finally in MainActivity, pass context to LoginFragment like this:

supportFragmentManager.beginTransaction()
            .add(com.google.android.material.R.id.container,LoginFragment(this))
            .commit()
  • Related