每次活动开始时,Firebase文档字段都会重置,我需要保留它们。
集合和文档的创建是在onResume中使用“ setOptions.merge()”完成的,对于String,将文档值设置为null;对于数组,将文档值设置为emptyList。
@Override
protected void onResume() {
super.onResume();
//Creating the document if it does not already exist.
Map<String, Object> read_book = new HashMap<>();
read_book.put("read_pages", Collections.emptyList());
read_book.put("total_pages", null);
fireStoreDB.collection("user_" + user.getId).document("book_" + book.getId())
.set(read_book, SetOptions.merge())
.addOnSuccessListener(aVoid ->
Log.d("Activity", "FirestoreDB => created empty read_pages and total_pages"))
.addOnFailureListener(e ->
Log.d("Activity", "Firestore failed to create empty read_pages and total_pages" + e));
}
private void pageFlip(String currentPage, String totalPages){
// Add read page to array (no duplicates)
fireStoreDB.collection("user_" + user.getId).document("book_" + book.getId())
.update("read_pages", FieldValue.arrayUnion(currentPage))
.addOnSuccessListener(aVoid ->
Log.d("Activity", "FirestoreDB => updated read_pages " + currentPage))
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.d("Activity", "FirestoreDB => failed to update read_pages" + e);
}
});
// Set total book pages number
fireStoreDB.collection("user_" + user.getId).document("book_" + book.getId())
.update("total_pages", totalPages)
.addOnSuccessListener(aVoid ->
Log.d("Activity", "FirestoreDB => updated total_pages " + totalPages))
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.d("Activity", "FirestoreDB => failed to update total_pages" + e);
}
});
}
使用上述代码,每次调用onResume时,该字段都将重置为null和空列表。
我需要total_pages值和read_pages数组才能在Activity重新启动时持续存在,并且可以使用FieldValue.arrayUnion向read_pages数组添加新值。
实现用例的有效方法是什么?
答案 0 :(得分:3)
您可以直接将Set方法与SetOptions.merge()一起使用,而无需使用空值初始化
private void pageFlip(String currentPage, String totalPages){
Map<String, Object> data = new HashMap<>();
data.put("total_pages", totalPages);
data.put("read_pages", FieldValue.arrayUnion(currentPage));
// Add read page to array (no duplicates)
fireStoreDB.collection("user_" + user.getId).document("book_" + book.getId())
.set(data, SetOptions.merge())
.addOnSuccessListener(aVoid ->
Log.d("Activity", "FirestoreDB => updated read_pages " + currentPage))
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.d("Activity", "FirestoreDB => failed to update read_pages" + e);
}
});
}