如何在动态节点上设置侦听器?火力地堡

时间:2017-10-20 05:52:37

标签: java android firebase firebase-realtime-database

我需要在当前坐标上获得所有玩家,每次转弯都会改变。问题是如果我返回到我已经拥有的坐标,onChildAdded,onChildRemoved方法的工作量超过了必要的范围。我做错了什么?

基础结构

enter image description here

当用户向北时,执行onNorth方法,删除旧坐标并在节点中添加新坐标" users / uid / location和locations"

public void onNorth(View view) {
    Map<String, Object> update = new HashMap<>();
    update.put("locations/"+ns+"/"+we+"/"+userId, null);
    ++ns;
    update.put("users/" + userId + "/location/ns", ns);
    update.put("locations/"+ns+"/"+we+"/"+userId, new User("Bot"));

    mFirebaseDatabase.getReference().updateChildren(update);
}

我将侦听器设置为获取当前坐标(&#34; users / userId / location&#34;)。

mFirebaseDatabase = FirebaseDatabase.getInstance();
mReferenceLocation = mFirebaseDatabase.getReference("users/" + userId + "/location");

if (mValueEventListener == null) {
mValueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        Location location = dataSnapshot.getValue(Location.class);
        ns = location.getNs();
        we = location.getWe();

        //Listener on current position(locations)
        setListenerForCurrentLocation(ns,we);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
};

mReferenceLocation.addValueEventListener(mValueEventListener);}

我设置了侦听器以获取当前位置的所有用户

mReferenceLocations = mFirebaseDatabase.getReference("locations/" + ns+"/"+we);
public void setListenerForCurrentLocation(long ns, long we){
    mChildEventListenerLocations = new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        Log.e("onChildAdded", dataSnapshot.getKey());
    }

    @Override
    public void onChildChanged(DataSnapshot dataSnapshot, String s){
            Log.e("onChildChanged", dataSnapshot.getKey());
    }

    @Override
    public void onChildRemoved(DataSnapshot dataSnapshot) {
        Log.e("onChildRemoved", dataSnapshot.getKey());
    }

    @Override
    public void onChildMoved(DataSnapshot dataSnapshot, String s) {
        Log.e("onChildMoved", dataSnapshot.getKey());
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
    }
};
mReferenceLocations.addChildEventListener(mChildEventListenerLocations);
}

0 个答案:

没有答案