Java Code Examples for com.google.firebase.auth.FirebaseAuth#AuthStateListener

The following examples show how to use com.google.firebase.auth.FirebaseAuth#AuthStateListener . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FirestackAuth.java    From react-native-firestack with MIT License 6 votes vote down vote up
@ReactMethod
public void listenForAuth() {
  mAuthListener = new FirebaseAuth.AuthStateListener() {

  @Override
  public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
      WritableMap msgMap = Arguments.createMap();
      msgMap.putString("eventName", "listenForAuth");

      if (firebaseAuth.getCurrentUser() != null) {
          WritableMap userMap = getUserMap();

          msgMap.putBoolean("authenticated", true);
          msgMap.putMap("user", userMap);

          FirestackUtils.sendEvent(mReactContext, "listenForAuth", msgMap);
      } else {
          msgMap.putBoolean("authenticated", false);
          FirestackUtils.sendEvent(mReactContext, "listenForAuth", msgMap);
      }
      }
    };

    mAuth = FirebaseAuth.getInstance();
    mAuth.addAuthStateListener(mAuthListener);
  }
 
Example 2
Source File: AuthStateChangesOnSubscribe.java    From rxfirebase with Apache License 2.0 6 votes vote down vote up
/**
 * @param emitter
 */
@Override
public void subscribe(final ObservableEmitter<FirebaseAuth> emitter) {
    final FirebaseAuth.AuthStateListener listener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            if (!emitter.isDisposed()) {
                emitter.onNext(firebaseAuth);
            }
        }
    };

    instance.addAuthStateListener(listener);

    emitter.setDisposable(Disposables.fromAction(new Action() {
        @Override
        public void run() throws Exception {
            instance.removeAuthStateListener(listener);
        }
    }));
}
 
Example 3
Source File: FirebaseAuthManager.java    From Android-MVP-vs-MVVM-Samples with Apache License 2.0 6 votes vote down vote up
public FirebaseAuthManager() {
    super();
    mAuth = FirebaseAuth.getInstance();
    mAuthListener = new FirebaseAuth.AuthStateListener() {

        @Override
        public final void onAuthStateChanged(final @NonNull FirebaseAuth firebaseAuth) {
            final FirebaseUser _user = firebaseAuth.getCurrentUser();

            if (_user != null) {
                // User is signed in
                user = _user;
            } else {
                // User is signed out
                user = null;
            }

            if (authStateListener != null) authStateListener.onAuthorized(_user != null);
        }
    };
}
 
Example 4
Source File: MainActivity.java    From Simple-Blog-App with MIT License 6 votes vote down vote up
private void firebaseInit() {

        mAuth = FirebaseAuth.getInstance();
        mAuthListener = new FirebaseAuth.AuthStateListener() {

            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                if (FirebaseAuth.getInstance().getCurrentUser() == null) {
                    Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
                    loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(loginIntent);
                }//if there is no curreent user then only move to liginActivity
            }
        };
        mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
        mDatabaseUsers = FirebaseDatabase.getInstance().getReference().child("Users");
        mDBRefSetup = FirebaseDatabase.getInstance().getReference().child("Users");
        mDatabaseLike = FirebaseDatabase.getInstance().getReference().child("Likes");
        mDatabaseLike.keepSynced(true);
        mDatabaseUsers.keepSynced(true);
        mDatabase.keepSynced(true);
    }
 
Example 5
Source File: LoginActivity.java    From Stayfit with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    for (String provider : AuthUI.SUPPORTED_PROVIDERS) {
        Log.v(this.getClass().getName(), provider);
    }

    mAuth = FirebaseAuth.getInstance();
    mDatabase = FirebaseDatabase.getInstance().getReference();
    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            updateInfo();
        }
    };

    startActivityForResult(
            AuthUI.getInstance()
                    .createSignInIntentBuilder()
                    .setIsSmartLockEnabled(false)
                    .setAvailableProviders(providers)
                    .setLogo(R.drawable.stayfit)
                    .build(),
            RC_SIGN_IN);
}
 
