【发布时间】:2021-01-12 10:42:21
【问题描述】:
首先,我希望任何人都可以使用以下文档参考帮助调整我的代码行。
从下面的 firebase 控制台可以看出,我的 FaceEmotion-id 文档包含 Faceemotion 和 Timestamp 字段。 使用下面的代码,每次用户获得不同的情绪时,firestore 都会覆盖情绪。因此,我无法看到用户在使用我的应用程序时获得的不同情绪以及他/她使用我的应用程序的不同时间。
我需要防止覆盖上述两个字段。请帮我。我想要的是在文档中添加字段而不是覆盖它。
另外,我不知道如何为名为 FaceEmotion-id 的文档生成不同的 id。正如您从下面的代码中看到的那样,我实际上已经使用 Uid 事先引用了该文档。但是对于“结果”集合中的子文档。我似乎找不到让它独一无二的方法。
这是我的代码:
public static final String TAG = "TAG";
FirebaseAuth fAuth;
FirebaseFirestore fStore;
String userID;
String FaceEmotion;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detection);
fAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
StartQues = (Button) findViewById(R.id.view_question);
StartQues.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String Emotion = EmotionType.toString();
userID = fAuth.getCurrentUser().getUid();
FaceEmotion = "FaceEmotion";
DocumentReference documentReference = fStore.collection("users").document(userID).collection("Result").document("FaceEmotion-id");
//DocumentReference documentReference = fStore.collection("users").document(userID).collection("FaceEmotion").document(Emotion);
Map<String,Object> user = new HashMap<>();
user.put("FaceEmotion",Emotion);
user.put("timestamp", FieldValue.serverTimestamp());
documentReference.set(user).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "onSuccess: Data has been saved "+ userID);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.d(TAG, "onFailure: " + e.toString());
}
});
【问题讨论】:
-
为了更好地理解,您需要不同的文档 ID?您是否尝试过使用 add() 而不是 set()?
-
是的。我试过了,但使用 .add @AlexMamo 时出现错误
-
使用 add() 的示例可以是found here。如果这不起作用,请发布您收到的错误
标签: android firebase google-cloud-firestore save add