# #android #firebase #android-studio #android-intent #registerforactivityresult
Вопрос:
Я пытаюсь предоставить пользователю возможность войти в учетную запись Google с помощью firebase ранее мне это удалось успешно, но недавно у меня возникла эта проблема, из-за которой я не уверен, почему это происходит
ПРОБЛЕМА-> когда я начинаю другое действие и получаю результат в registerForActivityResult (), я всегда получаю код result.result как 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()
}
}
}
}
Комментарии:
1. Эй! произошла ошибка 404(не найдена), пожалуйста, попробуйте отправить ее снова
2. Пожалуйста, проверьте репо еще раз.
3. спасибо, брат:), но было кое-что еще, из-за чего я столкнулся с этой проблемой, я обновил отпечаток пальца SHA1
4. Определили ли вы что-нибудь особенное
launchMode
для себяActivity
в манифесте?