首页 > 解决方案 > 始终获取结果代码 RESULT_CANCELED

问题描述

我试图让用户选择使用firebase使用google帐户登录,我之前成功地做到了这一点,但最近我遇到了这个问题,我不确定为什么会这样

ISSUE->当我开始另一个活动并在 registerForActivityResult() 中返回结果时,我总是将 result.resultCode 设为 0,即 RESULT_CANCELED

这是注册片段

class NewAccountFragment : Fragment() {
    private lateinit var binding: FragmentNewAccountBinding

    //declaring and initializing the shareViewModel
    private val sharedViewModel:SharedViewModel by activityViewModels()
    private lateinit var auth:FirebaseAuth


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


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

        //setting the things to use if user taps on google button
        sharedViewModel.getGso(requireContext()) //to get info from user's gmail id
        sharedViewModel.getGSC(requireContext())//google signInClient

        //initializing fire base auth
        auth = FirebaseAuth.getInstance()

        //handling the click of register button
        binding.registerButton.setOnClickListener {
            startRegistrationProcess()
        }

        //handling the click of google sign in button
        binding.googleSignInButton.setOnClickListener {
            val intent = sharedViewModel.getSignInIntent(requireContext())
            if(intent!=null){
                //receiving intent to show pop up on screen to show option which account he/she will use for this app
                //and passing this intent to googleLauncher
                googleLauncher.launch(intent)
            }
        }

    }

    //this will handle the result from that pop up
    private var googleLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        when (result.resultCode) {

            RESULT_OK-> {
                // There are no request codes
                val data: Intent? = result.data
                val task = GoogleSignIn.getSignedInAccountFromIntent(data)
                try {
                    // Google Sign In was successful, authenticate with Firebase
                    val account = task.getResult(ApiException::class.java)!!

                    //telling sharedViewModel to signIn the user with it's google account on firebase
                    sharedViewModel.firebaseAuthWithGoogle(account.idToken!!, requireContext())
                    //clearing up the inputs
                    binding.passwordEt.setText("")
                    binding.emailEt.setText("")
                } catch (e: ApiException) {
                    // Google Sign In failed, show error on toast
                    Toast.makeText(requireContext(), e.message, Toast.LENGTH_SHORT).show()
                }
            }

            RESULT_CANCELED->{
                Toast.makeText(requireContext(),"result failed",Toast.LENGTH_SHORT).show()
            }

        }
    }


    private fun startRegistrationProcess() {
        //getting text from editTexts
        val email = binding.emailEt.text.toString().trim()
        val password = binding.passwordEt.text.toString().trim()

        //Validation.
        //if email matches the standards
        if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            binding.emailEt.error = "Invalid Email"
        } else if (password.length < 8) {
            //set error and focus on passWord.
           binding.passwordEt.error = "Enter more than 7 character"

        } else {
            //telling shareViewModel to crate account for this use with email and password
           sharedViewModel.registerOnFirebase(email,password,requireContext())
            binding.passwordEt.setText("")
            binding.emailEt.setText("")
        }
    }



}

这是附加的视图模型

class SharedViewModel:ViewModel() {

    private lateinit var gso:GoogleSignInOptions
    private lateinit var googleSignInClient:GoogleSignInClient
    private val auth: FirebaseAuth = FirebaseAuth.getInstance()

    //  -> FOR NEW ACCOUNT FRAGMENT

                            //for firebase registration
                                        fun registerOnFirebase( email:String, password:String,context: Context){
                                            auth.createUserWithEmailAndPassword(email, password).addOnCompleteListener { task->
                                                if(task.isSuccessful){
                                                    //user has signed in successfully
                                                    Toast.makeText(context, "Account created successfully!!", Toast.LENGTH_SHORT).show()
                                                    // go to dashboard activity
                                                    val intent = Intent(context,DashboardActivity::class.java)
                                                    //intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
                                                    context.startActivity(intent)
                                                    MainActivity.isAlive.value = false

                                                }else{
                                                    Toast.makeText(context, "error: ${task.exception!!.message}", Toast.LENGTH_SHORT).show()
                                                }
                                            }
                                        }


                            //for google registration
                                        fun getGso(context: Context){
                                            gso = GoogleSignInOptions
                                                .Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                                                .requestIdToken(context.getString(R.string.server_client_id))
                                                .requestEmail()
                                                .build()
                                        }

                                        fun getGSC(context: Context){
                                            googleSignInClient = GoogleSignIn.getClient(context,gso)
                                        }


                                       fun getSignInIntent(context: Context): Intent? {
                                           val duplicate = checkDelicacy(context) //true if duplicate
                                           if(duplicate){
                                               Toast.makeText(context, "Already a member, Please logIn", Toast.LENGTH_SHORT).show()
                                           } else {
                                               return googleSignInClient.signInIntent
                                           }

                                           return null
                                       }


                                        fun firebaseAuthWithGoogle(idToken: String,context: Context) {
                                            val credential = GoogleAuthProvider.getCredential(idToken, null)
                                           auth.signInWithCredential(credential).addOnCompleteListener { task->
                                                if(task.isSuccessful){
                                                    //if registered  with google successfully then navigate to DashboardActivity with a toast
                                                    Toast.makeText(context, "Signed in with google", Toast.LENGTH_SHORT).show()
                                                    //navigate to DashboardActivity
                                                    val intent = Intent(context,DashboardActivity::class.java)
                                                    context.startActivity(intent)
                                                    MainActivity.isAlive.value = false
                                                }else{
                                                    Toast.makeText(context, "error: ${task.exception!!.message}", Toast.LENGTH_SHORT).show()
                                                }
                                            }
                                        }

                                        private fun checkDelicacy(context: Context): Boolean {
                                            val account = GoogleSignIn.getLastSignedInAccount(context)
                                            return account!=null
                                        }



    //  -> FOR ALREADY ACCOUNT FRAGMENT

                 //logging in with email and password
                 fun logInWithFireBase(email: String, password: String,context: Context) {
                    auth.signInWithEmailAndPassword(email,password).addOnCompleteListener { task->
                        if(task.isSuccessful){
                            //if logged in successfully then navigate to DashboardActivity with a toast
                            Toast.makeText(context, "Logged in successfully!!", Toast.LENGTH_SHORT).show()
                            val intent = Intent(context,DashboardActivity::class.java)
                            context.startActivity(intent)
                            MainActivity.isAlive.value = false
                        }else{
                            Toast.makeText(context, "error: ${task.exception!!.message}", Toast.LENGTH_SHORT).show()
                        }
                    }
                }



}

标签: androidfirebaseandroid-studioandroid-intentregisterforactivityresult

解决方案


推荐阅读