我正在将Firestore用作应用程序的数据库。使用方法documentSnapshot.getString()
检索数据库中的某个值时,它始终为null
。
这个想法是,当任何用户在我的应用程序上创建新帖子时,该应用程序都会将该帖子和用户名存储在数据库中。
我在包含所有Firestore方法的单独类中使用该方法,然后在活动中将其重新调用。
在单独的类中使用它时,它返回null
,但是在活动本身中使用它时,它返回值。
@Override
public void newPost(String post) {
FirebaseAuth auth = FirebaseAuth.getInstance();
final FirebaseUser users = auth.getCurrentUser();
currentUser = users.getEmail();
if (currentUser != null) {
userSearch = db.collection("users")
.document(currentUser)
.get().toString();
db.collection("users")
.document(currentUser)
.get()
.addOnSuccessListener(new
OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot
documentSnapshot) {
if (documentSnapshot.exists()) {
userName =
documentSnapshot.getString("first_name");
}
}
});
}
Map<String, Object> postCase = new HashMap<>();
postCase.put("user_posted_email", currentUser);
postCase.put("user_posted_name", userName);
postCase.put("post", postBody = post);
db.collection("posts").add(postCase)
.addOnCompleteListener(new
OnCompleteListener<DocumentReference>() {
@Override
public void onComplete(@NonNull Task<DocumentReference>
task) {
if (task.isSuccessful()) {
postEvent(PostEvent.onPostingSuccess);
} else {
postEvent(PostEvent.onPostingError);
}
}
});
}
假设从用户集合中获取用户名后,便会发布该用户名,但始终为null
。
尝试活动本身时,它将返回用户名值。 a screenshot of my database