我正在尝试将我的实时数据库调整为适合聊天应用程序的Cloud Firestore。要存储的对象属于我创建的Message类。我希望邮件成为文档。
我的RecyclerView适配器将使用实时数据库像这样检索它们:
public ChatRecyclerViewAdapter(Context mContext, ArrayList<String> mMessage, ArrayList<String> mAuthor, String mRoomID,DatabaseReference reference) {
this.mContext = mContext;
this.mRoomID = mRoomID;
mDatabaseReference = reference.child(mRoomID+"_messages");
recentMessages = mDatabaseReference.orderByKey().limitToLast(numberOfRecentMessages);
recentMessages.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
// Convert data snapshot from Database into a Message Object
Message message = dataSnapshot.getValue(Message.class);
// Add it to an arrayList of Messages
messageList.add(message);
// Notice Changes
notifyItemInserted(messageList.size());
}
下面是我如何开始使用Firestore重新创建它的方法。如何在快照侦听器的onEvent方法中将快照转换回Message?
public ChatRecyclerViewAdapter(Context mContext, ArrayList<String> mMessage, ArrayList<String> mAuthor, String mRoomID, FirebaseFirestore firestore, CollectionReference reference) {
this.mContext = mContext;
this.mRoomID = mRoomID;
messageList = new ArrayList<>();
firestore = FirebaseFirestore.getInstance();
mCollection = firestore.collection(mRoomID + "_messages");
mCollection.addSnapshotListener(new com.google.firebase.firestore.EventListener<QuerySnapshot>() {
@Override
public void onEvent(@javax.annotation.Nullable QuerySnapshot queryDocumentSnapshots, @javax.annotation.Nullable FirebaseFirestoreException e) {
for (DocumentChange documentChange:queryDocumentSnapshots.getDocumentChanges()){
switch (documentChange.getType()){
case ADDED:
}
}
}
});
mCollection.get();
答案 0 :(得分:1)
为了将您的文档转换为类,请使用:-
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
如此处所述:-
ExceptionFilterAttribute
更新:- 您可以在代码中将其用作:-
Message message = documentSnapshot.toObject(Message.class);