Firebase无法使用Android Studio存储自定义字段

时间:2019-01-03 14:09:46

标签: android firebase firebase-realtime-database

我正在尝试使用用户的名字在Firebase中存储自定义字段。我在firebase中使用实时数据库。当我单击注册时,它将电子邮件和密码存储到Firebase中,但不存储名字字段。我是Firebase的新手,我很确定自己在将应用程序连接到Firebase时安装了正确的依赖项。

我创建了一个 UserDetails.java 类来创建变量的构造函数,并使用以下方法将其存储到firebase:

已更新

package com.test.smartparkingsystem_cit;

public class UserDetails {
    public String firstname, lastname, email, password, phonenumber, vehiclenumber;


    public UserDetails(){

    }

    public UserDetails(String firstname, String lastname, String email, String password, String phonenumber, String vehiclenumber) {
        this.firstname = firstname;
        this.lastname = lastname;
        this.email = email;
        this.password = password;
        this.phonenumber = phonenumber;
        this.vehiclenumber = vehiclenumber;
    }
}

我非常确定我已经初始化了firebase实例,并使用以下代码将数据存储在firebase中:

mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
// call the constructor UserDetails.java and store user details to firebase
UserDetails user = new UserDetails(
        email,
        firstname
);

FirebaseDatabase.getInstance().getReference("Users")
       .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
       .setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
   @Override
   public void onComplete(@NonNull Task<Void> task) {
       progressBar.setVisibility(View.GONE);
       if(task.isSuccessful()) {
            Toast.makeText(register.this, getString(R.string.registration_success), Toast.LENGTH_LONG).show();
       }else {
           Toast.makeText(register.this, "Could not store to database.", Toast.LENGTH_SHORT).show();
       }
   }
});

}
else {
// Send Error message to application
Toast.makeText(register.this, "Some error occur, please check.", Toast.LENGTH_SHORT).show();
}
}
});

但是只有电子邮件和密码存储在数据库中,没有包括名字。有人可以帮忙吗?

这是我的 Register.java 中的以下代码:

package com.test.sample;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class register extends AppCompatActivity {

    private FirebaseAuth mAuth; // declare firebase authentication
    private Button back_btn; // create button config to open activity_register
    private Button register_btn; // create button config to register user
    ProgressBar progressBar; // declare progress bar after user registers

    // Declare variables for register
    EditText reg_email, reg_password, reg_fname;

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

        // Write a message to the database
        FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference myRef = database.getReference("message");

        myRef.setValue("Hello, World!");


        //Initialize variables according to ID
        reg_email = (EditText) findViewById(R.id.reg_email);
        reg_password = (EditText) findViewById(R.id.reg_password);
        reg_fname = (EditText) findViewById(R.id.reg_fname);

        progressBar = (ProgressBar) findViewById(R.id.progressBar);

        // Initialize Firebase Instance
        mAuth = FirebaseAuth.getInstance();

        // Register Button
        register_btn = (Button) findViewById(R.id.reg_confirmbtnreg); // register User
        register_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RegisterUser();
            }
        });
    }



    // Function Register User
    private void RegisterUser() {

        // Initialize variables and get text inputs
         final String email = reg_email.getText().toString().trim();
         final String password = reg_password.getText().toString().trim();
         final String firstname = reg_fname.getText().toString().trim();

        // ** Check Empty Fields Start **//
        // check if email is empty
        if(email.isEmpty()) {
            reg_email.setError("Email is required.");
            reg_email.requestFocus();
            return;
        }
        // check if password is empty
        if(password.isEmpty()) {
            reg_password.setError("Password is required.");
            reg_password.requestFocus();
            return;
        }
        // check if first name is empty
        if(firstname.isEmpty()) {
            reg_fname.setError("First Name is required.");
            reg_fname.requestFocus();
            return;
        }
        // ** Check Empty Fields End **//

        // check if email is valid
        if(!Patterns.EMAIL_ADDRESS.matcher(email).matches())
        {
            reg_email.setError("Please enter a valid email.");
            reg_email.requestFocus();
            return;
        }
        // check if password is minimum
        if(password.length()<5) {
            reg_password.setError("Minimum length of password should be 5.");
            reg_password.requestFocus();
            return;
        }
        // check if first name is minimum characters
        if(firstname.length()<1) {
            reg_fname.setError("First name should be 3-10 characters.");
            reg_fname.requestFocus();
            return;
        }

        // set visible progressbar once user clicks register button
        progressBar.setVisibility(View.VISIBLE);

        // Function to store data to firebase
        mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if(task.isSuccessful()) {
                    // call the constructor UserDetails.java and store user details to firebase
                    UserDetails user = new UserDetails(
                            email,
                            firstname
                    );

                   FirebaseDatabase.getInstance().getReference("Users")
                           .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
                           .setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
                       @Override
                       public void onComplete(@NonNull Task<Void> task) {
                           progressBar.setVisibility(View.GONE);
                           if(task.isSuccessful()) {
                                Toast.makeText(register.this, getString(R.string.registration_success), Toast.LENGTH_LONG).show();
                           }else {
                               Toast.makeText(register.this, "Could not store to database.", Toast.LENGTH_SHORT).show();
                           }
                       }
                   });

                }
                else {
                    // Send Error message to application
                    Toast.makeText(register.this, "Some error occur, please check.", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

在我的 build.grade 中,位于应用程序下。我已经安装了这些依赖项以连接Firebase和实时数据库。还有这个问题吗?请帮忙。谢谢

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    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'
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.google.firebase:firebase-core:16.0.1'
    implementation 'com.google.firebase:firebase-auth:16.0.1'
    implementation 'com.google.firebase:firebase-database:16.0.1'
}

1 个答案:

答案 0 :(得分:0)

要解决此问题,请更改以下代码行:

UserDetails user = new UserDetails(
    email,
    firstname
);

UserDetail suser = new UserDetails(
    firstname,
    lastname,
    email,
    password,
    phonenumber,
    vehiclenumber
);

通过这种方式,您正在通过将所有值传递给构造函数来构造UserDetails类的对象。在代码中,您只将两个值传递给不存在的两个参数的构造函数。