Example 6
Source File: RxFirebaseAuthTests.java    From RxFirebase with Apache License 2.0 6 votes vote down vote up
@Test
public void testObserveAuthState()  {

    TestSubscriber<FirebaseUser> testSubscriber = new TestSubscriber<>();
    RxFirebaseAuth.observeAuthState(mockAuth)
            .subscribeOn(Schedulers.immediate())
            .subscribe(testSubscriber);

    ArgumentCaptor<FirebaseAuth.AuthStateListener> argument = ArgumentCaptor.forClass(FirebaseAuth.AuthStateListener.class);
    verify(mockAuth).addAuthStateListener(argument.capture());
    argument.getValue().onAuthStateChanged(mockAuth);

    testSubscriber.assertNoErrors();
    testSubscriber.assertValueCount(1);
    testSubscriber.assertReceivedOnNext(Collections.singletonList(mockUser));
    testSubscriber.assertNotCompleted();
    testSubscriber.unsubscribe();
}
 
Example 7
Source File: ChatAuthentication.java    From chat21-android-sdk with GNU Affero General Public License v3.0 5 votes vote down vote up
public void createAuthListener(final OnAuthStateChangeListener onAuthStateChangeListener) {
    Log.d(DEBUG_LOGIN, "createAuthListener");

    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            Log.d(DEBUG_LOGIN, "onAuthStateChanged");

            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                Log.i(DEBUG_LOGIN, "onAuthStateChanged:signed_in:" + user.getUid());

                if (!isEmailUpdated)
                    updateUserEmail(getEmail());

                if (!isUserProfileUpdated)
                    updateUserProfile(getFullName(), null);

                onAuthStateChangeListener.onAuthStateChanged(user);

            } else {
                // User is signed out
                Log.i(DEBUG_LOGIN, "onAuthStateChanged:signed_out");

                onAuthStateChangeListener.onAuthStateChanged(null);
            }
        }
    };
}
 
Example 8
Source File: AnonymousAuthActivity.java    From endpoints-samples with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_anonymous_auth);

    // [START initialize_auth]
    mAuth = FirebaseAuth.getInstance();
    // [END initialize_auth]

    // [START auth_state_listener]
    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
            } else {
                // User is signed out
                Log.d(TAG, "onAuthStateChanged:signed_out");
            }
            // [START_EXCLUDE]
            updateUI(user);
            // [END_EXCLUDE]
        }
    };
    // [END auth_state_listener]

    // Fields
    mEmailField = (EditText) findViewById(R.id.field_email);
    mPasswordField = (EditText) findViewById(R.id.field_password);

    // Click listeners
    findViewById(R.id.button_anonymous_sign_in).setOnClickListener(this);
    findViewById(R.id.button_anonymous_sign_out).setOnClickListener(this);
    findViewById(R.id.button_link_account).setOnClickListener(this);
}
 
Example 9
Source File: EmailPasswordActivity.java    From endpoints-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_emailpassword);

    // Views
    mStatusTextView = (TextView) findViewById(R.id.status);
    mDetailTextView = (TextView) findViewById(R.id.detail);
    mEmailField = (EditText) findViewById(R.id.field_email);
    mPasswordField = (EditText) findViewById(R.id.field_password);

    // Buttons
    findViewById(R.id.email_sign_in_button).setOnClickListener(this);
    findViewById(R.id.email_create_account_button).setOnClickListener(this);
    findViewById(R.id.sign_out_button).setOnClickListener(this);

    // [START initialize_auth]
    mAuth = FirebaseAuth.getInstance();
    // [END initialize_auth]

    // [START auth_state_listener]
    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
            } else {
                // User is signed out
                Log.d(TAG, "onAuthStateChanged:signed_out");
            }
            // [START_EXCLUDE]
            updateUI(user);
            // [END_EXCLUDE]
        }
    };
    // [END auth_state_listener]
}
 
Example 10
Source File: CustomAuthActivity.java    From endpoints-samples with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_custom);

    // Button click listeners
    findViewById(R.id.button_sign_in).setOnClickListener(this);

    // Create token receiver (for demo purposes only)
    mTokenReceiver = new TokenBroadcastReceiver() {
        @Override
        public void onNewToken(String token) {
            Log.d(TAG, "onNewToken:" + token);
            setCustomToken(token);
        }
    };

    // [START initialize_auth]
    mAuth = FirebaseAuth.getInstance();
    // [END initialize_auth]

    // [START auth_state_listener]
    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
            } else {
                // User is signed out
                Log.d(TAG, "onAuthStateChanged:signed_out");
            }
            // [START_EXCLUDE]
            updateUI(user);
            // [END_EXCLUDE]
        }
    };
    // [END auth_state_listener]
}
 
