'How to manage firebase sign-in in another class
I have 3 different Fragments to sign in. This is one of fragment to sign-in.
@AndroidEntryPoint
class SettingFragment : Fragment(){
lateinit var binding: FragmentSettingBinding
private lateinit var auth: FirebaseAuth
private lateinit var googleSignInClient : GoogleSignInClient
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
auth = Firebase.auth
configure_google_login()
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?,
): View? {
binding = FragmentSettingBinding.inflate(inflater,container,false)
binding.apply {
btnLogin.setOnClickListener {
val signInIntent = googleSignInClient.signInIntent
startActivityForResult(signInIntent, signincode)
}
}
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
}
private fun configure_google_login(){
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build()
googleSignInClient = GoogleSignIn.getClient(requireActivity(), gso)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == signincode) {
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
try {
val account = task.getResult(ApiException::class.java)!!
firebaseAuthWithGoogle(account.idToken!!)
} catch (e: ApiException) {
Log.i("catch", "$e")
}
} else {
Log.i("else", "onActivityResult else")
}
}
private fun firebaseAuthWithGoogle(idToken: String) {
var pd = ProgressDialog(activity)
pd.setMessage(resources.getString(R.string.loginisprogressing))
pd.show()
val credential = GoogleAuthProvider.getCredential(idToken, null)
auth.signInWithCredential(credential)
.addOnCompleteListener(requireActivity()) { task ->
if (task.isSuccessful) {
pd.dismiss()
}else{
Toast.makeText(requireActivity(),"google login failed", Toast.LENGTH_LONG).show()
}
}.addOnFailureListener { e ->
Log.i("google login faile", "$e")
}
}
}
I call three method ( 1.configure_google_login() , 2. firebaseAuthWithGoogle() , 3. override onActivityResult() ) , and initialize GoogleSignInClient in this Fragment.
The problem is that I have 3 Fragments to sign-in , and I wrote same code to all of them for sign-in.
I don't think it's desirable and clean design.... I want to manage sign-in in another class so I don't have to write same sign-in code to all 3 Fragments. but I'm having problem to dealt with onActivityResult() in another class.
I searched about it alot to do this, but I couldn't find...
How to manage firebase sign-in in another class??
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
