.setActivity() method in fragment

Viewed 294

I'm creating firebase phone-auth application. (I am learning firebase and navigation controller side by side).

I've 1 activity having NavHostFragment in it, I have 2 fragments (1. for getting phone number, 2. for entering and validating OTP)

There is nothing in my activity. I've crated navigation graph etc. perfectly, and everything (related with navigation controller) is working fine.

So after I added Firebase phone-auth in my fragment-1, I released that the activity does nothing other than controlling fragments.(Question is in the end. See que(2))

Also what about
.setActivity(this) // Activity (for callback binding)

We can't use this in fragment.

My questions are:

  1. Alternative of .setActivity(this) in fragments (kotlin)
  2. Is this correct way, or I should implement it in activity by sending values from fragment to activity.

For detailed code:

class IdentityFragment : Fragment() {

    private var _binding: FragmentIdentityBinding? = null
    private val binding get() = _binding!!

    lateinit var auth: FirebaseAuth
    lateinit var storedVerificationId:String
    lateinit var resendToken: PhoneAuthProvider.ForceResendingToken
    private lateinit var callbacks: PhoneAuthProvider.OnVerificationStateChangedCallbacks

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        auth=FirebaseAuth.getInstance()
    }

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

        binding.etPhone.requestFocus()

        binding.btnSendotp.setOnClickListener {
           sendOTP()
        }
    }

    private fun sendOTP() {
        var phone=binding.etPhone.text.toString().trim()

        if(!phone.isEmpty()) {
            phone = "+91" + phone
            sendVerificationCode(phone)
        }
    }

    private fun sendVerificationCode(phone: String) {
        val options = PhoneAuthOptions.newBuilder(auth)
            .setPhoneNumber(phone) // Phone number to verify
            .setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
            .setActivity()// problem is here
            .setCallbacks(callbacks) // OnVerificationStateChangedCallbacks
            .build()
        PhoneAuthProvider.verifyPhoneNumber(options)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}
1 Answers

In a Fragment, You can use the getActvity() or requireActivity() method to get the activity instance to which this fragment is attached currently.

setActivity(this.requireActivity())//for kotlin getActivity() available in property access as activity

You can still have the callback in the fragment, where you will get the callback of success or failure.

Related