Example 11
Source File: FacebookLoginActivity.java    From endpoints-samples with Apache License 2.0 4 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(getApplicationContext());
    setContentView(R.layout.activity_facebook);

    // Views
    mStatusTextView = (TextView) findViewById(R.id.status);
    mDetailTextView = (TextView) findViewById(R.id.detail);
    mResponseTextView = (TextView) findViewById(R.id.response);
    findViewById(R.id.button_facebook_signout).setOnClickListener(this);

    // [START initialize_auth]
    // Initialize Firebase Auth
    mAuth = FirebaseAuth.getInstance();
    // [END initialize_auth]

    // [START auth_state_listener]
    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
            } else {
                // User is signed out
                Log.d(TAG, "onAuthStateChanged:signed_out");
            }
            // [START_EXCLUDE]
            updateUI(user);
            // [END_EXCLUDE]
        }
    };
    // [END auth_state_listener]

    // [START initialize_fblogin]
    // Initialize Facebook Login button
    mCallbackManager = CallbackManager.Factory.create();
    LoginButton loginButton = (LoginButton) findViewById(R.id.button_facebook_login);
    loginButton.setReadPermissions("email", "public_profile");
    loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            Log.d(TAG, "facebook:onSuccess:" + loginResult);
            handleFacebookAccessToken(loginResult.getAccessToken());
        }

        @Override
        public void onCancel() {
            Log.d(TAG, "facebook:onCancel");
            // [START_EXCLUDE]
            updateUI(null);
            // [END_EXCLUDE]
        }

        @Override
        public void onError(FacebookException error) {
            Log.d(TAG, "facebook:onError", error);
            // [START_EXCLUDE]
            updateUI(null);
            // [END_EXCLUDE]
        }
    });
    // [END initialize_fblogin]
}
 
Example 12
Source File: RegisterActivity.java    From SnapchatClone with MIT License 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);

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

            if (user != null) {
                Intent intent = new Intent(getApplication(), MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                finish();
            }
        }
    };

    mAuth = FirebaseAuth.getInstance();

    mRegister = findViewById(R.id.buttonRegister);

    mEmail = findViewById(R.id.editTextEmailRegister);
    mPassword = findViewById(R.id.editTextPasswordRegister);
    mUsername = findViewById(R.id.editTextUsernameRegister);

    passwordLayout = findViewById(R.id.editTextPasswordRegisterLay);
    emailLayout = findViewById(R.id.editTextEmailRegisterLay);
    usernameLayout = findViewById(R.id.editTextUsernameRegisterLay);

    mPassword.addTextChangedListener(new MyTextWatcher(mPassword));
    mUsername.addTextChangedListener(new MyTextWatcher(mUsername));
    mEmail.addTextChangedListener(new MyTextWatcher(mEmail));

    mRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (!validateEmail()) {
                return;
            }

            if (!validatePassword()) {
                return;
            }

            if (!validateUsername()) {
                return;
            }

            final String username = mUsername.getText().toString();
            final String email = mEmail.getText().toString();
            final String password = mPassword.getText().toString();

            mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(RegisterActivity.this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (!task.isSuccessful()) {
                        Toast.makeText(getApplication(), "Sign in ERROR", Toast.LENGTH_LONG).show();
                    } else {
                        String userId = mAuth.getCurrentUser().getUid();
                        DatabaseReference currentUserDB = FirebaseDatabase.getInstance().getReference().child("users").child(userId);

                        Map userInfo = new HashMap();
                        userInfo.put("email", email);
                        userInfo.put("username", username);
                        userInfo.put("profileImageUrl", "default");

                        currentUserDB.updateChildren(userInfo);
                    }
                }
            });
        }
    });
}
 
Example 13
Source File: GoogleSignInActivity.java    From endpoints-samples with Apache License 2.0 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_google);

    // Views
    mStatusTextView = (TextView) findViewById(R.id.status);
    mDetailTextView = (TextView) findViewById(R.id.detail);
    mResponseTextView = (TextView) findViewById(R.id.response);

    // Button listeners
    findViewById(R.id.sign_in_button).setOnClickListener(this);
    findViewById(R.id.sign_out_button).setOnClickListener(this);
    findViewById(R.id.disconnect_button).setOnClickListener(this);

    // [START config_signin]
    // Configure Google Sign In
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build();
    // [END config_signin]

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();

    // [START initialize_auth]
    mAuth = FirebaseAuth.getInstance();
    // [END initialize_auth]

    // [START auth_state_listener]
    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
            } else {
                // User is signed out
                Log.d(TAG, "onAuthStateChanged:signed_out");
            }
            // [START_EXCLUDE]
            updateUI(user);
            // [END_EXCLUDE]
        }
    };
    // [END auth_state_listener]
}
 
