Firebase数据库问题 - 无法正确写入数据库

时间:2018-04-18 03:44:54

标签: android firebase firebase-realtime-database

我希望用户使用Google登录,然后将他们的信息写入我的Firebase数据库。然后,如果此用户退出,然后使用其他Google帐户重新登录,则此信息将作为新条目写入同一Firebase数据库。目前的问题是,在将条目写入数据库之前,用户需要注销然后返回两次,然后覆盖(而不是作为新条目添加)。

MainActivity.class

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.SyncStateContract;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

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.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
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.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;


class MainActivity extends BaseActivity implements
        View.OnClickListener {

    private static final String TAG = "GoogleActivity";
    private static final String LOG_TAG = "Logs";
    private static final int RC_SIGN_IN = 9001;

    FirebaseUser currentUser;
    User user;

    // [START declare_auth]
    private FirebaseAuth mAuth;
    // [END declare_auth]

    private GoogleSignInClient mGoogleSignInClient;
    private TextView mStatusTextView;
    private TextView mDetailTextView;
    private TextView mDetailTextViewTwo;

    DatabaseReference myRef;

    FirebaseDatabase database;


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

//        mDatabase = FirebaseDatabase.getInstance().getReference();


//        mUsersReference = mTheReference.child("Users").child(userId);


        //hide action bar
//        getSupportActionBar().hide();
        getSupportActionBar().setElevation(0);







        // Views
        mStatusTextView = findViewById(R.id.status);
        mDetailTextView = findViewById(R.id.detail);
        mDetailTextViewTwo = findViewById(R.id.detail_two);

        // Button listeners
        findViewById(R.id.sign_in_button).setOnClickListener(this);
        findViewById(R.id.sign_out_button).setOnClickListener(this);
        findViewById(R.id.disconnect_button).setOnClickListener(this);



        String url = "https://mydbstring";
        DatabaseReference ref = FirebaseDatabase.getInstance().getReferenceFromUrl(url);




        // [START config_signin]
        // Configure Google Sign In
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();
        // [END config_signin]

        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

        // [START initialize_auth]
        mAuth = FirebaseAuth.getInstance();
        // [END initialize_auth]
    }

    // [START on_start_check_user]
    @Override
    public void onStart() {
        super.onStart();
        // Check if user is signed in (non-null) and update UI accordingly.
        currentUser = mAuth.getCurrentUser();


        updateUI(currentUser);





    }
    // [END on_start_check_user]

    // [START onactivityresult]
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            try {
                // Google Sign In was successful, authenticate with Firebase
                GoogleSignInAccount account = task.getResult(ApiException.class);
                firebaseAuthWithGoogle(account);

                if(currentUser != null){
                    writeToDb(currentUser.getDisplayName(), currentUser.getEmail(),currentUser.getPhoneNumber(), currentUser.getProviderId(), currentUser.getUid(),currentUser.getPhotoUrl().toString());
                    loadSecondActivity();

                }



            } catch (ApiException e) {
                // Google Sign In failed, update UI appropriately
                Log.w(TAG, "Google sign in failed", e);
                // [START_EXCLUDE]
                updateUI(null);
                // [END_EXCLUDE]
            }
        }
    }
    // [END onactivityresult]

    // [START auth_with_google]
    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
        // [START_EXCLUDE silent]
        showProgressDialog();
        // [END_EXCLUDE]

        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");
                            currentUser = mAuth.getCurrentUser();
                            updateUI(currentUser);
                        } 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();
                            updateUI(null);
                        }

                        // [START_EXCLUDE]
                        hideProgressDialog();
                        // [END_EXCLUDE]
                    }
                });
    }
    // [END auth_with_google]

    // [START signin]
    private void signIn() {
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();




        startActivityForResult(signInIntent, RC_SIGN_IN);
        Log.d(LOG_TAG, "sign in completed");
//


    }
    // [END signin]

    private void signOut() {
        // Firebase sign out
        mAuth.signOut();

        // Google sign out
        mGoogleSignInClient.signOut().addOnCompleteListener(this,
                new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        updateUI(null);
                    }
                });

        FirebaseAuth.getInstance().signOut();

        database = null;
        myRef = null;
    }

    private void revokeAccess() {
        // Firebase sign out
        mAuth.signOut();

        // Google revoke access
        mGoogleSignInClient.revokeAccess().addOnCompleteListener(this,
                new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        updateUI(null);
                    }
                });

