带有(DocumentSnapShot documentsnapShot)参数的自定义对象.也是firebSAE的内部对象,它检索快照并将值设置为我的自定义模型也有其参数(DocumentSnapShot documentsnapShot).但是,我希望从文件中获取数据并将其传递给我的自定义参数,因为我的不仅仅是firebase还有多个数据.并且不可能在没有覆盖的情况下迭代firestore.
继承人的代码
public UserSettings getUserSettings(DocumentSnapshot documentSnapshot){ Log.d(TAG,"getUserSettings: retrieving user account settings from firestore"); DocumentReference mSettings = mFirebaseFirestore.collection("user_account_settings").document(userID); mSettings.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() { @Override public void onSuccess(DocumentSnapshot documentSnapshot) { UserAccountSettings settings = documentSnapshot.toObject(UserAccountSettings.class); settings.setDisplay_name(documentSnapshot.getString("display_name")); settings.setUsername(documentSnapshot.getString("username")); settings.setWebsite(documentSnapshot.getString("website")); settings.setProfile_photo(documentSnapshot.getString("profile_photo")); settings.setPosts(documentSnapshot.getLong("posts")); settings.setFollowers(documentSnapshot.getLong("followers")); settings.setFollowing(documentSnapshot.getLong("following")); } }); }
解决方法
您现在无法返回尚未加载的内容. Firestore异步加载数据,因为它可能需要一些时间.根据您的连接速度和状态,可能需要几百毫秒到几秒才能获得数据.如果要将设置对象传递给另一个方法,只需在onSuccess()方法中调用该方法,并将该对象作为参数传递.所以快速解决这个问题:
@Override public void onSuccess(DocumentSnapshot documentSnapshot) { UserAccountSettings settings = documentSnapshot.toObject(UserAccountSettings.class); yourMethod(settings); }
One more thing to mention is that you don’t need to set the those values to object that already have them. You are already getting the data from the database as an object.
所以请记住,onSuccess()方法具有异步行为,这意味着甚至在从数据库获取数据之前就会调用它.如果要在该方法之外使用设置对象,则需要创建自己的回调.要实现这一点,首先需要创建一个这样的接口:
public interface MyCallback { void onCallback(UserAccountSettings settings); }
然后,您需要创建一个实际从数据库获取数据的方法.此方法应如下所示:
public void readData(MyCallback myCallback) { DocumentReference mSettings = mFirebaseFirestore.collection("user_account_settings").document(userID); mSettings.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() { @Override public void onSuccess(DocumentSnapshot documentSnapshot) { UserAccountSettings settings = documentSnapshot.toObject(UserAccountSettings.class); myCallback.onCallback(settings); } }); }
最后,只需调用readData()方法并将MyCallback接口的实例作为参数传递给您需要的地方,如下所示:
readData(new MyCallback() { @Override public void onCallback(UserAccountSettings settings) { Log.d("TAG",settings.getDisplay_name()); } });
这是在onSuccess()方法之外可以使用UserAccountSettings类的对象的唯一方法.有关更多信息,您还可以查看此video.