首页 > 解决方案 > Firebase 实时数据库未显示在控制台中

问题描述

我正在尝试从电子邮件/密码验证的 Firebase Auth 获取用户 ID,但它没有显示在 Firebase 数据库中。

这是我的 DriverLogin.class 代码:

public class DriverLogin extends AppCompatActivity {

    private static final String TAG = "EmailPassword";

    private EditText mEmail;
    private EditText mPass;

    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener firebaseAuthListener;


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

        mAuth = FirebaseAuth.getInstance();
        firebaseAuthListener= new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
                if(user != null){
                    Intent intent = new Intent(DriverLogin.this,DriverMain.class);
                    startActivity(intent);
                    finish();
                    return;
                }
            }
        };

        //editText
        mEmail = findViewById(R.id.DriverEmail);
        mPass = findViewById(R.id.DriverPass);
        //Btn

        findViewById(R.id.DriverSign).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signUp(mEmail.getText().toString(), mPass.getText().toString());
            }
        });

        findViewById(R.id.DriverLogbtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signIn(mEmail.getText().toString(), mPass.getText().toString());
            }
        });

    }


    //CreateAccount with Email and Password
    private void signUp(final String email, final String password) {
        Log.d(TAG, "CreateAccount:" + email);
        if (!validateForm()) {
            return;
        }

        mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()) {
                    Log.d(TAG, "createUserWithEmail:success");
                    Toast.makeText(DriverLogin.this, "Registered Successfully",
                            Toast.LENGTH_SHORT).show();
                } else {
                    String user_id = mAuth.getCurrentUser().getUid();
                    DatabaseReference driverDb = FirebaseDatabase.getInstance().getReference().child("Users").child("Driver").child(user_id);
                    driverDb.setValue(true);
                    Toast.makeText(DriverLogin.this, "Something went wrong",
                            Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    //---------------------------------------------LOGIN------------------------------------//
    //Login Existing Account
    private void signIn(final String email, final String pass) {
        Log.d(TAG, "CreateAccount:" + email);
        if (!validateForm()) {
            return;
        }

        mAuth.signInWithEmailAndPassword(email, pass).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {


                            Log.d(TAG, "signInWithEmail:success");

                            FirebaseUser user = mAuth.getCurrentUser();
                            Toast.makeText(DriverLogin.this, "Logged in Successfully", Toast.LENGTH_SHORT).show();


                        } else {

                            // If sign in fails, display a message to the user.

                            Log.w(TAG, "signInWithEmail:failure", task.getException());

                            Toast.makeText(DriverLogin.this, "Authentication failed.",

                                    Toast.LENGTH_SHORT).show();
                        }
                        // [END_EXCLUDE]
                    }
                }
        );
    }


    @Override
        protected void onStart() {
            super.onStart();
            mAuth.addAuthStateListener(firebaseAuthListener);
    }
    @Override
    protected void onStop() {
        super.onStop();
        mAuth.removeAuthStateListener(firebaseAuthListener);
    }

    //textfield validations
    private boolean validateForm() {

        boolean valid = true;


        String email = mEmail.getText().toString();

        if (TextUtils.isEmpty(email)) {

            mEmail.setError("Required.");

            valid = false;

        } else {

            mEmail.setError(null);

        }


        String password = mPass.getText().toString();

        if (TextUtils.isEmpty(password)) {

            mPass.setError("Required.");

            valid = false;

        } else {

            mPass.setError(null);

        }
        return valid;

    }


}

没有弹出错误,但我无法在 firebase 数据库中写入数据。

我已经启用了电子邮件/密码身份验证,我的规则是:

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

和我的 build.gradle:app

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.0'
    implementation 'com.google.firebase:firebase-core:15.0.2'
    implementation 'com.google.firebase:firebase-database:15.0.0'
    implementation 'com.google.firebase:firebase-auth:15.1.0'
    implementation 'com.google.android.gms:play-services-auth:15.0.1'
    implementation 'com.github.bumptech.glide:glide:4.7.1'
    implementation 'com.android.support:design:27.1.1'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.7.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

apply plugin: 'com.google.gms.google-services'

标签: androidfirebase-realtime-databasefirebase-authentication

解决方案


尝试将写入操作移动到成功块中。

   mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
    @Override
    public void onComplete(@NonNull Task<AuthResult> task) {
        if (task.isSuccessful()) {
            Log.d(TAG, "createUserWithEmail:success");
            String user_id = mAuth.getCurrentUser().getUid();
            DatabaseReference driverDb = FirebaseDatabase.getInstance().getReference().child("Users").child("Driver").child(user_id);
            driverDb.setValue(true);
            Toast.makeText(DriverLogin.this, "Registered Successfully",
                    Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(DriverLogin.this, "Something went wrong",
                    Toast.LENGTH_SHORT).show();
        }
    }
});

推荐阅读