该文档是用户ID,我想从地图“地址”中检索特定用户的“地址1”。
private FirebaseFirestore mfirestore;
DocumentReference docRef;
private FirebaseAuth mAuth;
private FirebaseUser user;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_address);
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser();
uid = user.getUid();
docRef = mfirestore.collection("user").document(uid);
}
@Override
protected void onStart() {
super.onStart();
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
if (document.getData().get("Address")!=null){
String Address=document.getData().get("Address").toString();
}
}
} else {
Toast.makeText(UserAddress.this, task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
我已经检索了整个“地址”,但无法找到一种方法来单独获取用户的地址1。
答案 0 :(得分:0)
地图类型文档字段在Java中显示为类型Map<String, Object>
。如果您要访问地图,则只需对其进行投射:
Map<String, Object> address = (Map<String, Object>) document.getData().get("Address");
现在您可以使用该地图访问其各个字段:
String address1 = (String) address.get("Address1");
理想情况下,还应在强制转换每个值之前检查该类型是否为空,否则可能会引发异常。