我正在开发一个Android应用程序,我需要在应用程序的启动画面中从Firestore检索数据,并使用该文档快照中的特定值来检索另一个文档。为此,我需要从Firebase的get()函数中获取字符串值。 但是当我尝试这个时,我没有从函数中得到变量的值:
String userCityL;
DocumentReference docRef = firestoreDB.collection("users").document(mail);
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
String userCityL;
if (document.exists()) {
Log.d(TAG, "DocumentSnapshot data: " + document.getData());
userNameL = document.getString("UserName");
userPhoneL = document.getString("UserPhoneNo");
userDegreeL = document.getString("UserDegree");
userSpecialL = document.getString("UserSpecial");
userCityL = document.getString("UserCity");
userProfilePicL = document.getString("downloadUri");
TextView userCity = findViewById(R.id.tvCity);
userCity.setText(userCityL);
//loadNotesList();
//dummy(userCityL);
//loadNotesList(userCityL);
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
此处,userCityL
变量中没有存储任何内容。
答案 0 :(得分:0)
您没有在onComplete()
函数之外获得该字符串的值,而不是get()
函数之外的值。发生这种情况是因为onComplete()
函数具有异步行为。您也不能简单地创建一个全局变量并在函数外部使用它的值,因为它始终是null
。如果要在onDataChange()
方法之外使用来自数据库的值,则有两种选择。第一个是将所需的对象作为参数传递给类中定义的方法,如下所示:
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
String userCityL = document.getString("UserCity");
methodThatDoesSomething(userCityL); //Method call
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
private void methodThatDoesSomething(String userCityL) {
//Do what you need to do with your userCityL object
}
或者,如果您想以更复杂的方式使用它,那么请深入了解现代API的异步世界,并在此 post 中查看我的答案的最后一部分,我已经逐步解释了如何使用自定义回调实现此目的。有关更多信息,您还可以查看此 video 。
答案 1 :(得分:0)
是的,但是你可以在获得结果之前调用字符串。
尝试将函数放在该函数中调用字符串的位置。
查看Alex Mamo视频,了解您的解释。
答案 2 :(得分:-2)
我使用“共享的首选项”解决了这个问题。我的问题是获取当前登录用户的用户数据,并在所有活动中的整个应用程序中使用此数据。 在这里,我在启动屏幕期间从Firebase提取数据,并将其存储在共享首选项文件中,并在其他活动中使用这些数据。 谢谢:)