[英]Best practices for defining and initializing variables in web.xml and then accessing them from Java code
[英]Best practices to update variables in app from firebase
抱歉,标题混乱,我无法提出更好的标题,因此,如果有人认为他认为更好,请更新。
问题的核心。
我有一个包含信息的Firebase实时数据库,我有以下课程:
public class FirebaseUtil implements Constants {
private static final String fbRoot = "foods",
fbName = "name",
fbImage = "image";
private static FirebaseUtil instance;
public static FirebaseUtil getInstance() {
return instance == null ? new FirebaseUtil() : instance;
}
private FirebaseDatabase mFBDB;
private int mItemCount = 10;
private boolean mItemCountUpdateRecently = false;
private FirebaseUtil() {
instance = this;
mFBDB = FirebaseDatabase.getInstance();
}
public void getNumberOfItems() {
mFBDB.getReference(fbRoot).addListenerForSingleValueEvent(new VEListenerWrapper(runnable) {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
在getNumberOfItems()
内部,我想获取称为“ foods”( fbRoot
)的分支的子fbRoot
并将其更新为mItemCount
。
到目前为止,我采用的方法是创建一个ValueEventListener
包装器,该包装器具有一个接口,一旦onDataChange
完成并更新me的值,该接口将被执行。
老实说,我认为这是一个非常糟糕的做法,这就是为什么我试图了解从ValueEventListener
内部更改变量的最佳方法是什么,或者通常是可接受的方法。
请注意,我要更新Firebase中不存在的值。
如果只想更新一个值,则不需要使用ValueEventListener
,只需直接在引用上使用setValue()
方法即可。
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.child("name").setValue("John");
如果要控制子级数,则直接在dataSnapshot
对象上直接使用getChildrenCount()
方法。 但是请记住,要将此数字设置为视图,请在onDataChange
方法内使用set方法,因为此方法是异步调用的。
希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.