2016-09-16 27 views
1

我遇到GeoFire等Firebase問題。刪除並重新插入GeoFire位置以觸發onKeyExited和onKeyEntered不起作用

我想根據GeoFire位置觸發器更新UI上的信息。當客戶端發生操作時,必須將數據保存在Firebase數據庫中,並且必須更新GeoFire。

我會更清楚一些代碼。

1-客戶端操作。爲用戶存儲溫度及其位置。

public void sendTemperature(Float temp) { 

    LatLng myPosition = getMyPosition(); 

    //instantiate the db connection 
    FirebaseDatabase database = FirebaseDatabase.getInstance(); 
    DatabaseReference dbTemperatures = database.getReference("temperatures"); 

    //push the value to global temperature db 
    String tempId = dbTemperatures.push().getKey(); 
    dbTemperatures.child("/"+tempId).setValue(temp); 

    //create an index to link the user with its last sent temperature 
    DatabaseReference dbUserLastTemperature = database.getReference("users_last_temperature"); 
    dbUserLastTemperature.child(userId).setValue(tempId); 

    //update the geofireDb (here is the problem) 
    geoUsersTemperatures.removeLocation(userId); 
    geoUsersTemperatures.setLocation(userId, new GeoLocation(myPosition.latitude, myPosition.longitude)); 

} 

2 - 客戶端的監聽器。獲取附近用戶的溫度通知。

GeoQuery usersTemperatureGeoQuery = geoUsersTemperatures.queryAtLocation(new GeoLocation(getMyPosition().latitude, getMyPosition().longitude), mapsRadius); 
    usersTemperatureGeoQuery.addGeoQueryEventListener(new GeoQueryEventListener() { 
     @Override 
     public void onKeyEntered(String key, GeoLocation location) { 
      System.out.println(String.format("Key %s entered the search area at [%f,%f]", key, location.latitude, location.longitude)); 
      addTemperature(key, location); 
     } 

     @Override 
     public void onKeyExited(String key) { 
      System.out.println(String.format("Key %s is no longer in the search area", key)); 
      removeTemperature(key); 
     } 

     @Override 
     public void onKeyMoved(String key, GeoLocation location) { 
      System.out.println(String.format("Key %s moved within the search area to [%f,%f]", key, location.latitude, location.longitude)); 
      moveTemperature(key, location); 
     } 

     @Override 
     public void onGeoQueryReady() { 
      System.out.println("All initial data has been loaded and events have been fired!"); 
     } 

     @Override 
     public void onGeoQueryError(DatabaseError error) { 
      System.err.println("There was an error with this query: " + error); 
     } 
    }); 

3-問題。我期望發生的事情是,當發送新的溫度時,監聽器檢測到它的刪除和新的插入(但實際上它的密鑰沒有改變),所以我可以更新我的UI。這不會發生,因爲這兩個操作非常快,GeoFire偵聽器不會觸發任何事情,因爲它沒有任何更改數據庫。

有沒有辦法讓偵聽器按照我的意願行事?

回答

0

這大概可以通過在removeLocation()中使用所謂的completion listener來解決。

快速,未經測試的寫了(所以它可能含有語法錯誤):

geoUsersTemperatures.removeLocation(userId, new GeoFire.CompletionListener { 
    public void onComplete(String key, DatabaseError error) { 
    geoUsersTemperatures.setLocation(userId, new GeoLocation(myPosition.latitude, myPosition.longitude)); 
    }); 
}); 

用這種方法你等待,直到該數據庫確認已設置新的位置之前刪除舊的位置。