Вход в Google не работает в Android с использованием Firebase - PullRequest
0 голосов
/ 10 марта 2019

Где я здесь не так?Я также отлаживал программу, она сразу переходила на Snackbar, который называется «Авторизация не пройдена».Он избегает

if (task.isSuccessful ())

и прыгает прямо на оператор Snackbar.

Snackbar snackbar = Snackbar.make (ordinatorLayoutLogin, «Ошибка авторизации!», Snackbar.LONG) snakbar.show ();

Что мне делать?Где я не прав?

Код:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        FirebaseApp.initializeApp(this);
        //-------------Firebase Initialization----------------
        InitializeComponents();
        mAuth = FirebaseAuth.getInstance();
        //----------------------------------------------------


        //-------------OnclickListeners-----------------------
        btnLogin.setOnClickListener(LoginActivity.this);
        textViewRegister.setOnClickListener(LoginActivity.this);
        textViewForgetPassword.setOnClickListener(this);
        btnGoogleSignIn.setOnClickListener(this);
        //----------------------------------------------------


        mAuthListener = new FirebaseAuth.AuthStateListener()
        {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                if (firebaseAuth.getCurrentUser() != null)
                {
                    startActivity(new Intent(LoginActivity.this,HomeActivity.class));
                }
                else
                {

                }
            }
        };

        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, new GoogleApiClient.OnConnectionFailedListener() {
                    @Override
                    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
                        Snackbar snackbar =  Snackbar.make(coordinatorLayoutLogin,"Google Sign In Failed !",Snackbar.LENGTH_LONG);
                        snackbar.show();
                    }
                })
                .addApi(Auth.GOOGLE_SIGN_IN_API,gso)
                .build();

    }
    private void signIn()
    {
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent,RC_SIGN_IN);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RC_SIGN_IN)
        {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            if (result.isSuccess())
            {
                GoogleSignInAccount account = result.getSignInAccount();
                firebaseAuthWithGoogle(account);
            }
            else
            {
                Snackbar snackbar = Snackbar.make(coordinatorLayoutLogin,"Authorization Failed !",Snackbar.LENGTH_LONG);
                snackbar.show();
            }
        }
    }

    private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
        AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(),null);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful())
                        {
                            FirebaseUser user = mAuth.getCurrentUser();
                            //updateUI(user);
                        }
                        else
                        {
                            Snackbar snackbar = Snackbar.make(coordinatorLayoutLogin,"Authentication Failed !",Snackbar.LENGTH_LONG);
                            snackbar.show();
                            //updateUI(null);
                        }
                    }
                });
    }

    private void InitializeComponents() {
        textInputLayoutEmail = findViewById(R.id.tiEmail);
        textInputLayoutPassword = findViewById(R.id.tiPassword);
        btnLogin = findViewById(R.id.btnLogin);
        textViewRegister = findViewById(R.id.tvRegister);
        textViewForgetPassword = findViewById(R.id.tvForgetPassword);
        progressDialogLogin = new ProgressDialog(this);
        coordinatorLayoutLogin = findViewById(R.id.coordinatorLayoutLogin);
        btnGoogleSignIn = findViewById(R.id.btnGoogleSignIn);
    }

    @Override
    protected void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }

    @Override
    public void onClick(View v) {
        if (v == btnLogin) {
            if (CheckEmailField() == true && CheckPasswordField() == true)
            {
                progressDialogLogin.setMessage("Please wait while your logging in ....");
                progressDialogLogin.show();
                progressDialogLogin.setCancelable(false);

                final String email,password;
                email = textInputLayoutEmail.getEditText().getText().toString().trim();
                password = textInputLayoutPassword.getEditText().getText().toString();
                mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful())
                        {
                            progressDialogLogin.dismiss();
                            Toast.makeText(LoginActivity.this, "Welcome "+email+"", Toast.LENGTH_SHORT).show();
                            startActivity(new Intent(LoginActivity.this,HomeActivity.class));
                            finish();
                        }
                        else
                        {
                            progressDialogLogin.dismiss();
                            Snackbar snackbar = Snackbar.make(coordinatorLayoutLogin,"Invalid Email or Password !",Snackbar.LENGTH_LONG);
                            snackbar.show();
                        }
                    }
                });
            }
        } else if (v == textViewRegister) {
            startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
            finish();
        } else if (v == textViewForgetPassword) {
            startActivity(new Intent(LoginActivity.this, ForgetPassword.class));
            finish();
        }
        else if (v == btnGoogleSignIn)
        {
            signIn();
        }
    }

    private boolean CheckEmailField() {
        String email = textInputLayoutEmail.getEditText().getText().toString().trim();
        if (email.isEmpty()) {
            textInputLayoutEmail.setError("Enter email !");
            return false;
        } else if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            textInputLayoutEmail.setError("Invalid Email Address !");
            return false;
        } else {
            textInputLayoutEmail.setError(null);
            textInputLayoutEmail.setErrorEnabled(false);
            return true;
        }
    }

    private boolean CheckPasswordField() {
        String password = textInputLayoutPassword.getEditText().getText().toString();
        if (password.isEmpty()) {
            textInputLayoutPassword.setError("Enter Password !");
            return false;
        } else if (password.length() < 8) {
            textInputLayoutPassword.setError("Minimum of 8 character of password required !");
            return false;
        } else {
            textInputLayoutPassword.setError(null);
            textInputLayoutPassword.setErrorEnabled(false);
            return true;
        }
    }
}
...