FirebaseAuth和FirebaseDatabase无法保存Google注册

时间:2019-07-09 17:22:26

标签: java android firebase firebase-realtime-database firebase-authentication

我有一个将createUserWithEmailAndPassword数据保存到实时数据库和身份验证数据库的系统。但是,在使用google登录创建类似系统后,什么也不会保存到数据库,什么也不会保存到Authentication数据库。

我尝试使用Log.e,我尝试调试该应用程序,还尝试解码该代码...

这里是一些代码:

package com.brandshopping.brandshopping;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.nfc.Tag;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.HashMap;

public class LoginOrSignupActivity extends AppCompatActivity {

    private Button LoginBtn, RegisterWithEmailBtn, RegisterWithGoogleBtn;
    private String Tag;
    private ProgressDialog LoadingBar;

    private FirebaseDatabase firebasedatabase = FirebaseDatabase.getInstance();
    private DatabaseReference database = firebasedatabase.getReference();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_or_signup);

        LoadinGUI();



        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();

        GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(this, gso); //Create Google sign in object


        LoginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(LoginOrSignupActivity.this, LogInActivity.class));
            }
        });

        RegisterWithEmailBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(LoginOrSignupActivity.this, RegisterActivity.class));
            }
        });

        RegisterWithGoogleBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                switch (v.getId()) {
                    case R.id.Register_WithGoogle_btn:
                        signIn();
                        break;
                }

           }
        });
    }

    private void signIn() {

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();

        GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(LoginOrSignupActivity.this, gso); //Create Google sign in object

        Intent signInIntent = mGoogleSignInClient.getSignInIntent();

        int RC_SIGN_IN = 100;

        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

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

        int RC_SIGN_IN = 100;

        // Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            // The Task returned from this call is always completed, no need to attach
            // a listener.
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            handleSignInResult(task);
        }
    }

    private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
        try {
            GoogleSignInAccount account = completedTask.getResult(ApiException.class);
            Toast.makeText(this, "Register/signin successful", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(LoginOrSignupActivity.this, AccountInfoActivity.class));




        } catch (ApiException e) {
            // The ApiException status code indicates the detailed failure reason.
            // Please refer to the GoogleSignInStatusCodes class reference for more information.
            Toast.makeText(this, "Log in failed", Toast.LENGTH_SHORT).show();
            Log.e(Tag, "error: ");
            startActivity(new Intent(LoginOrSignupActivity.this, AccountInfoActivity.class));

        }
    }

    void SaveToDataBase(){

        database.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                GoogleSignInAccount Guser = GoogleSignIn.getLastSignedInAccount(LoginOrSignupActivity.this);
                String EmailWithEtheraRemoved = Guser.getEmail().replace(".", " ");

                if(!(dataSnapshot.child("Users").child(EmailWithEtheraRemoved).exists())){
                    LoadingBar.setMessage("Please wait while we load the credentialls in");
                    LoadingBar.setTitle("Register");
                    LoadingBar.setCanceledOnTouchOutside(false);
                    LoadingBar.show();

                    HashMap<String, Object> Userdatamap = new HashMap<>();

                    Userdatamap
                            .put("Email", Guser.getEmail());

                    Userdatamap
                            .put("Phone number", "Google intigrated sign in does not allow phone number requesting... This will be fixed in later patches");

                    Userdatamap
                            .put("Name", Guser.getGivenName() + Guser.getFamilyName());

                    if(Guser != null){
                        Userdatamap
                                .put("Created with", "Intigrated Google sign in");
                    }

                    database
                            .child("Users")
                            .child(EmailWithEtheraRemoved)
                            .updateChildren(Userdatamap)
                            .addOnCompleteListener(new OnCompleteListener<Void>() {
                                @Override
                                public void onComplete(@NonNull Task<Void> task) {
                                    LoadingBar.dismiss();
                                    Toast.makeText(LoginOrSignupActivity.this, "Database save successful", Toast.LENGTH_SHORT).show();
                                    Log.e("SignUpError :", task
                                            .getException()
                                            .getMessage());


                                }
                            }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast.makeText(LoginOrSignupActivity.this, "Registration failed", Toast.LENGTH_SHORT).show();
                            Log.e(Tag, "error: ");
                        }
                    });

                }

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

    }

    void LoadinGUI(){

        LoginBtn = (Button) findViewById(R. id. Login_btn);
        RegisterWithEmailBtn = (Button) findViewById(R. id. Register_WithEmail_btn);
        RegisterWithGoogleBtn = (Button) findViewById(R. id. Register_WithGoogle_btn);

    }

}

