Skip to content

Commit

Permalink
Open FirebaseUI Auth sign in screen if user is not logged in.
Browse files Browse the repository at this point in the history
  • Loading branch information
Daniel Mai committed Nov 7, 2016
1 parent 477c12d commit 81d3782
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
4 changes: 4 additions & 0 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ dependencies {

// Firebase
compile 'com.google.firebase:firebase-database:9.6.0'
compile 'com.google.firebase:firebase-auth:9.6.0'

// FirebaseUI
compile 'com.firebaseui:firebase-ui-auth:0.6.0'
}

apply plugin: 'com.google.gms.google-services'
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package com.google.firebase.udacity.friendlychat;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.InputFilter;
Expand All @@ -29,7 +30,11 @@
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.firebase.ui.auth.AuthUI;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
Expand All @@ -46,6 +51,8 @@ public class MainActivity extends AppCompatActivity {
public static final String ANONYMOUS = "anonymous";
public static final int DEFAULT_MSG_LENGTH_LIMIT = 1000;

public static final int RC_SIGN_IN = 1;

private ListView mMessageListView;
private MessageAdapter mMessageAdapter;
private ProgressBar mProgressBar;
Expand All @@ -59,6 +66,8 @@ public class MainActivity extends AppCompatActivity {
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mMessagesDatabaseReference;
private ChildEventListener mChildEventListener;
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;

@Override
protected void onCreate(Bundle savedInstanceState) {
Expand All @@ -69,6 +78,7 @@ protected void onCreate(Bundle savedInstanceState) {

// Initialize Firebase components
mFirebaseDatabase = FirebaseDatabase.getInstance();
mFirebaseAuth = FirebaseAuth.getInstance();

mMessagesDatabaseReference = mFirebaseDatabase.getReference().child("messages");

Expand Down Expand Up @@ -141,6 +151,42 @@ public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
public void onCancelled(DatabaseError databaseError) {}
};
mMessagesDatabaseReference.addChildEventListener(mChildEventListener);

mAuthStateListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Toast.makeText(MainActivity.this, "You're now signed in. Welcome to FriendlyChat.", Toast.LENGTH_SHORT).show();
} else {
// User is signed out
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(false)
.setProviders(
AuthUI.EMAIL_PROVIDER,

This comment has been minimized.

Copy link
@mahye82

mahye82 Mar 2, 2017

setProviders(java.lang.String...) is now deprecated. However, setProviders(List<AuthUI.IdpConfig>) exists. So this should instead read:

                List<AuthUI.IdpConfig> providers = Arrays.asList(
                        new AuthUI.IdpConfig.Builder(AuthUI.EMAIL_PROVIDER).build(),
                        new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build()
                );

                startActivityForResult(
                        AuthUI.getInstance()
                                .createSignInIntentBuilder()
                                .setIsSmartLockEnabled(false)
                                .setProviders(providers)
                                .build(),
                        RC_SIGN_IN);

This comment has been minimized.

Copy link
@bisolaomisore

bisolaomisore Dec 23, 2017

this doesn't work anymore either, you have to change .setProviders(providers) to .setAvailableProviders(providers)

This comment has been minimized.

Copy link
@amicbuczek

amicbuczek Feb 22, 2018

Here is the newest version that you have to use:

startActivityForResult(
        AuthUI.getInstance()
                .createSignInIntentBuilder()
                .setAvailableProviders(Arrays.asList(
                        new AuthUI.IdpConfig.EmailBuilder().build(),
                        new AuthUI.IdpConfig.PhoneBuilder().build(),
                        new AuthUI.IdpConfig.GoogleBuilder().build(),
                        new AuthUI.IdpConfig.FacebookBuilder().build(),
                        new AuthUI.IdpConfig.TwitterBuilder().build()))
                .build(),
        RC_SIGN_IN);

This comment has been minimized.

Copy link
@Tarek-Bohdima

Tarek-Bohdima Aug 25, 2018

            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    // user is signed in
                    onSignedInInitialize(user.getDisplayName());
                } else {
                    // user is signed out
                    onSignedOutCleanup();
                    startActivityForResult(
                            AuthUI.getInstance()
                                    .createSignInIntentBuilder()
                                    .setIsSmartLockEnabled(false)
                                    .setAvailableProviders(Arrays.asList(
                                            new AuthUI.IdpConfig.EmailBuilder().build(),
                                            new AuthUI.IdpConfig.GoogleBuilder().build()))
                                    .setTosAndPrivacyPolicyUrls("https://superapp.example.com/terms-of-service.html",
                                            "https://superapp.example.com/privacy-policy.html")
                                    .build(),
                            RC_SIGN_IN);
                }
            }
        };

This comment has been minimized.

Copy link
@ivanrakonjac

ivanrakonjac Aug 11, 2021

Code that works for me. :D

mAuthStateListener = new FirebaseAuth.AuthStateListener() {
          @Override
          public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
              FirebaseUser user = firebaseAuth.getCurrentUser();
              if(user != null){
                  // user is signed in
                  Toast.makeText(MainActivity.this,"You are signed in!",Toast.LENGTH_SHORT).show();
              }else{
                  //user is signed out

                    Intent signInIntent =
                                AuthUI.getInstance()
                                        .createSignInIntentBuilder()
                                        .setIsSmartLockEnabled(false)
                                        .setAvailableProviders(Arrays.asList(
                                                new AuthUI.IdpConfig.GoogleBuilder().build(),
                                                new AuthUI.IdpConfig.EmailBuilder().build()))
                                        .build();
                    
                    startActivity(signInIntent);
            }
        }
    };
