我想从firestore检索当前记录的用户数据,但这显示错误

时间:2018-03-09 12:15:22

标签: java android firebase-realtime-database google-cloud-firestore

  

尝试调用虚拟方法com.google.firebase.auth.FirebaseUser com.google.firebase.auth.FirebaseAuth.getCurrentUser()'在null对象引用上:

MyAccount.java

public class MyAccount extends AppCompatActivity  {

    private FirebaseAuth mAuth;
    private TextView email,passwordtxt;
    private FirebaseFirestore mFirestore;
    private String UserId;
    private FirebaseAuth.AuthStateListener mAuthListener;

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

        email       = (TextView)findViewById(R.id.email_txt);
        UserId      = mAuth.getCurrentUser().getUid();
        passwordtxt = (TextView)findViewById(R.id.pass_txt);
        mAuth       = FirebaseAuth.getInstance();
        mFirestore  = FirebaseFirestore.getInstance();

        mFirestore.collection("Hospitals")
                  .document(UserId).get()
                  .addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
            @Override
            public void onSuccess(DocumentSnapshot documentSnapshot) {
                String user_name = documentSnapshot.getString("email");
                String password  = documentSnapshot.getString("password");

                email.setText(user_name);
                passwordtxt.setText(password);
            }
        });
    }
}

1 个答案:

答案 0 :(得分:0)

将您的onCreate方法代码更改为:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my_account);

    email = (TextView)findViewById(R.id.email_txt);
    mAuth = FirebaseAuth.getInstance();
    UserId = mAuth.getCurrentUser().getUid();
    passwordtxt = (TextView)findViewById(R.id.pass_txt);

    mFirestore = FirebaseFirestore.getInstance();
   mFirestore.collection("Hospitals").document(UserId).get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
        @Override
        public void onSuccess(DocumentSnapshot documentSnapshot) {
            String user_name = documentSnapshot.getString("email");
            String password  = documentSnapshot.getString("password");


            email.setText(user_name);
            passwordtxt.setText(password);
        }
    });    
}