我希望该应用程序将信息保存到实时数据库以及身份验证数据库中。其中的零点似乎正在起作用...

3 个答案:

答案 0 :(得分:1)

成功登录后,您忘记了致电SaveToDataBase。这就是为什么没有日志和数据库条目的原因。

答案 1 :(得分:1)

从Google Signin收到结果后,您将不会调用Firebase登录。

handleSignInResult中,您获得了Google登录的结果,您只需创建GoogleAuth凭据并将其用于signInwithCredentials

AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        // Sign in success, update UI with the signed-in user's information
                        Log.d(TAG, "signInWithCredential:success");
                        FirebaseUser user = mAuth.getCurrentUser();
                        saveUpdateUserProfile(user);
                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w(TAG, "signInWithCredential:failure", task.getException());
                        Snackbar.make(findViewById(R.id.main_layout), "Authentication Failed.", Snackbar.LENGTH_SHORT).show();

                    }
                }
            });

这将创建/登录Firebase用户,然后您可以检查数据库以查看用于登录的Google帐户是否是用于保存用户信息的新帐户。

P.S您还可以优化数据库查询。您当前的查询将从数据库获取所有用户。另外,您不应使用电子邮件地址作为数据库中的密钥。

使用Firebase用户ID作为键可以更有效地使用数据库结构:

users: {
 firebaaseUID1: {},
 firebaaseUID2: {},
 .
 .
}

您的SaveToDataBase现在可以是:

void SaveToDataBase(FirebaseUser用户,布尔值isGoogleSignIn){

database.getReference().child("Users").child(user.getUid())
    .addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                if (dataSnapshot.exists()){
                    // firebase user data is present in db, do appropiate action or take user to home screen
                }
                else {
                    LoadingBar.setMessage("Please wait while we load the credentialls in");
                    LoadingBar.setTitle("Register");
                    LoadingBar.setCanceledOnTouchOutside(false);
                    LoadingBar.show();
                    HashMap<String, Object> Userdatamap = new HashMap<>();

                    Userdatamap.put("Email", user.getEmail());

                    // Userdatamap
                    //         .put("phoneNumber", "Google intigrated sign in does not allow phone number requesting... This will be fixed in later patches");

                    Userdatamap.put("Name", user.getDisplayName());

                    if (isGoogleSignIn)
                        Userdatamap.put("Created with", "Intigrated Google sign in");

                    database
                            .child("Users")
                            .child(user.getUid())
                            .updateChildren(Userdatamap)
                            .addOnCompleteListener(new OnCompleteListener<Void>() {
                                @Override
                                public void onComplete(@NonNull Task<Void> task) {
                                    LoadingBar.dismiss();
                                    Toast.makeText(LoginOrSignupActivity.this, "Database save successful", Toast.LENGTH_SHORT).show();
                                    Log.e("SignUpError :", task
                                            .getException()
                                            .getMessage());
                                }
                            }).addOnFailureListener(new OnFailureListener() {
                                @Override
                                public void onFailure(@NonNull Exception e) {
                                    Toast.makeText(LoginOrSignupActivity.this, "Registration failed", Toast.LENGTH_SHORT).show();
                                    Log.e(Tag, "error: ");
                                }
                            });
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {}
        });

    }
}

答案 2 :(得分:1)

