Firebase - 使用push()时无法获取值

时间:2018-01-04 21:38:44

标签: java android firebase-realtime-database nullpointerexception key

问题:

我正在尝试将员工添加到Firebase中的UnverifiedEmployee节点,以便潜在用户可以稍后进入并注册信息是否匹配。它在单个实例中工作,但如果雇主连续添加两个雇员,则第一个被覆盖。

到目前为止我尝试做的是:

我想我需要另一个子节点,每次添加新的UnverifiedEmployee时都会迭代。但是我不确定如何检查之前的#"数字"是。我可以获得键值对的值,但不能获得此子节点键的值。

我还尝试了什么:

所以当我查看文档时,它提到了push()方法。这分为子键,但它为每个键创建一个单独的值,并且在以后查找时也很难引用:

使用push()方法后的数据库: Updated DB

(请注意,它目前使用" num&#34进行了硬编码;这显然不是动态的或可扩展的。我似乎无法在文档中找到它如何获取密钥子子节点。

没有推送的Firebase数据库并手动设置员工编号

Unverified Employee with subnode

AddEmployeeActivity.java

public class AddEmployeeActivity extends Activity {

    private EditText firstNameET, lastNameET, phoneNumberET, emailET, ssnET;
    private ImageView checkmarkImage;

    private static FirebaseUser currentUser;
    private static final String TAG = "RealtimeDB";
    private FirebaseDatabase database;
    private DatabaseReference dbRef;
    Intent emailIntent;

    int num;


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

        firstNameET = (EditText) findViewById(R.id.firstNameET);
        lastNameET = (EditText) findViewById(R.id.lastNameET);
        phoneNumberET = (EditText) findViewById(R.id.phoneNumberET);
        emailET = (EditText) findViewById(R.id.emailET);
        ssnET = (EditText) findViewById(R.id.ssnET);

        checkmarkImage = (ImageView) findViewById(R.id.checkmarkImage);

        //STEPS
        //1A) New Unverified employee node
        //1B) Send email to user

        database = FirebaseDatabase.getInstance();
        dbRef = database.getReference("/Unverified Employees");
        currentUser =
                FirebaseAuth.getInstance().getCurrentUser();

        checkmarkImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                final String email = emailET.getText().toString().trim();
                final String ssn = ssnET.getText().toString().trim();


                //CHECK TO MAKE SURE THEY ENTER INFORMATION FOR EMAIL AND SSN
                if (TextUtils.isEmpty(email)) {
                    Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (TextUtils.isEmpty(ssn)) {
                    Toast.makeText(getApplicationContext(), "Enter Social Security Number!", Toast.LENGTH_SHORT).show();
                    return;
                }

                //SEND INFORMATION TO FIREBASE DATABASE
                num = 1;
                String numString = String.valueOf(num);
                dbRef.child(currentUser.getUid()).child(numString).setValue(num, completionListener);
                dbRef.child(currentUser.getUid()).child(numString).child("emailAddress").setValue(emailET.getText().toString(), completionListener);                        


            }
        });

    } //End of ONCREATE

    DatabaseReference.CompletionListener completionListener =
            new DatabaseReference.CompletionListener() {
                @Override
                public void onComplete(DatabaseError databaseError,
                                       DatabaseReference databaseReference) {

                    if (databaseError != null) {
                        notifyUser(databaseError.getMessage());
                    }
                }
            };

    private void notifyUser(String message) {
        Toast.makeText(AddEmployeeActivity.this, message,
                Toast.LENGTH_SHORT).show();
    }
}

更新了代码AddEmployeeActivity.java:

    dbRef.child(currentUser.getUid()).push().child("emailAddress").setValue(emailET.getText().toString(), completionListener);
    dbRef.child(currentUser.getUid()).push().child("socialSecurityNumber").setValue(ssnET.getText().toString(), completionListener);