Example 14
Source File: TwitterLoginActivity.java    From endpoints-samples with Apache License 2.0 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Configure Twitter SDK
    TwitterAuthConfig authConfig =  new TwitterAuthConfig(
            getString(R.string.twitter_consumer_key),
            getString(R.string.twitter_consumer_secret));
    Fabric.with(this, new Twitter(authConfig));

    // Inflate layout (must be done after Twitter is configured)
    setContentView(R.layout.activity_twitter);

    // Views
    mStatusTextView = (TextView) findViewById(R.id.status);
    mDetailTextView = (TextView) findViewById(R.id.detail);
    findViewById(R.id.button_twitter_signout).setOnClickListener(this);

    // [START initialize_auth]
    // Initialize Firebase Auth
    mAuth = FirebaseAuth.getInstance();
    // [END initialize_auth]

    // [START auth_state_listener]
    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
            } else {
                // User is signed out
                Log.d(TAG, "onAuthStateChanged:signed_out");
            }
            // [START_EXCLUDE]
            updateUI(user);
            // [END_EXCLUDE]
        }
    };
    // [END auth_state_listener]

    // [START initialize_twitter_login]
    mLoginButton = (TwitterLoginButton) findViewById(R.id.button_twitter_login);
    mLoginButton.setCallback(new Callback<TwitterSession>() {
        @Override
        public void success(Result<TwitterSession> result) {
            Log.d(TAG, "twitterLogin:success" + result);
            handleTwitterSession(result.data);
        }

        @Override
        public void failure(TwitterException exception) {
            Log.w(TAG, "twitterLogin:failure", exception);
            updateUI(null);
        }
    });
    // [END initialize_twitter_login]
}
 
Example 15
Source File: PlaceDetailActivity.java    From protrip with MIT License 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_place_detail);
    //Enable support for vector drawables on Pre-lollipop devices
    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);

    if (getIntent().getExtras() != null) {
        place_id = getIntent().getStringExtra("place_id");
        place_name = getIntent().getStringExtra("place_name");
        image_URL = getIntent().getStringExtra("image_URL");
        Log.d(TAG, "Image url " + image_URL);
        //Toast.makeText(this, place_id, Toast.LENGTH_SHORT).show();

    }

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


    //Views and click listeners
    coordinatorLayout = (CoordinatorLayout) findViewById(R.id.activity_place_detail);
    fabFav = (FloatingActionButton) findViewById(R.id.fab_favorite);
    rbRatingBar = (RatingBar) findViewById(R.id.rating);
    tvAddress = (TextView) findViewById(R.id.address);
    llUrlIcon = (LinearLayout) findViewById(R.id.icon_link);
    llCall = (LinearLayout) findViewById(R.id.icon_call);
    llDirections = (LinearLayout) findViewById(R.id.icon_directions);
    llReviews = (LinearLayout) findViewById(R.id.layout_reviews);
    fabFav.setOnClickListener(this);
    llUrlIcon.setOnClickListener(this);
    llCall.setOnClickListener(this);
    llDirections.setOnClickListener(this);

    //Toolbar
    Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar_layout);
    collapsingToolbarLayout.setTitle(place_name);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    mBanner = (ImageView) findViewById(R.id.banner);
    if (image_URL != null && !image_URL.isEmpty()) {
        Picasso.with(this).load(image_URL).fit().into(mBanner);
    }

    //Ui


    final String DOMAIN = Constants.BASE_URL_PLACE_DETAILS;
    final String APPKEY_PARAM = Constants.API_KEY_PARAM;
    final String PLACE_ID_PARAM = Constants.PLACE_ID_PARAM;


    try {
        StringBuilder sb = new StringBuilder(DOMAIN)
                .append(PLACE_ID_PARAM + "=" + place_id)
                .append("&" + APPKEY_PARAM + "=" + Constants.API_VALUE);

        Log.d(TAG, "Place URL built " + sb.toString());

        fetchPlaceDetails(sb.toString());

    } catch (Exception e) {
        Log.e(TAG, "Error building url");
    }

    //Firebase Auth listener
    mAuthStateListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                onSignedInInitialize(user);
            } else {
                // User is signed out
                onSignedOutCleanup();
                //showFirebaseLogin();
            }
        }
    };
}
 
