我有一个带3个参数的User类实例(currentUser):用户名,电子邮件和等级,以及一个Firestore的“用户”集合,其中的文档仅包括3个字段:用户名,电子邮件和等级。我正在尝试检索登录用户的数据并将其保存在我的currentUser实例中,并使用loadUserData()方法显示它,但Android不会分配该值。
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_profile, container, false);
ownerProfileRetriever(this.getContext());
loadUserData(root);
viewPager = root.findViewById(R.id.view_pager);
tabLayout = root.findViewById(R.id.tabs);
viewPager.setAdapter(createCardAdapter());
new TabLayoutMediator(tabLayout, viewPager,
new TabLayoutMediator.TabConfigurationStrategy() {
@Override public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
tab.setText("Tab " + (position + 1));
}
}).attach();
return root;
}
private void ownerProfileRetriever(Context context) {
String userId = FirebaseAuth.getInstance().getCurrentUser() != null ? FirebaseAuth.getInstance().getCurrentUser().getUid() : null;
FirebaseFirestore db = FirebaseFirestore.getInstance();
if (userId == null || userId.isEmpty()) {
Toast.makeText(context, "No user id", Toast.LENGTH_SHORT).show();
return;
}
DocumentReference docRef = db.collection("users").document(userId);
docRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
currentUser = documentSnapshot.toObject(User.class);
}
});
}
private void loadUserData(View root){
TextView username = root.findViewById(R.id.username);
username.setText(currentUser.getUsername());
TextView email = root.findViewById(R.id.email);
email.setText(currentUser.getEmail());
TextView rating = root.findViewById(R.id.ratingValue);
rating.setText(String.valueOf(currentUser.getRating()));
}
}
当我运行它时,我没有收到任何错误,但是用户名,电子邮件和等级未显示在屏幕上。 (以防万一,不应该在视图寻呼机中显示该日期)
答案 0 :(得分:1)
检索数据后,您需要调用方法loadUserData()
:
DocumentReference docRef = db.collection("users").document(userId);
docRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
currentUser = documentSnapshot.toObject(User.class);
loadUserData(root);
}
});
}