即使在notifyDataSetChanged()之后,Firebase RecycleView适配器也不会更新

时间:2017-06-24 06:38:30

标签: android firebase firebase-realtime-database

我已为特定的firebase数据库引用注册了一个侦听器。一旦数据被改变"它显示一个toast消息,并应将chatMessage添加到列表中并在循环视图中显示该项目。但是,仅显示Toast消息,但该项目未添加到回收视图中。我认为这是由RecycleView适配器的问题引起的,但我无法确定位置。

public void getMessageByMessageUUID(final MessageAdapter messageAdapter, final String chatUUID, final String messageUUID) {
    MESSAGE_REFERENCE.child(chatUUID).child(messageUUID).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            ChatMessage message = dataSnapshot.getValue(ChatMessage.class);
            Toast.makeText(getApplicationContext(),
                    "Welcome " + chatUUID + " " + message.getMessageText(),
                    Toast.LENGTH_LONG)
                    .show();
            messageAdapter.addMessage(message);

            messageAdapter.notifyDataSetChanged();
        }

适配器类

private ArrayList<ChatMessage> messages = new ArrayList<ChatMessage>();
protected Context context;

public MessageAdapter(final String chatUUID, DatabaseReference databaseReference) {
    databaseReference.addChildEventListener(new ChildEventListener()...);
}

public void addMessage(ChatMessage chatMessage) {
    messages.add(chatMessage);

    notifyDataSetChanged();
}

@Override
public MessageHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    Context context = parent.getContext();
    LayoutInflater inflater = LayoutInflater.from(context);

    MessageHolder viewHolder = null;
    View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.messages, parent, false);
    viewHolder = new MessageHolder(layoutView, messages);

    return viewHolder;
}

@Override
public void onBindViewHolder(MessageHolder holder, int position) {
    holder.messageImage.setImageResource(R.drawable.user_pacific);
    holder.messageText.setText(messages.get(position).getMessageText());
}

@Override
public int getItemCount() {
    return this.messages.size();
}

@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
    super.onAttachedToRecyclerView(recyclerView);
}

1 个答案:

答案 0 :(得分:0)

问题不在于firebase代码或适配器,而在于使用LinearLayoutManager。我相信代码是在屏幕外添加的。我通过改变

解决了这个问题
LinearLayoutManager manager = new LinearLayoutManager(this);

LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);