Example 16
Source File: newUser.java    From NITKart with MIT License 4 votes vote down vote up
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_user);
        username = (EditText) findViewById(R.id.usernameRegistration);
        pass = (EditText) findViewById(R.id.passwordRegistration);
        passVerification = (EditText) findViewById(R.id.passwordRegistrationConfirmation);
        firstname = (EditText) findViewById(R.id.firstName);
        lastname = (EditText) findViewById(R.id.lastName);

        isSeller = getIntent().getExtras().getBoolean("seller");
        if(isSeller){
            ((TextView) findViewById(R.id.userRegistrationPageTitle)).setText("Seller Registration");
        }

        setViews(true);

        progressBar = (ProgressBar) findViewById(R.id.registrationPageProgressBar);

        mAuth = FirebaseAuth.getInstance();
        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    // User is signed in
                    Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
                    String name = firstname.getText().toString() + " " + lastname.getText().toString();
                    UserProfileChangeRequest profileChangeRequest = new UserProfileChangeRequest.Builder().
                            setDisplayName(name).build();
                    user.updateProfile(profileChangeRequest);

                    DatabaseReference myRef;

                    if (!isSeller){
                        myRef = FirebaseDatabase.getInstance().getReference("users").child(user.getUid());
                        myRef.child(user.getUid()).push();

                        // As firebase does not accept keys with empty values, I'm putting a dummy item with empty Strings and -1 as ints
                        // Quantity of items in cart is not realtime database quantity but the quantity the user wants
                        ArrayList<ShoppingItem> cart = new ArrayList<>();
                        cart.add(new ShoppingItem("", "", "", "", -1, -1));
                        Map<String, Object> cartItems = new HashMap<>();
                        cartItems.put("cartItems", cart);

                        // Adding a isCartEmpty State Variable for cart window display

                        Map<String, Object> cartState = new HashMap<>();
                        cartState.put("isCartEmpty", Boolean.TRUE);

                        // Updating the database for the user
                        myRef.updateChildren(cartItems);
                        myRef.updateChildren(cartState);
                    } else {
                        myRef = FirebaseDatabase.getInstance().getReference("sellers").child(user.getUid());
                        myRef.child(user.getUid()).push();

//                        Dummy product sold by any seller who has 0 products
                        ArrayList<ShoppingItem> prods = new ArrayList<>();
                        prods.add(new ShoppingItem("", "", "", "", -1, -1));
                        Map<String, Object> prodslist = new HashMap<>();
                        prodslist.put("products", prods);

                        Map<String, Object> state = new HashMap<>();
                        state.put("isEmpty", Boolean.TRUE);

                        // Updating the database for the seller
                        myRef.updateChildren(prodslist);
                        myRef.updateChildren(state);
                    }

                    sendVerificationEmail();

                } else {
                    // User is signed out
                    Log.d(TAG, "onAuthStateChanged:signed_out");
                }
            }
        };

        mRegister = (Button) findViewById(R.id.registerButton);
        mRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setViews(false);
                email = username.getText().toString();
                password = pass.getText().toString();
                passwordVerification = passVerification.getText().toString();
                if (password.equals(passwordVerification) && !password.equals("") && !passwordVerification.equals("")) {
                    createAccount();
                } else {
                    Snackbar.make(findViewById(R.id.newUserPage), "Passwords don't match", Snackbar.LENGTH_SHORT).show();
                    pass.setText("");
                    passVerification.setText("");
                    setViews(true);
                }
            }
        });
    }
 
Example 17
Source File: SignInBaseActivity.java    From Expert-Android-Programming with MIT License 4 votes vote down vote up
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    FacebookSdk.sdkInitialize(getApplicationContext());
    callbackManager = CallbackManager.Factory.create();

    LoginManager.getInstance().registerCallback(callbackManager,
            new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult) {

                    // App code
                    MyLg.e(TAG, "Get Facebook User Details");
                    handleFacebookAccessToken(loginResult.getAccessToken());
                }

                @Override
                public void onCancel() {
                    // App code
                    MyLg.e(TAG, "Get Facebook onCancel");
                }

                @Override
                public void onError(FacebookException exception) {
                    // App code
                    MyLg.e(TAG, "Get Facebook onError ");
                    exception.printStackTrace();
                }
            });


    // Configure Google Sign In
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build();

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this, this)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();

    mAuth = FirebaseAuth.getInstance();
    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                MyLg.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
            } else {
                // User is signed out
                MyLg.d(TAG, "onAuthStateChanged:signed_out");
            }

            onGotFirebaseUser(user);
        }
    };
}
 
