每次运行代码时都会创建Firestore云新文档

时间:2018-07-13 09:08:35

标签: android firebase google-cloud-firestore

无论何时将位置从应用程序发送到Firestore云,它都会每次创建一个新文档。我只希望更改发生在已更改的文档字段中。

这是我的代码:-

LocationManager locationManager;
LocationListener locationListener;

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if( grantResults.length > 0  && grantResults[0] == PackageManager.PERMISSION_GRANTED){
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60 , 0,locationListener);
    }

}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    locationListener = new LocationListener() {

        @Override
        public void onLocationChanged(Location location) {

            Toast.makeText(MainActivity.this, location.toString(),Toast.LENGTH_LONG).show();



            FirebaseFirestore db = FirebaseFirestore.getInstance();

            db.collection("Location")
                    .add(location)
                    .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                        @Override
                        public void onSuccess(DocumentReference documentReference) {
                            Log.d("Info", "DocumentSnapshot added with ID: " + documentReference.getId());
                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Log.w("Info", "Error adding document", e);
                        }
                    }); ...
}

1 个答案:

答案 0 :(得分:0)

正在创建一个新文档,因为您正在使用add()

  

public Task<DocumentReference> add (Object pojo)

     

使用指定的POJO作为内容向此集合添加一个新文档,并自动为其分配一个文档ID。

您需要改用set()

db.collection("cities").document("Locations")
    .set(location)
    .addOnSuccessListener(new OnSuccessListener<Void>() {

还要检查此内容:

Firestore: set() & add()