Firebase : I get in trouble when I sign in with Google

匆匆过客 提交于 2020-12-26 11:09:09

问题


I have this mistake when I log in with 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)

enter image description here

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

}

回答1:


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. If you are providing the configuration data in code, be sure to call setDatabaseUrl on your options.

  2. 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.




回答2:


Seems like you didn't connect your app to firebase. You should:

  • connect your app to firebase
  • add Firebase Authentication to your project

You are also using Firebase Database. Connect it to your project.

After all, change this code

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

to this:

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

To conclude, as Frank mentioned, do not forget to download your google-services.json file and add it into the module (app-level) directory of your app



来源:https://stackoverflow.com/questions/65348685/firebase-i-get-in-trouble-when-i-sign-in-with-google

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!