База данных аутентификации firebase не сохраняется - PullRequest
0 голосов
/ 10 июля 2019

У меня есть система, которая сохраняет данные createUserWithEmailAndPassword в базу данных в реальном времени и в базу данных аутентификации. Но после создания аналогичной системы с использованием входа в Google вместо этого ничего не сохранится в базе данных аутентификации, приложение просто аварийно завершает работу с моим текущим кодом.

я пытался использовать 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.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
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));
            FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

            firebaseAuthWithGoogle(account);


        } 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) {

            }
        });

    }

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

        final FirebaseAuth mAuth = FirebaseAuth.getInstance();
        final GoogleSignInAccount Guser = GoogleSignIn.getLastSignedInAccount(LoginOrSignupActivity.this);

        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");
                            Log.d("user id", Guser.getId());
                            startActivity(new
                                    Intent(LoginOrSignupActivity.this,MainActivity.class));

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

                        }
                    }
                });
    }

    void LoadinGUI() {

        LoadingBar = new ProgressDialog(LoginOrSignupActivity.this);
        LoginBtn = (Button) findViewById(R.id.Login_btn);
        RegisterWithEmailBtn = (Button) findViewById(R.id.Register_WithEmail_btn);
        RegisterWithGoogleBtn = (Button) findViewById(R.id.Register_WithGoogle_btn);

    }
}

Я ожидаю, что приложение сохранит информацию в базе данных аутентификации.

это файл отладки:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.brandshopping.brandshopping, PID: 30495
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=100, result=-1, data=Intent { (has extras) }} to activity {com.brandshopping.brandshopping/com.brandshopping.brandshopping.LoginOrSignupActivity}: java.lang.IllegalArgumentException: Must specify an idToken or an accessToken.
    at android.app.ActivityThread.deliverResults(ActivityThread.java:4936)
    at android.app.ActivityThread.handleSendResult(ActivityThread.java:4978)
    at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:49)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2123)
    at android.os.Handler.dispatchMessage(Handler.java:109)
    at android.os.Looper.loop(Looper.java:207)
    at android.app.ActivityThread.main(ActivityThread.java:7470)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:958)
 Caused by: java.lang.IllegalArgumentException: Must specify an idToken or an accessToken.
    at com.google.firebase.auth.GoogleAuthCredential.<init>(Unknown Source:3)
    at com.google.firebase.auth.GoogleAuthProvider.getCredential(Unknown Source:2)
    at com.brandshopping.brandshopping.LoginOrSignupActivity.firebaseAuthWithGoogle(LoginOrSignupActivity.java:213)
    at com.brandshopping.brandshopping.LoginOrSignupActivity.handleSignInResult(LoginOrSignupActivity.java:127)
    at com.brandshopping.brandshopping.LoginOrSignupActivity.onActivityResult(LoginOrSignupActivity.java:116)
    at android.app.Activity.dispatchActivityResult(Activity.java:7775)
    at android.app.ActivityThread.deliverResults(ActivityThread.java:4929)
    at android.app.ActivityThread.handleSendResult(ActivityThread.java:4978) 
    at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:49) 
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2123) 
    at android.os.Handler.dispatchMessage(Handler.java:109) 
    at android.os.Looper.loop(Looper.java:207) 
    at android.app.ActivityThread.main(ActivityThread.java:7470) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:958) 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...