简体   繁体   中英

How to set up Interface and listener in custom Dialog class to pass Facebook's login callback to firebase auth in MainActivity?

I'm having some issues implementing a custom dialog class getting the response from facebook and passing it back to the main activity.

Here there's my custom class:

class LoginDialog(var c: Activity) : Dialog(c), View.OnClickListener {

val mContext = c
private lateinit var realFbButton: LoginButton
private lateinit var listener: LoginListener

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    requestWindowFeature(Window.FEATURE_NO_TITLE)
    getWindow()?.setBackgroundDrawableResource(android.R.color.transparent);
    setContentView(R.layout.login_dialog)

    // here image to cover the real facebook LoginButton
    val loginFbButton: ImageView = findViewById(R.id.facebookButton)
    loginFbButton.setOnClickListener(this)

    // the real facebook login button I wanna click to start the facebook auth process
    realFbButton = findViewById(R.id.facebooOfficalButton)
    realFbButton.setOnClickListener(this)

}

override fun onClick(v: View) {
    when (v.id) {
        R.id.facebookButton -> {realFbButton.performClick()
            // Initialize Facebook Login button
            //TODO: (nothing necessary)
        }
        R.id.facebooOfficalButton -> {
            realFbButton.setReadPermissions("email", "public_profile")

            // register callback after LoginButton has been pushed
            realFbButton.registerCallback(callbackManager, object :
                FacebookCallback<LoginResult>{
                override fun onSuccess(result: LoginResult?) {
                    try{
                        Toast.makeText(context, "success", Toast.LENGTH_LONG).show()
                        // listener to pass result
                        listener.passLoginListener(result)
                    }
                    catch(e: Exception){
                        Toast.makeText(context, "exception" + e, Toast.LENGTH_LONG).show()

                    }
                    TODO("Not yet implemented")
                }

                override fun onCancel() {
                    TODO("Not yet implemented")
                }

                override fun onError(error: FacebookException?) {
                    TODO("Not yet implemented")
                }
            })
        }
        else -> {
            Toast.makeText(mContext, "id not recognized: " + v, Toast.LENGTH_LONG).show()
        }
    }
    dismiss()
}

fun setLoginListener(listener: LoginListener?) {
    this.listener = listener!!
}


interface LoginListener{
    public fun passLoginListener(callBack: LoginResult?)

}

}

In my main activity:

   // interface implementation
   class CentralActivity : AppCompatActivity(), LoginDialog.LoginListener{/* my full class is  here
   ...*/}

   
   override fun passLoginListener(callBack: LoginResult?) {/*here call to handleFacebookAccessToken(token: AccessToken)*/}
  
   // in onCreate overriden method:
   val dialog = LoginDialog(this@CentralActivity)
   dialog.setLoginListener(this@CentralActivity) // this activate the listener

However it doesn't work: even with debugger I can absolulutely tell nothing can pass through the interface to the activity, nor the "on success" response (as the other ones) is triggered.

What can I do to implent it rightly?

I solved the issue and I hope this experience can save someone else some precious time :)

  1. listener needs to be correctly initialized into the custom class, where "c" is the Activity passed from my main activity:

     //in onCreate, inside the custom dialog class: listener = c as LoginDialog.LoginListener
  2. since the callback needs time to come back, it's useless to pass the response to the main activity: instead is better to pass the pushed button

     override fun onClick(v: View) { when (v.id) { R.id.facebookButton -> {realFbButton.performClick() //TODO: nothing here } R.id.facebooOfficalButton -> { realFbButton.setReadPermissions("email", "public_profile") this.listener.passLoginListener(realFbButton) // here we go passing the button to the interface and to the main activity } else -> { Toast.makeText(mContext, "id not recognized: " + v, Toast.LENGTH_LONG).show() } } dismiss()
  3. in main activity let's set it up to wait for the result: here is the listener

     override fun passLoginListener(fbb: LoginButton): LoginButton { // get the LoginButton and set up the receiver fbb.registerCallback(callbackManager, object : FacebookCallback<LoginResult> { override fun onSuccess(result: LoginResult?) { try{ Toast.makeText(applicationContext, "success", Toast.LENGTH_LONG).show() handleFacebookAccessToken(result!!.accessToken) } catch(e: Exception){ Toast.makeText(applicationContext, "exception" + e, Toast.LENGTH_LONG).show() } } override fun onCancel() { TODO("Not yet implemented") } override fun onError(error: FacebookException?) { TODO("Not yet implemented") } }) return fbb }

Now the onActivityResult method can work properly

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    // Pass the activity result back to the Facebook SDK
    callbackManager.onActivityResult(requestCode, resultCode, data)}

The same, now, for the firebase auth initializated in onCreate

    //firebase auth in onCreate
    auth = Firebase.auth

and updated here (see the official firebase doc for this)

private fun handleFacebookAccessToken(token: AccessToken) {
    Log.d("Tag", "handleFacebookAccessToken:$token")
    Toast.makeText(applicationContext, "in handle fb login " + token, Toast.LENGTH_LONG).show()

    val credential = FacebookAuthProvider.getCredential(token.token)
    auth.signInWithCredential(credential)
        .addOnCompleteListener(this) { task ->
            if (task.isSuccessful) {
                // Sign in success, update UI with the signed-in user's information
                Log.d("Tag", "signInWithCredential:success")
                val user = auth.currentUser
                updateUI(user)
            } else {
                // If sign in fails, display a message to the user.
                Log.w("Tag", "signInWithCredential:failure", task.exception)
                Toast.makeText(baseContext, "Authentication failed.",
                    Toast.LENGTH_SHORT).show()
                updateUI(null)
            }

            // ...
        }
}
    

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM