首页 > 解决方案 > 从 Firestore 检索当前登录用户的数据

问题描述

我试了很多次,仍然无法显示用户当前的登录数据。我想从 Firestore 数据库中获取数据到用户的个人资料页面,但它保持空白。

这是我的 register.java:

public class Register extends AppCompatActivity {

//Variables
TextInputLayout username, email, PhoneNo, password;
RadioGroup radioGroup;
RadioButton selectedElderly, selectedGuardian;
Button regBtn, regToLoginBtn;

FirebaseAuth fAuth;
FirebaseFirestore fStore;

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

    fAuth = FirebaseAuth.getInstance();
    fStore = FirebaseFirestore.getInstance();

    //Hooks to all xml elements in activity_register.xml
    username = findViewById(R.id.reg_username);
    email = findViewById(R.id.reg_email);
    PhoneNo = findViewById(R.id.reg_phoneNo);
    password = findViewById(R.id.reg_password);
    regBtn = findViewById(R.id.reg_btn);
    regToLoginBtn = findViewById(R.id.reg_login_btn);
    radioGroup = findViewById(R.id.radio_type);
    selectedGuardian = findViewById(R.id.radioGuardian);
    selectedElderly = findViewById(R.id.radioElderly);

    regToLoginBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Register.this, Login.class);
            startActivity(intent);
        }
    });

    regBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (validateUsername() && validateEmail() && validatePhoneNo() && validateUserType() && validatePassword() == true) {
                Intent intent = new Intent(Register.this, Login.class);
                startActivity(intent);
            } else {
                validateUsername();
                validateEmail();
                validatePhoneNo();
                validateUserType();
                validatePassword();
            }
            fAuth.createUserWithEmailAndPassword(email.getEditText().getText().toString(), password.getEditText().getText().toString()).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
                @Override
                public void onSuccess(AuthResult authResult) {
                    FirebaseUser user = fAuth.getCurrentUser();
                    Toast.makeText(Register.this, "Account Created", Toast.LENGTH_SHORT).show();
                  
                    DocumentReference df = fStore.collection("Users").document(user.getUid());
                    Map<String, Object> userInfo = new HashMap<>();
                    userInfo.put("Username", username.getEditText().getText().toString());
                    userInfo.put("Email", email.getEditText().getText().toString());
                    userInfo.put("phoneNo", PhoneNo.getEditText().getText().toString());
                    userInfo.put("Password",password.getEditText().getText().toString());
                   
                    //specify the user is elderly
                    if (selectedElderly.isChecked()) {
                        userInfo.put("isElderly", "1");
                    }
                    if (selectedGuardian.isChecked()) {
                        userInfo.put("isGuardian", "1");
                    }

                    df.set(userInfo);
                    if (selectedElderly.isChecked()) {
                        startActivity(new Intent(getApplicationContext(), Login.class));
                        finish();
                    }
                    if (selectedGuardian.isChecked()) {
                        startActivity(new Intent(getApplicationContext(), Login.class));
                        finish();
                    }
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Toast.makeText(Register.this, "Failed to Create Account", Toast.LENGTH_SHORT).show();
                }
            });

                }

这是profile.java:

public class profileGuardian extends AppCompatActivity {

TextInputLayout username, email, PhoneNo, password, address;
TextView usernameLabel, emailLabel;
Button save;
FirebaseAuth fAuth;
FirebaseFirestore fStore;

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

    //Hooks
    username = findViewById(R.id.full_name_profile);
    email = (TextInputLayout) findViewById(R.id.email_profile);
    PhoneNo = (TextInputLayout) findViewById(R.id.phoneNo_profile);
    password = (TextInputLayout) findViewById(R.id.password_profile);
    address = (TextInputLayout) findViewById(R.id.address_profile);
    emailLabel = (TextView) findViewById(R.id.email_field);
    usernameLabel = (TextView) findViewById(R.id.username_field);
    save = findViewById(R.id.save_btn);

    getData();
}

private void getData() {
    fStore = FirebaseFirestore.getInstance();
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    final String current = user.getUid();//getting unique user id

    fStore.collection("Users")
            .whereEqualTo("uId", current)//looks for the corresponding value with the field
            // in the database
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (DocumentSnapshot document : task.getResult()) {

                            emailLabel.setText((CharSequence) document.get("Email"));
                            usernameLabel.setText((CharSequence) document.get("Username"));
                            username.getEditText().setText((CharSequence) document.get("Username"));
                            email.getEditText().setText((CharSequence) document.get("Email"));
                            PhoneNo.getEditText().setText((CharSequence) document.get("phoneNo"));
                            password.getEditText().setText((CharSequence) document.get("Password"));
                        }
                    }
                }

            });
}

这是我的数据库结构:

数据库结构

我在 Youtube 上尝试了多种解决方案,但一直失败..

标签: javaandroidfirebasegoogle-cloud-firestore

解决方案


在呈现的代码get方法中返回类型QuerySnapshot参考)的结果。我认为这task.getResult()将获取QuerySnapshot对象而不是文档列表,因此循环无法正常工作。

根据参考 for声明应该是这样的:

for (DocumentSnapshot document : task.getResult().getDocuments())

应该可以遍历包含在QuerySnapshot.


推荐阅读