1

In my fragment i have dialog(with log out), when user click he log out from app:

override fun onClick(dialog: DialogInterface?, which: Int) {
    AuthUI.getInstance().signOut(requireContext())
}

But after that, I want to send the user to the authorization fragment, in my case this is MainFragment.

So i added next code in my nav_graph:

<fragment
    android:id="@+id/settings_list_fragment"
    android:name="com.mandarine.targetList.features.settings.SettingsListFragment"
    android:label="@string/settings"
    tools:layout="@layout/fragment_settings_list" >
    <action
        android:id="@+id/action_settings_list_fragment_to_mainFragment"
        app:destination="@id/mainFragment" />
</fragment>

Also add line in my function onClick():

override fun onClick(dialog: DialogInterface?, which: Int) {
        AuthUI.getInstance().signOut(requireContext())
        findNavController().navigate(R.id.action_settings_list_fragment_to_mainFragment)
    }

But always when i move to MainFragment my user isn't null.

Only if I kill the app then the user is null.

Here is code of my MainFragment:

class MainFragment : Fragment() {

    private lateinit var auth: FirebaseAuth
    private lateinit var mAuthStateListener: FirebaseAuth.AuthStateListener

    companion object {
        const val TAG = "MainFragment"
        const val SIGN_IN_RESULT_CODE = 1001
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_main, container, false)
    }

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

    override fun onResume() {
        super.onResume()
        auth.addAuthStateListener(mAuthStateListener)
    }

    override fun onPause() {
        super.onPause()
        auth.removeAuthStateListener(mAuthStateListener)
    }

    private fun signIn() {
        auth = FirebaseAuth.getInstance()
        mAuthStateListener = FirebaseAuth.AuthStateListener { firebaseAuth ->
            if (firebaseAuth.currentUser != null) {
                Log.d("some", "user not null")
                findNavController().navigate(R.id.show_goals)
            } else {
                Log.d("some", "null")
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == SIGN_IN_RESULT_CODE) {
            val response = IdpResponse.fromResultIntent(data)
            if (resultCode == Activity.RESULT_OK) {
                // User successfully signed in
                Log.i(TAG, "Successfully signed in user ${FirebaseAuth.getInstance().currentUser?.displayName}!")
            } else {
                // Sign in failed. If response is null the user canceled the
                // sign-in flow using the back button. Otherwise check
                // response.getError().getErrorCode() and handle the error.
                Log.i(TAG, "Sign in unsuccessful ${response?.error?.errorCode}")
            }
        }
    }

    private fun launchSignInFlow() {
        // Give users the option to sign in / register with their email
        // If users choose to register with their email,
        // they will need to create a password as well
        val providers = arrayListOf(
            AuthUI.IdpConfig.EmailBuilder().build(),
            AuthUI.IdpConfig.GoogleBuilder().build()
        )

        // Create and launch sign-in intent.
        // We listen to the response of this activity with the
        // SIGN_IN_RESULT_CODE code
        startActivityForResult(
            AuthUI.getInstance()
                .createSignInIntentBuilder()
                .setAvailableProviders(providers)
                .build(),
             SIGN_IN_RESULT_CODE
        )
    }
}

UPD: For example if i change my onClick in SettingsListFragment all works is correct:

override fun onClick(dialog: DialogInterface?, which: Int) {
    AuthUI.getInstance().signOut(requireContext())
    activity?.finish()
}

But I don't want the user to exit my app

Morozov
  • 4,968
  • 6
  • 39
  • 70
  • Check **[this](https://stackoverflow.com/questions/50885891/one-time-login-in-app-firebaseauth)** out but instead of sending the user to a new activity, navigate to an existing fragment. If you are interested in a clean Firebase authentication, you can check this [article](https://medium.com/firebase-tips-tricks/how-to-create-a-clean-firebase-authentication-using-mvvm-37f9b8eb7336). – Alex Mamo Nov 14 '19 at 12:30
  • @AlexMamo hm but i didn't sending the user to a new activity, i want to navigate him in my existing fragment:`MainFragment`. Also i didn t want to use MVVM in this project, i using MVP – Morozov Nov 14 '19 at 12:36
  • That was what I'm saying, instead of sending the user to an activity simply navigate to the desired fragment. – Alex Mamo Nov 14 '19 at 12:39
  • @AlexMamo so?)) i write that i m tried to send user to fragment with this line `findNavController().navigate(R.id.action_settings_list_fragment_to_mainFragment)` From one fragment to another fragment – Morozov Nov 14 '19 at 12:45
  • That's correct. Aren't you getting to the desired fragment? – Alex Mamo Nov 14 '19 at 12:47
  • @AlexMamo yep, in my `MainFragment`, but the user I have is not null. Also u can check my method `signIn` – Morozov Nov 14 '19 at 12:49
  • @AlexMamo after I click log out I expect to see an authorization window in `MainFragment` since the user is my `null` instead I get the same user... – Morozov Nov 14 '19 at 12:51
  • So you say that you are still authenticated even if you logout? – Alex Mamo Nov 14 '19 at 12:53
  • @AlexMamo Yes, only if I don't kill the app. Maybe he does not have time so quickly to get out of the system, and I throw in another fragment? I don t know – Morozov Nov 14 '19 at 12:58
  • @AlexMamo mb u have some ideas? – Morozov Nov 14 '19 at 13:10
  • No idea so far. – Alex Mamo Nov 14 '19 at 13:12
  • Also, I created a task, mb the full picture will be able to help answer the question, thereby helping me to deal with the problem https://github.com/mnewlive/make-it/issues/30 – Morozov Nov 14 '19 at 14:06

1 Answers1

0

Modified my nav_graph.xml:

<fragment
    android:id="@+id/settings_list_fragment"
    android:name="com.mandarine.targetList.features.settings.SettingsListFragment"
    android:label="@string/settings"
    tools:layout="@layout/fragment_settings_list">

    <action
        android:id="@+id/sign_in"
        app:destination="@id/mainFragment"/>
</fragment>

And add next code:

override fun onClick(dialog: DialogInterface?, which: Int) {
    activity?.let {
        AuthUI.getInstance().signOut(it).addOnCompleteListener {
            findNavController().navigate(R.id.sign_in)
        }
    }
}

That is solved my problem.

Morozov
  • 4,968
  • 6
  • 39
  • 70