我正在考虑您是否已经将Firebase添加到项目中,请点击此链接https://firebase.google.com/docs/auth/android/google-signin

然后,您必须在Firebase中启用Google登录,方法是从左侧面板中选择身份验证,然后选择登录提供者标签并启用Google登录。

您的项目级构建脚本应如下所示

buildscript {
repositories {
    google()
    jcenter()

}
dependencies {
    classpath 'com.android.tools.build:gradle:3.4.1'

    classpath 'com.google.gms:google-services:4.2.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    google()
    jcenter()

}
}

task clean(type: Delete) {
delete rootProject.buildDir
}

并且应用程序级别的build.gradle文件应该具有这些依赖项

//firebasecore
implementation 'com.google.firebase:firebase-core:17.0.0'
//firebase auth
implementation 'com.google.firebase:firebase-auth:18.0.0'
//google auth
implementation 'com.google.android.gms:play-services-auth:17.0.0'

并且登录名应具有以下代码

public class Login_Activity extends AppCompatActivity {


ImageView gLogin;
private static final int RC_SIGN_IN=1;
private FirebaseAuth mAuth;
GoogleSignInClient mGoogleSignInClient;
Firebase user;

@Override
protected void onStart() {
    super.onStart();

 user = mAuth.getCurrentUser();
    if(user!=null)
    {
        startActivity(new Intent(Login_Activity.this,MainActivity.class));
        Login_Activity.this.finish();

    }

}



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login_);

    gLogin=findViewById(R.id.gLogin);

    // ...
// Initialize Firebase Auth
    mAuth = FirebaseAuth.getInstance();

    // Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
    GoogleSignInOptions gso = new 
 GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build();

    // Build a GoogleSignInClient with the options specified by gso.
    mGoogleSignInClient= GoogleSignIn.getClient(this, gso);



    gLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            signIn();
        }
    });


}


private void signIn() {
    Intent signInIntent = mGoogleSignInClient.getSignInIntent();
    startActivityForResult(signInIntent, RC_SIGN_IN);
 Toast.makeText(this, "starting activity", Toast.LENGTH_SHORT).show();
}


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

    // Result returned from launching the Intent from 
GoogleSignInClient.getSignInIntent(...);
    if (requestCode == RC_SIGN_IN) {
// The Task returned from this call is always completed, no need to 
   //attach
        // a listener.
 Task<GoogleSignInAccount> task = 
 GoogleSignIn.getSignedInAccountFromIntent(data);
    Toast.makeText(this, "inside on Activity result", 
 Toast.LENGTH_SHORT).show();

        try {
   Toast.makeText(this, "authenticating", Toast.LENGTH_SHORT).show();

// Google Sign In was successful, authenticate with Firebase
    GoogleSignInAccount account = task.getResult(ApiException.class);
            firebaseAuthWithGoogle(account);
        } catch (ApiException e) {
            // Google Sign In failed, update UI appropriately
            Log.w("firebase exception", "Google sign in failed", e);
            // ...
        }
        //handleSignInResult(task);
    }
}

private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    Log.d("authenticate", "firebaseAuthWithGoogle:" + acct.getId());

    AuthCredential credential = 
GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() 
{
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) 
                {
                    if (task.isSuccessful()) {
  // Sign in success, update UI with the signed-in user's information

  Log.d("message","signInWithCredential:success");
                        user = mAuth.getCurrentUser();
                        Log.d("user id", user.getUid());
                        startActivity(new 
Intent(Login_Activity.this,MainActivity.class));
                        Login_Activity.this.finish();

                    } else {
              // If sign in fails, display a message to the user.
                        Log.w("message","signInWithCredential:failure", task.getException());

                    }
                }
            });
}

您需要使用带有Google登录名的requestId令牌进行登录,您可以使用此代码,它将使用google登录名登录到Firebase经过身份验证的用户数据库中。

对于数据库,您应该一次检查数据库规则的读写权限,并且该规则应该有效