我有一个Order节点和一个Status键.我正在寻找状态值的变化,如果检测到任何变化,我必须阅读父订单节点.
关键点是我不想听Order节点中的更改.但只是Order节点下的Status.最佳方式是什么?在另一个监听器中有一个监听器是否好?这是我的代码:
final Query qRef = FirebaseDatabase.getInstance().getReference().child("orders").orderByChild("customerId").equalTo(FirebaseAuth.getInstance().getCurrentUser().getUid()) .limitToFirst(1); qRef.keepSynced(true); final DatabaseReference reference = qRef.getRef().child("status"); reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { DatabaseReference inner = reference.getParent(); inner.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot parent) { if (parent != null) { Order newOrder = parent.getValue(Order.class); if (newOrder != null) { if (newOrder.getStatus() != null && !newOrder.getStatus().equals("FX_OVER")) processOrder(newOrder); } } } @Override public void onCancelled(DatabaseError databaseError) { } }); } @Override public void onCancelled(DatabaseError databaseError) { } });
和JSON:
{ "20161010210955" : { "createdAt" : { "date" : 10,"day" : 1,"hours" : 21,"minutes" : 9,"month" : 9,"seconds" : 55,"time" : 1476113995244,"timezoneOffset" : -330,"year" : 116 },"customerId" : "npsd3Ldfsdf1x0hsdfsdf2mj14VUA876f2","id" : "20161010210955","status" : "FX_FULL" } }
解决方法
你为什么不先检查状态?你知道开始状态的价值.我认为这个解决方案应该是最佳方式.
reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if("FX_OVER".equals(dataSnapshot.getValue(String.class)) { reference.getParent().addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot parent) { // This is a defensive check. I dont know this is necessary. // If status exist,parent must be exist. if (parent.exists()) { Order newOrder = parent.getValue(Order.class); if (newOrder != null) { processOrder(newOrder); } } } @Override public void onCancelled(DatabaseError databaseError) {} }); } } @Override public void onCancelled(DatabaseError databaseError) {} });