java - 如何使用java在android studio应用程序中由多个注册用户访问Firebase Firestore集合?
问题描述
我面临的问题是:当用户 2 尝试访问同一个数据库集合时,而不是显示数据库中已经存在一些数据(要求是用户 1 输入的数据保存在同一个数据库中),我得到数据库中为空。我还可以弄清楚为什么会发生这种情况,但对如何以不同用户在 BookingInformation 集合中保存文档字段“StartTime”和“EndTimes”的唯一值的方式查询 Firestore 集合却一无所知?
以下是我使用的代码;
FirebaseAuth fAuth = FirebaseAuth.getInstance();
String userId = fAuth.getCurrentUser().getUid();
Log.d(TAG,"userID: "+userId);
FirebaseFirestore fstore = FirebaseFirestore.getInstance();
DocumentReference docRef =
fstore.collection("BookingInformation").document(userId);
之所以发生这种情况,是因为我使用 userId 作为“BookingInformation”集合的文档 ID。通过这样做,每次新用户登录时都会创建一个新文档。我应该如何解决它以确保当用户 2 输入数据时,它首先检查集合中是否存在某些文档?
添加代码
NewBookingFragment.java
newBookingViewModel.getBookingInformation().observe(getViewLifecycleOwner(), new Observer<BookingInfo>() {
@Override
public void onChanged(final BookingInfo bookingInfo) {
Log.d(TAG,"hi from bookingInfodatabase");
Log.d(TAG,"content of bookingInfodatabase"+bookingInfo);
if (bookingInfo == null) {
Log.d(TAG,"no data from database, so add as a new");
Toast toast = Toast.makeText(getActivity().getApplicationContext(), "No data from database, so add as a new booking information", Toast.LENGTH_SHORT);
toast.show();
searchBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast toast1 = Toast.makeText(getActivity().getApplicationContext(), "No data in database to compare!", Toast.LENGTH_SHORT);
toast1.show();
}
});
addBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "user id in fragment class: "+currentUserId);
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);
dataStore.collection("BookingInformation").document(currentUserId).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();
}
});
}
});
}else{
searchBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG,"after clicking available button");
Log.d(TAG,"booking id"+bookingInfo.getBookingDocId());
Log.d(TAG,"database time: "+bookingInfo.getStartTime());
Log.d(TAG,"user input time: "+startTime.getText().toString());
Log.d(TAG,"comparing time: "+bookingInfo.getStartTime().equals(startTime.getText().toString()));
if (bookingInfo.getDate().equals(date.getText().toString()) ){
Log.d(TAG, "Date check ");
if (bookingInfo.getStartTime().equals(startTime.getText().toString()) && bookingInfo.getEndTime().equals(endTime.getText().toString())) {
Toast toast = Toast.makeText(getActivity().getApplicationContext(), "Select another time.", Toast.LENGTH_SHORT);
toast.show();
Log.d(TAG, "start and end time check ");
if (bookingInfo.getStartTime().equals(startTime.getText().toString())) {
Log.d(TAG, "start time check ");
if (bookingInfo.getEndTime().equals(endTime.getText().toString())) {
Toast toast2 = Toast.makeText(getActivity().getApplicationContext(), "Select another end time.", Toast.LENGTH_SHORT);
toast2.show();
Log.d(TAG, "end time check ");
}
Log.d(TAG, "end time not equal check ");
}
Log.d(TAG, "start time not equal check ");
}
else{
Toast toast4 = Toast.makeText(getActivity().getApplicationContext(), "Area available at this time,'Book' it.", Toast.LENGTH_SHORT);
toast4.show();
availabletextView.setText("Area available");
addBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "user id in fragment class: "+currentUserId);
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);
dataStore.collection("BookingInformation").document(currentUserId).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();
}
});
}
});
}
} else {
availabletextView.setText("Area available");
Log.d(TAG, "user id: "+currentUserId);
addBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "user id in fragment class: "+currentUserId);
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);
dataStore.collection("BookingInformation").document(currentUserId).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();
}
});
}
});
}
}
});
}
}
});
NewBookingViewModel.java
public class NewBookingViewModel extends ViewModel {
private static final String TAG = "Firelog";
public LiveData<BookingInfo> getBookingInformation() {
final MutableLiveData<BookingInfo> bookingInfoMutableLiveData = new MutableLiveData<>();
FirebaseAuth fAuth = FirebaseAuth.getInstance();
String userId = fAuth.getCurrentUser().getUid();
Log.d(TAG,"userID: "+userId);
FirebaseFirestore fstore = FirebaseFirestore.getInstance();
DocumentReference docRef = fstore.collection("BookingInformation").document(userId);
Log.d(TAG,"docRef"+docRef);
String docid = docRef.getId();
Log.d(TAG,"document id"+docid);
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
Log.d(TAG,"hi from viewmodel database");
DocumentSnapshot documentSnapshot = task.getResult();
Log.d(TAG, "Doc ID: "+documentSnapshot.getId());
Log.d(TAG,"document exist: "+documentSnapshot.exists());
if (documentSnapshot != null && documentSnapshot.exists()) {
String date = documentSnapshot.getString("Date");
String startTime = documentSnapshot.getString("StartTime");
String endTime = documentSnapshot.getString("EndTime");
BookingInfo bookingInfo = documentSnapshot.toObject(BookingInfo.class);
Log.d(TAG,"hi from viewmodel date: "+date);
bookingInfo.setDate(date);
bookingInfo.setStartTime(startTime);
bookingInfo.setEndTime(endTime);
bookingInfoMutableLiveData.postValue(bookingInfo);
} else {
bookingInfoMutableLiveData.postValue(null);
}
} else {
bookingInfoMutableLiveData.postValue(null);
}
}
});
return bookingInfoMutableLiveData;
}
}
谢谢。
解决方案
我刚刚发现要允许 2 个或更多用户在集合中输入和保存数据而没有任何重复数据 wrt startTime 和 endTime 字段,我必须确保文档已经存在或不存在。为此,作为解决方案,我计算了集合中的文档。
以下是代码“NewBookingViewModel.java”
fstore.collection("BookingInformation")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
QuerySnapshot querySnapshot = task.getResult();
if (!querySnapshot.isEmpty()) {
for (QueryDocumentSnapshot queryDocumentSnapshot : task.getResult()) {
count++;
Log.d(TAG, "document count: "+count);
if (count != 0) {
String date = queryDocumentSnapshot.getString("Date");
String startTime = queryDocumentSnapshot.getString("StartTime");
String endTime = queryDocumentSnapshot.getString("EndTime");
BookingInfo bookingInfo = queryDocumentSnapshot.toObject(BookingInfo.class);
bookingInfo.setBookingDocId((queryDocumentSnapshot.getId()));
bookingInfo.setDate(date);
bookingInfo.setStartTime(startTime);
bookingInfo.setEndTime(endTime);
bookingInfoMutableLiveData.postValue(bookingInfo);
}else {
Log.d(TAG, "No booking data");
}
}
} else {
bookingInfoMutableLiveData.postValue(null);
}
} else {
bookingInfoMutableLiveData.postValue(null);
}
}
});
推荐阅读
- flutter - 将 Whatsapp 业务 API 与 Flutter 应用程序集成
- python - python新手,刚刚遇到一个新错误:pygame.error: video system not initialized
- postgresql - 通过 pgAdmin 的“字符变化”和“字符变化 []”之间的 PostgreSQL 区别
- javascript - react native 中的嵌套列表组件
- excel - 如何在excel中将同一组中的表格中的损益组合在一起?
- javascript - TypeError:无法读取我的 api 中未定义的属性“地址”
- python - 如何从给定的索引数组中弹出列表中的元素?
- python - 如何在 bigquery 中插入一行 DATE 类型的列
- ruby - 测试 ruby 模块类方法不起作用
- python - 在 Python 中从网页中检索信息?