RegisterEmployeeActivity.java:

 mDatabaseEmp = database.getReference("/Employees");
    currentUser =
            FirebaseAuth.getInstance().getCurrentUser();


    checkmarkImage = (ImageView) findViewById(R.id.checkmarkImage);

    //Insert information into FirebaseDB and go to next screen
    checkmarkImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            final String email = emailET.getText().toString().trim();
            final String password = passwordET.getText().toString().trim();
            final String ssn = ssnET.getText().toString().trim();
            final String fName = firstName.getText().toString().trim();
            final String lName = lastName.getText().toString().trim();
            final String phone = phoneNumber.getText().toString().trim();

            Log.i("CHECKMARKCLICK", "You have entered: " + email + " " + password);

            if (TextUtils.isEmpty(fName)) {
                MethodHelper.showAlert(RegisterEmployeeActivity.this, "First Name Required", "A First Name is required. Please enter your name and try again.");
                return;
            }

            if (TextUtils.isEmpty(lName)) {
                MethodHelper.showAlert(RegisterEmployeeActivity.this, "Last Name Required", "A Last Name is required. Please enter your name and try again.");
                return;
            }

            if (TextUtils.isEmpty(phone)) {
                MethodHelper.showAlert(RegisterEmployeeActivity.this, "Phone Number Required", "A Phone Number is required. Please enter your number and try again.");
                return;
            }


            if (TextUtils.isEmpty(email)) {
                MethodHelper.showAlert(RegisterEmployeeActivity.this, "Email Required", "An email is required. Please enter your email and try again.");
                return;
            }

            if (TextUtils.isEmpty(password)) {
                MethodHelper.showAlert(RegisterEmployeeActivity.this, "Password Required", "A password is required. Please enter your password and try again.");
                return;
            }

            if(TextUtils.isEmpty(ssn)) {
                MethodHelper.showAlert(RegisterEmployeeActivity.this, "Social Security Number Required", "A social security number is required. Please enter the last 4 digits of your social security number and try again.");
                return;
            }

            //mAuthListener = new FirebaseAuth.AuthStateListener() {
               // @Override
               // public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                  //  FirebaseUser user = firebaseAuth.getCurrentUser();

                //}

                    mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            //1st check: Make sure the username is not already in use
                            Log.i("DATA VALUE", dataSnapshot.child("RC9zIioE6vc5vlhrIethmbqyFDS2").getValue().toString());

                            //Used https://github.com/mitchtabian/Android-Instagram-Clone/tree/6e2ffe29621c592e57057b8561d3cac4df9c14a1/app/src/main/java/tabian/com/instagramclone  and https://www.youtube.com/watch?v=I-2T4i75gfw
                            if (firebaseMethods.checkIfUsernameExists(email, ssn, dataSnapshot)) {
                                auth.createUserWithEmailAndPassword(emailET.getText().toString(), passwordET.getText().toString())
                                        .addOnCompleteListener(RegisterEmployeeActivity.this, new OnCompleteListener() {

错误/警告:

I/FirebaseMethods: checkIfUsernameExists: email: null
No setter/field for -L21e85qYzHfOhI6IscR found on class com.netgalaxystudios.timeclock.Models.EmployeeUser

EmployeeUser.java:

public class EmployeeUser {

    private String userId;
    private String emailAddress;
    private String socialSecurityNumber;

    public EmployeeUser(String userId, String emailAddress, String socialSecurityNumber) {
        this.userId = userId;
        this.emailAddress = emailAddress;
        this.socialSecurityNumber = socialSecurityNumber;
    }

    public EmployeeUser(String emailAddress) {
        this.emailAddress = emailAddress;
    }

    public EmployeeUser() {}

    ...........


    public String getEmailAddress() {
        return emailAddress;
    }

    public void setEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress;
    }

     ....


}

1 个答案:

答案 0 :(得分:0)

假设Unverfied Employees节点是Firebase root的直接子节点,要使用这些pusehed id的子节点,您需要使用getChildren()方法,所以请使用以下代码:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference yourRef = rootRef.child("Unverfied Employees").child(currentUser.getUid());
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String emailAddress = ds.child("emailAddress").getValue(String.class);
            Log.d("TAG", emailAddress);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
yourRef.addListenerForSingleValueEvent(eventListener);

您的输出将是:

push2@aol.com
win1@aol.com
//and so on

注意,使用database.getReference("/Unverified Employees")时,无需使用说明/