我有2个收藏集;预订信息和停车区。从ParkingArea文档中,我想将“ areanumber”字段的最新值保存到具有字段名称“ Area”的BookingInformation集合中。
我尝试了以下方法。在logcat中,我可以查看所需的数据,但不知道如何分配它们。我没有找到任何资源。请帮忙。
final List<String> parkingDocList = new ArrayList<>();
dataStore.collection("ParkingArea").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot documentSnapshot : task.getResult()) {
parkingDocList.add(documentSnapshot.getId());
}
}
}
});
final Map<String, Object> reserveInfo = new HashMap<>();
reserveInfo.put("date", date.getText().toString());
reserveInfo.put("startTime", startTime.getText().toString());
reserveInfo.put("endTime", endTime.getText().toString());
reserveInfo.put("userId", currentUserId);
reserveInfo.put("area", allocatedArea[0]);
dataStore.collection("BookingInformation").document(id).set(reserveInfo)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
Toast toast4 =
Toast.makeText(getActivity().getApplicationContext(),
"Area reserved successfully", Toast.LENGTH_SHORT);
toast4.show();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast toast5 = Toast.makeText(getActivity().getApplicationContext(), "Reservation failed", Toast.LENGTH_SHORT);
toast5.show();
}
});
答案 0 :(得分:1)
从Firestore(和大多数云API)异步加载数据。这意味着需要从数据库中获取数据的任何代码都必须在内部内,onComplete
处理程序在加载数据时被调用。
所以在您的情况下:
final List<String> parkingDocList = new ArrayList<>();
dataStore.collection("ParkingArea").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot documentSnapshot : task.getResult()) {
parkingDocList.add(documentSnapshot.getId());
}
final Map<String, Object> reserveInfo = new HashMap<>();
reserveInfo.put("date", date.getText().toString());
reserveInfo.put("startTime", startTime.getText().toString());
reserveInfo.put("endTime", endTime.getText().toString());
reserveInfo.put("userId", currentUserId);
reserveInfo.put("area", allocatedArea[0]);
dataStore.collection("BookingInformation").document(id).set(reserveInfo)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
Toast toast4 =
Toast.makeText(getActivity().getApplicationContext(),
"Area reserved successfully", Toast.LENGTH_SHORT);
toast4.show();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast toast5 = Toast.makeText(getActivity().getApplicationContext(), "Reservation failed", Toast.LENGTH_SHORT);
toast5.show();
}
});
}
}
});