//        database = null;
//        myRef = null;
    }

    private void updateUI(FirebaseUser user) {
        hideProgressDialog();
        if (user != null) {
            mStatusTextView.setText(getString(R.string.google_status_fmt, user.getEmail()));
            mDetailTextView.setText(getString(R.string.firebase_status_fmt, user.getUid()));
            mDetailTextViewTwo.setText(user.getDisplayName());

            findViewById(R.id.sign_in_button).setVisibility(View.GONE);
            findViewById(R.id.sign_out_and_disconnect).setVisibility(View.VISIBLE);


        } else {
            mStatusTextView.setText(R.string.signed_out);
            mDetailTextView.setText(null);

            findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
            findViewById(R.id.sign_out_and_disconnect).setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.sign_in_button) {
            signIn();
        } else if (i == R.id.sign_out_button) {
            signOut();
        } else if (i == R.id.disconnect_button) {
            revokeAccess();
        }
    }


    public void writeToDb(String displayName, String email, String phoneNumber, String providerId, String uId, String photoUrl){




        database = FirebaseDatabase.getInstance();
        myRef = database.getReference("Users");

        User user = new User(displayName, email, phoneNumber, providerId, uId, photoUrl);
        myRef.child("Name").setValue(user.getDisplayName());
        myRef.child("Email").setValue(user.getEmail());
        myRef.child("Phonenumber").setValue(user.getPhoneNumber());
        myRef.child("ProviderId").setValue(user.getProviderId());
        myRef.child("uId").setValue(user.getuId());
        myRef.child("photoUrl").setValue(user.getPhotoUrl().toString());
}



    public void loadSecondActivity(){
        Intent myIntent = new Intent(MainActivity.this, SecondActivity.class);
        MainActivity.this.startActivity(myIntent);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }





}

User.class

import android.net.Uri;

public class User {

    private String displayName;
    private String email;
    private String phoneNumber;
    private  String providerId;
    private String uId;
    private String photoUrl;

    public User(){

    }

    public User(String displayName, String email, String phoneNumber, String providerId, String uId, String photoUrl) {
        this.displayName = displayName;
        this.email = email;
        this.phoneNumber = phoneNumber;
        this.providerId = providerId;
        this.uId = uId;
        this.photoUrl = photoUrl;
    }

    public String getDisplayName() {
        return displayName;
    }

    public String getEmail() {
        return email;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public String getProviderId() {
        return providerId;
    }

    public String getuId() {
        return uId;
    }

    public String getPhotoUrl() {
        return photoUrl;
    }

    public void setDisplayName(String displayName) {
        this.displayName = displayName;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public void setProviderId(String providerId) {
        this.providerId = providerId;
    }

    public void setuId(String uId) {
        this.uId = uId;
    }

    public void setPhotoUrl(String photoUrl) {
        this.photoUrl = photoUrl;
    }
}

2 个答案:

答案 0 :(得分:1)

而不是

myRef.child("Name").setValue(user.getDisplayName()); myRef.child("Email").setValue(user.getEmail()); myRef.child("Phonenumber").setValue(user.getPhoneNumber()); myRef.child("ProviderId").setValue(user.getProviderId()); myRef.child("uId").setValue(user.getuId()); myRef.child("photoUrl").setValue(user.getPhotoUrl().toString());

使用:

myRef.push().setValue(user);

每次插入新用户数据时,Push都会生成唯一键

答案 1 :(得分:1)

使用此行。

myRef.push().setValue(user);

这对你有用。感谢