Example 18
Source File: MainActivity.java    From CourierApplication with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Set SharedPreferences
    mSharedPreferences = getSharedPreferences(PREFERENCES_NAME, Activity.MODE_PRIVATE);
    // Set a toolbar to replace the actionbar
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    // Find drawer view
    mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    // Tie DrawerLayout events to the ActionBarToggle.
    drawerToggle = setupDrawerToggle();
    mDrawer.addDrawerListener(drawerToggle);

    // Attach listener to drawer menuitems and handle user selections.
    NavigationView nvDrawer = (NavigationView) findViewById(R.id.nvView);
    //View drawerHeader = nvDrawer.inflateHeaderView(R.layout.drawer_header);
    setupDrawerContent(nvDrawer);

    mAuth = FirebaseAuth.getInstance();
    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            if(firebaseAuth.getCurrentUser() != null) {
                if(getIntent().getExtras() == null) {
                    // Begin transaction
                    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                    // Replace the contents of the container with the new fragment
                    ft.replace(R.id.fragment_placeholder, new NewOrderFragment());
                    // Complete the changes added above.
                    ft.commit();
                } else {
                    Bundle extras = getIntent().getExtras();
                    if(extras.containsKey(MyFirebaseMessagingService.NOTIFICATION_TYPE)) {
                        String type = extras.getString(MyFirebaseMessagingService.NOTIFICATION_TYPE);
                        if (type.equals("new") || type.equals("taken")) {
                            saveData(extras.getString(MyFirebaseMessagingService.NOTIFICATION_TIMESTAMP));
                            Class fragmentClass = CurrentOrderFragment.class;
                            Fragment fragment = null;
                            try {
                                fragment = (Fragment) fragmentClass.newInstance();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                            ft.replace(R.id.fragment_placeholder, fragment);
                            ft.commit();
                        } else if(type.equals("finished")) {
                            saveData(PREFERENCES_EMPTY);
                            // Begin transaction
                            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                            // Replace the contents of the container with the new fragment
                            ft.replace(R.id.fragment_placeholder, new ProfileFragment());
                            // Complete the changes added above.
                            ft.commit();
                        }
                    } else {
                        // Begin transaction
                        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                        // Replace the contents of the container with the new fragment
                        ft.replace(R.id.fragment_placeholder, new NewOrderFragment());
                        // Complete the changes added above.
                        ft.commit();
                    }
                }
            } else {
                finish();
                startActivity(new Intent(MainActivity.this, LoginActivity.class));
            }
        }
    };
}
 
Example 19
Source File: ChatAuthentication.java    From chat21-android-sdk with GNU Affero General Public License v3.0 4 votes vote down vote up
public FirebaseAuth.AuthStateListener getAuthListener() {
    return mAuthListener;
}
 
Example 20
Source File: LoginActivity.java    From SnapchatClone with MIT License 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

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

            if (user != null) {
                Intent intent = new Intent(getApplication(), MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                finish();
            }
        }
    };

    mAuth = FirebaseAuth.getInstance();

    mLogin = findViewById(R.id.buttonLogin);

    mEmail = findViewById(R.id.editTextEmailLogin);
    mPassword = findViewById(R.id.editTextPasswordLogin);

    emailLayout = findViewById(R.id.editTextEmailLoginLay);
    passwordLayout = findViewById(R.id.editTextPasswordLoginLay);

    mEmail.addTextChangedListener(new MyTextWatcher(mEmail));
    mPassword.addTextChangedListener(new MyTextWatcher(mPassword));

    mLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (!validateEmail()) {
                return;
            }
            
            if (!validatePassword()) {
                return;
            }

            final String email = mEmail.getText().toString();
            final String password = mPassword.getText().toString();

            mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (!task.isSuccessful()) {
                        Toast.makeText(LoginActivity.this, "Sign in ERROR", Toast.LENGTH_LONG).show();
                    }
                }
            });
        }
    });
}