Firebase :我在使用 Google 登录时遇到了麻烦 [英] Firebase : I get in trouble when I sign in with Google

查看:37
本文介绍了Firebase :我在使用 Google 登录时遇到了麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 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);
    }

}

推荐答案

您似乎在配置 Firebase 时没有指定实时数据库的 URL.发生这种情况的原因有几个:

It looks like you're configuring Firebase without specifying the URL of the Realtime Database. There are a few reasons this could be happening:

  1. 如果您在代码中提供配置数据,请务必调用 setDatabaseUrl 关于您的选项.

  1. If you are providing the configuration data in code, be sure to call setDatabaseUrl on your options.

当您的数据库实例托管在其他地区而不是(默认)美国地区时,这种情况尤其可能发生.

This is especially likely when your database instance is hosted in another region than the (default) US one.

如果您通过 GoogleServices.json 文件提供配置数据,请确保在之后下载该文件的新版本在Firebase 控制台.

If you are providing the configuration data through the GoogleServices.json file, be sure to download a new version of that file after you create the database in the Firebase console.

这是一项新要求(从几周前开始),因为实时数据库现在是按需创建的(而不是在创建项目时自动创建),因此您可以选择创建的区域.

This is a new requirement (since a few weeks ago) as the Realtime Database is now created on-demand (instead of auto-created when the project is created), so that you can pick in what region it's created.

这篇关于Firebase :我在使用 Google 登录时遇到了麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