FirestoreRecyclerAdapter不显示新添加的FireStore数据

时间:2018-12-01 10:25:06

标签: android android-recyclerview google-cloud-firestore firebaseui

我有一个自定义的FirestoreRecyclerAdapter,它可以正确显示Firestore数据库中当前存储的所有项目。但是,当我在数据库中输入新项目时,适配器不会显示数据库中新添加的项目。如果我返回屏幕并再次打开recyclerview,我可以看到“新”添加的数据。如何使Recycler视图显示新添加的Firestore数据?

预期:新数据显示在recylcerview的顶部 结果:新数据根本不在recyclerview中显示

问题:RecyclerView中不会显示新数据

 CollectionReference messagesCollectionRef = db.collection(MESSAGES);
    Query query = messagesCollectionRef.whereEqualTo(GROUPID, groupid).orderBy(TIMESTAMP, Query.Direction.ASCENDING);

    FirestoreRecyclerOptions<MessagesResponse> options = new FirestoreRecyclerOptions.Builder<MessagesResponse>()
            .setQuery(query, MessagesResponse.class)
            .build();

    adapter = new MessagesAdapter(options, progressBar, messagesList, userid);
    adapter.startListening();
    messagesList.setAdapter(adapter);

这是我的适配器

public class MessagesAdapter extends FirestoreRecyclerAdapter<MessagesResponse, MessagesHolder> {
private static final String USERS = "users";
private static final String IMAGE = "image";
private static final String MESSAGE = "message";
private FirebaseFirestore db;
private ProgressBar progressBar;
private RecyclerView messagesList;
private String userid;

public MessagesAdapter(@NonNull FirestoreRecyclerOptions<MessagesResponse> options, ProgressBar progressBar, RecyclerView messagesList, String userid) {
    super(options);

    this.progressBar = progressBar;
    this.messagesList = messagesList;
    this.userid = userid;
    db = FirebaseFirestore.getInstance();
}

@Override
public void onDataChanged() {
    messagesList.getLayoutManager().scrollToPosition(getItemCount() - 1);
    notifyDataSetChanged();
}

@Override
protected void onBindViewHolder(@NonNull MessagesHolder holder, int position, @NonNull MessagesResponse model) {
    progressBar.setVisibility(View.GONE);

    //set user profile pic
    setProfilePic(holder, model);

    //image message
    if(model.getType().equalsIgnoreCase(IMAGE)) {
        displayImage(model.getMessage(), holder);
    }
    //text message
    if(model.getType().equalsIgnoreCase(MESSAGE)) {
        holder.message.setText(model.getMessage());
    }
}

@NonNull
@Override
public MessagesHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.message_list_item,
            parent, false);
    return new MessagesHolder(v);

}

1 个答案:

答案 0 :(得分:0)

我通过在firebase控制台上的groupid和timestamp字段上创建索引来解决此问题。显然,这是用于创建复杂查询的东西。

这是有关创建索引的文档。 https://firebase.google.com/docs/firestore/query-data/indexing