¿为什么recyclerView不会立即更新从Firebase获得的数据?

时间:2017-06-05 19:48:16

标签: android firebase firebase-realtime-database android-recyclerview recycler-adapter

我正在使用recyclelerView来扩展两种类型的视图,以便能够进行聊天,一切都很好,但不会立即发送或接收 当我发送消息时,除非我点击我的编辑文本,否则不会收到消息 这是错误的,因为在聊天中应该立即显示...

我的适配器:

     public class ChatRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    public Context context;
    public ArrayList<ChatPersonal> items = new ArrayList<>();
    private String mId;
    private static final int CHAT_RIGHT = 1;
    private static final int CHAT_LEFT = 2;



    public ChatRecyclerAdapter (Context context, ArrayList<ChatPersonal> items, String mId){
        this.context = context;
        this.items = items;
        this.mId = mId;
    }



    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = null;
        RecyclerView.ViewHolder holder = null;
        switch (viewType){
            case CHAT_RIGHT:
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_chat_right, parent, false);
                holder = new ChatPersonalHolderSender(view);
                break;
            case CHAT_LEFT:
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_chat_left, parent, false);
                holder = new ChatPersonalHolder(view);
                break;
        }

        return  holder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        ChatPersonal mObject = items.get(position);
        int itemViewType = getItemViewType(position);
        switch(itemViewType){
            case CHAT_RIGHT:
                ((ChatPersonalHolderSender) holder).mMENSAJE.setText(mObject.getMessage());
                ((ChatPersonalHolderSender) holder).mHORA.setText(DateUtils.getRelativeTimeSpanString(mObject.getHour()));
                break;
            case CHAT_LEFT:
                ((ChatPersonalHolder) holder).mMENSAJE.setText(mObject.getMessage());
                ((ChatPersonalHolder) holder).mHORA.setText(DateUtils.getRelativeTimeSpanString(mObject.getHour()));
                break;

        }
    }



    @Override
    public int getItemViewType(int position) {
        if(items.get(position).getId().equals(mId)){
            return CHAT_RIGHT;
        }else{
            return CHAT_LEFT;
        }
    }




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



}

这是我的chatClass的相关代码:

   @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_chat);


     linearLayoutManager = new LinearLayoutManager(ActivityChat.this);
            linearLayoutManager.setStackFromEnd(true);
            mRecyclerView.setLayoutManager(linearLayoutManager);
            mRecyclerView.setHasFixedSize(false);
            adapter = new ChatRecyclerAdapter(getApplicationContext(), items, mId);
            adapter.notifyDataSetChanged();
            mRecyclerView.setAdapter(adapter);




          // send message

        mSentMensaje.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final String message = mEditText.getText().toString();
                    if (!message.isEmpty()) {
                        mChat.setMessage(message);
                        mChat.setHour(System.currentTimeMillis());
                        mChat.setId(mId);

                        if(mUser != null){
                            if(mUser.getIDchat() != null){
                                FirebaseUtils.getCHATT(mUser.getIDchat()).push().setValue(mChat).addOnSuccessListener(ActivityChat.this, new OnSuccessListener<Void>() {
                                    @Override
                                    public void onSuccess(Void aVoid) {
                                        mRecyclerView.scrollToPosition(items.size() -1);
                                        adapter.notifyDataSetChanged();
                                        mEditText.setText("");
                                    }
                                });
                            }}


    // retreive message
        if(mUser != null){
        if(mUser.getIDchat() != null){
            FirebaseUtils.getCHATT(mUser.getIDchat()).limitToFirst(50).addChildEventListener(new ChildEventListener() {
                @Override
                public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                    if (dataSnapshot != null && dataSnapshot.getValue() != null) {
                        try{
                            ChatPersonal model = dataSnapshot.getValue(ChatPersonal.class);
                            items.add(model);
                        } catch (Exception ex) {
                            Log.e(TAG, ex.getMessage());
                        }
                    }
                }

                @Override
                public void onChildChanged(DataSnapshot dataSnapshot, String s) {

                }

                @Override
                public void onChildRemoved(DataSnapshot dataSnapshot) {

                }

                @Override
                public void onChildMoved(DataSnapshot dataSnapshot, String s) {

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
        }




// status

 @Override
protected void onStart() {
    super.onStart();

    adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
        @Override
        public void onChanged() {
            super.onChanged();
            mRecyclerView.scrollToPosition(adapter.getItemCount() - 1);
        }
    });


}

@Override
protected void onResume() {
    super.onResume();
    adapter.notifyDataSetChanged();

}

@Override
protected void onPostResume() {
    super.onPostResume();
    adapter.notifyDataSetChanged();
}



  }

1 个答案:

答案 0 :(得分:0)

如果您希望数据自动与Firebase同步,则需要使用FirebaseRecyclerAdapter 参考:https://github.com/firebase/FirebaseUI-Android/blob/master/database/src/main/java/com/firebase/ui/database/FirebaseRecyclerAdapter.java