firebase:当我登录google时遇到了麻烦

amrnrhlw  于 2021-06-29  发布在  Java
关注(0)|答案(2)|浏览(358)

当我用google登录时,我犯了这个错误

com.google.firebase.database.DatabaseException: Failed to get FirebaseDatabase instance: Specify DatabaseURL within FirebaseApp or from your getInstance() call.
        at com.google.firebase.database.FirebaseDatabase.getInstance(com.google.firebase:firebase-database@@16.0.5:114)
        at com.google.firebase.database.FirebaseDatabase.getInstance(com.google.firebase:firebase-database@@16.0.5:71)
        at pl.cyfrogen.budget.ui.signin.SignInActivity.updateUI(SignInActivity.java:145)
        at pl.cyfrogen.budget.ui.signin.SignInActivity.access$400(SignInActivity.java:41)
        at pl.cyfrogen.budget.ui.signin.SignInActivity$3.onComplete(SignInActivity.java:130)
        at com.google.android.gms.tasks.zzj.run(Unknown Source:4)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:237)
        at android.app.ActivityThread.main(ActivityThread.java:8167)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:496)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)

在此处输入图像描述

public class SignInActivity extends AppCompatActivity {
    private static final int RC_SIGN_IN = 123;
    private FirebaseAuth mAuth;
    private GoogleSignInClient mGoogleSignInClient;
    private TextView errorTextView;
    private SignInButton signInButton;
    private View progressView;
    private TextView privacyPolicyTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signin);
        progressView = findViewById(R.id.progress_view);
        mAuth = FirebaseAuth.getInstance();
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();
        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

        signInButton = findViewById(R.id.sign_in_button);
        signInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signIn();
                signInButton.setEnabled(false);
                errorTextView.setText("");
            }
        });

        privacyPolicyTextView = findViewById(R.id.privacy_policy_text_view);
        SpannableStringBuilder spanTxt = new SpannableStringBuilder(
                "By signing in, you are indicating that you have read and agree to the ");
        spanTxt.append("privacy policy");
        spanTxt.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                Intent browserIntent = new Intent(Intent.ACTION_VIEW,
                        Uri.parse(Links.PRIVACY_POLICY_LINK));
                startActivity(browserIntent);
            }
        }, spanTxt.length() - "privacy policy".length(), spanTxt.length(), 0);
        privacyPolicyTextView.setMovementMethod(LinkMovementMethod.getInstance());
        privacyPolicyTextView.setText(spanTxt, TextView.BufferType.SPANNABLE);

        errorTextView = findViewById(R.id.error_textview);
    }

    @Override
    public void onStart() {
        super.onStart();
        showProgressView();
        FirebaseUser currentUser = mAuth.getCurrentUser();
        updateUI(currentUser);
    }

    private void signIn() {
        showProgressView();
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RC_SIGN_IN) {
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            try {
                GoogleSignInAccount account = task.getResult(ApiException.class);
                firebaseAuthWithGoogle(account);
            } catch (ApiException e) {
                e.printStackTrace();
                hideProgressView();
                loginError("Google sign in failed.");

            }
        }
    }

    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        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()) {
                            FirebaseUser user = mAuth.getCurrentUser();
                            updateUI(user);
                        } else {
                            loginError("Firebase auth failed.");
                            hideProgressView();
                        }
                    }
                });
    }

    private void updateUI(FirebaseUser currentUser) {
        if (currentUser == null) {
            progressView.setVisibility(View.GONE);
            return;
        }
        showProgressView();
        final DatabaseReference userReference = FirebaseDatabase.getInstance().getReference("users").child(currentUser.getUid());
        userReference.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                User user = dataSnapshot.getValue(User.class);
                if (user != null) {
                    startActivity(new Intent(SignInActivity.this, MainActivity.class));
                    finish();
                } else {
                    runTransaction(userReference);
                }

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                loginError("Firebase fetch user data failed.");
                hideProgressView();
            }
        });

    }

    private void loginError(String text) {
        errorTextView.setText(text);
        signInButton.setEnabled(true);
    }

    private void runTransaction(DatabaseReference userReference) {
        showProgressView();
        userReference.runTransaction(new Transaction.Handler() {
            @Override
            public Transaction.Result doTransaction(MutableData mutableData) {
                User user = mutableData.getValue(User.class);
                if (user == null) {
                    mutableData.setValue(new User());
                    return Transaction.success(mutableData);
                }

                return Transaction.success(mutableData);
            }

            @Override
            public void onComplete(DatabaseError databaseError, boolean committed,
                                   DataSnapshot dataSnapshot) {
                if (committed) {
                    startActivity(new Intent(SignInActivity.this, MainActivity.class));
                    finish();
                } else {
                    errorTextView.setText("Firebase create user transaction failed.");
                    hideProgressView();
                }
            }
        });
    }

    private void showProgressView() {
        progressView.setVisibility(View.VISIBLE);

    }

    private void hideProgressView() {
        progressView.setVisibility(View.GONE);

    }

    @Override
    public void onBackPressed() {
        moveTaskToBack(true);
    }

}
yh2wf1be

yh2wf1be1#

似乎你没有将你的应用程序连接到firebase。你应该:
将你的应用程序连接到firebase
向项目添加firebase身份验证
您也在使用firebase数据库。将其连接到您的项目。
毕竟,改变这个代码

final DatabaseReference userReference = FirebaseDatabase.getInstance().getReference("users").child(currentUser.getUid());

对此:

final DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
final DatabaseReference userReference = rootRef.child("users").child(currentUser.getUid());

最后,正如frank提到的,不要忘记下载google-services.json文件并将其添加到应用程序的module(app-level)目录中

uurity8g

uurity8g2#

看起来您正在配置firebase,但没有指定实时数据库的url。可能发生这种情况的原因有:
如果您是在代码中提供配置数据,请务必调用 setDatabaseUrl 你的选择。
如果您是通过 GoogleServices.json 文件,请确保在firebase控制台中创建数据库后下载该文件的新版本。
这是一个新的要求(从几周前开始),因为实时数据库现在是按需创建的(而不是在创建项目时自动创建),所以您可以选择在哪个区域创建它。

相关问题