gpt4 book ai didi

java - 如果数据尚不存在,如何将数据添加到 Firestore

转载 作者:行者123 更新时间:2023-12-01 21:10:42 27 4
gpt4 key购买 nike

我有一个类MapActivity.java,其方法是搜索我附近的咖啡馆和第二种方法

private void parseLocationResult(JSONObject result) throws JSONException {

String placeName = "", ivicinity = "";
Double placeRating = 0.0;
double latitude, longitude;

JSONArray jsonArray = result.getJSONArray("results");

if (result.getString(STATUS).equalsIgnoreCase(OK)) {

mMap.clear();

for (int i = 0; i < jsonArray.length(); i++) {
JSONObject place = jsonArray.getJSONObject(i);

if (!place.isNull(NAME)) {
placeName = place.getString(NAME);
}
if (!place.isNull(VICINITY)) {
ivicinity = place.getString(VICINITY);
}
if(!place.isNull( RATING )){
placeRating = place.getDouble( RATING );
}


latitude = place.getJSONObject(GEOMETRY).getJSONObject(LOCATION)
.getDouble(LATITUDE);
longitude = place.getJSONObject(GEOMETRY).getJSONObject(LOCATION)
.getDouble(LONGITUDE);

MarkerOptions markerOptions = new MarkerOptions();
LatLng latLng = new LatLng(latitude, longitude);
markerOptions.position(latLng);
markerOptions.title(placeName + " : " + ivicinity);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
PlaceDetail cafe= new PlaceDetail(placeName,ivicinity,placeRating);

Map<String, String> dataMap = new HashMap<>();
dataMap.put("name", placeName);
dataMap.put("address", ivicinity);
dataMap.put("rating", String.valueOf(placeRating));
db.collection("collection")
.add(dataMap)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
}
});
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12f));
mMap.addMarker(markerOptions);
}

Toast.makeText(getBaseContext(), jsonArray.length() + " Cafe(s) Found!",
Toast.LENGTH_LONG).show();
} else if (result.getString(STATUS).equalsIgnoreCase(ZERO_RESULTS)) {
Toast.makeText(getBaseContext(), "No Cafe Found in 4 Miles Radius!!!",
Toast.LENGTH_LONG).show();
}

}

将我的搜索结果保存到 Firestore。保存到基地几乎可以正常工作,但有一个问题。我只想保存尚未添加的咖啡馆。我想我需要任何检查系统 - 如果已经存在与我找到的值相同的数据,则不要保存它,否则保存。

如何阻止添加已存储在那里的数据?

最佳答案

据我了解,您希望将数据添加到您的集合中,但您希望确保这些数据在您的数据库中是唯一的。

本质上,在 Cloud Firestore 中,您无法确保来自规则或 SDK 的数据的唯一性。尽管我相信以下链接将帮助您实现这一目标,因为它们适用于类似的用例:

The accepted answer in this Stackoverflow Post解释如何通过规则实现您想要的目标。

另请检查this article其中方法非常简单。

  1. 使用“Cafes”集合,其中每个文档都对应一个 Cafe。文档的documentID应该是咖啡馆的名称。

  2. 当您尝试将搜索结果保存到 Firestore 时,请检查“Cafes”集合,看看是否有适合您每次要添加的搜索结果的 documentId。如果 documentId 不存在,则将搜索结果添加到您的集合中。

请告诉我这是否有帮助。

关于java - 如果数据尚不存在,如何将数据添加到 Firestore,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58902242/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com