AuthUI.GOOGLE_PROVIDER)
.build(),
RC_SIGN_IN);
}
}
};
}

@Override
protected void onResume() {
super.onResume();
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}

@Override
protected void onPause() {
super.onPause();
if (mAuthStateListener != null) {
mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
}
}

@Override
Expand Down

5 comments on commit 81d3782

@mhakeem531
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i had this problem when adding this dependency
compile 'com.firebaseui:firebase-ui-auth:3.2.2'
screenshot from 2018-03-22 18-46-17

@Testehan
Copy link

@Testehan Testehan commented on 81d3782 Sep 22, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does the email login functionality work for you guys?

My dependencies:

implementation 'com.google.firebase:firebase-database:16.0.2' // for the real time database
implementation 'com.google.firebase:firebase-auth:16.0.3' // authentification
implementation 'com.firebaseui:firebase-ui-auth:4.2.0'

I get the following error in the console, when pressing the "email login" button:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.google.firebase.udacity.friendlychat, PID: 7320
android.view.InflateException: Binary XML file line #24: Binary XML file line #24: Error inflating class android.support.design.widget.TextInputLayout
Caused by: android.view.InflateException: Binary XML file line #24: Error inflating class android.support.design.widget.TextInputLayout
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
at android.view.LayoutInflater.createView(LayoutInflater.java:647)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:790)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:866)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:866)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at com.firebase.ui.auth.ui.email.CheckEmailFragment.onCreateView(CheckEmailFragment.java:89)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2442)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:802)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3273)
at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3229)
at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:201)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:620)
at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:178)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1391)
at android.app.Activity.performStart(Activity.java:7157)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:2937)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:180)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:165)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:142)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:70)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
E/AndroidRuntime: Caused by: java.lang.NoSuchFieldError: No static field error_color_material of type I in class Landroid/support/v7/appcompat/R$color; or its superclasses (declaration of 'android.support.v7.appcompat.R$color' appears in /data/app/com.google.firebase.udacity.friendlychat-LXdQmiN3JebNM8AQtOT5XQ==/split_lib_slice_4_apk.apk)
at android.support.design.widget.TextInputLayout.setErrorEnabled(TextInputLayout.java:654)
at android.support.design.widget.TextInputLayout.(TextInputLayout.java:257)
at android.support.design.widget.TextInputLayout.(TextInputLayout.java:187)
... 42 more

@melike-ertekin
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

New version:

mAuthStateListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();

                if( user != null){
                    //user is signedin
                    Toast.makeText(MainActivity.this, "You're now signed in. Welcome to FriendlyChat.", Toast.LENGTH_SHORT).show();
                }else{
                    //user is signed out
                    // Choose authentication providers
                    List<AuthUI.IdpConfig> providers = Arrays.asList(
                            new AuthUI.IdpConfig.EmailBuilder().build(),
                            new AuthUI.IdpConfig.GoogleBuilder().build());

                    // Create and launch sign-in intent
                    startActivityForResult(
                            AuthUI.getInstance()
                                    .createSignInIntentBuilder()
                                    .setAvailableProviders(providers)
                                    .build(),
                            RC_SIGN_IN);
                }

            }
        };

@melike-ertekin
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

New version:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    //noinspection GradleCompatible
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'

    implementation 'com.google.firebase:firebase-core:16.0.6'
    implementation 'com.github.bumptech.glide:glide:4.7.1'

    implementation 'com.google.firebase:firebase-database:16.0.5'

    implementation 'com.google.firebase:firebase-auth:16.1.0'
    implementation 'com.firebaseui:firebase-ui-auth:4.3.1'

    // Glide v4 uses this new annotation processor -- see https://bumptech.github.io/glide/doc/generatedapi.html
    annotationProcessor 'com.github.bumptech.glide:compiler:4.7.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
apply plugin: 'com.google.gms.google-services'

@nmluthfi
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

my code same as the solution but the Sign In with google account seems not working, when i click, it display available email. Then i click i on my email but notihing happen

Please sign in to comment.