2

I am doing chat application. I am using Recyclerview to show the chat to users. If I add a new item to the Recyclerview I am facing two issues. First one is onBindViewHolder is not working second one is scrollToPosition is not working. Sometimes it's working properly but sometimes I am getting these issue's again and again.

Here I have added the initialisation of RecyclerView

compile 'com.android.support:recyclerview-v7:23.2.0'

LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(mLayoutManager);
        ArrayList<String> as = cd.messagesid(dialog.getDialogId());
        adapter = new ChatAdapter(_activity, cd.messages(dialog.getDialogId()), as);
        recyclerView.setAdapter(adapter);

I am using below method in adapter page to add a new item.

public void add(QBChatMessage qb) {
        chatMessages.add(qb);
        messageidis.add(qb.getId());
        notifyItemInserted(chatMessages.size() - 1);

    }

I am using below methods to add item into the recyclerview and to scroll down the recyclerview.

private void scrollDown() {
    //  messagesContainer.scrollToPosition(adapter.getItemCount() - 1);
    //   messagesContainer.smoothScrollToPosition(adapter.getItemCount() - 1);
    messagesContainer.scrollToPosition(adapter.getItemCount() - 1);
}

 Boolean cc = cd.Insert_tbl_chathistory(msg.getDialogId(), msg.getSenderId() + "", msg.getBody(), msg.getId() + "", msg.getDateSent(), "", msg.getReadIds() + "", msg.getDeliveredIds() + "", msg.getRecipientId() + "", 1, 0, "");
            if (cc) {
                msg.setProperty("SenderID", msg.getSenderId() + "");

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter.add(msg);
                        scrollDown();
                    }
                });
            }

It's an My activity xml file

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent"
    android:fitsSystemWindows="true">


    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/transparent"
        android:orientation="vertical">

        <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            android:minHeight="?attr/actionBarSize"
            app:navigationContentDescription="@string/abc_action_bar_up_description"
            app:navigationIcon="?attr/homeAsUpIndicator"
            app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">


            <com.chatapp.contacts.CircleImageView
                android:id="@+id/usericon"
                android:layout_width="?attr/actionBarSize"
                android:layout_height="?attr/actionBarSize"
                android:background="@color/colorPrimary"
                android:src="@drawable/ic_profile" />

            <com.chatapp.widgets.MaterialRippleLayout
                style="@style/RippleStyle"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="center_vertical"
                android:layout_toRightOf="@+id/usericon"
                android:focusable="false"
                android:gravity="center_vertical"
                app:rippleColor="@color/main_color_grey_400">


                <RelativeLayout
                    android:id="@+id/chat_details"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="center_vertical"
                    android:gravity="center_vertical"
                    android:paddingRight="5dp">

                    <com.chatapp.font.RobotoTextView
                        android:id="@+id/toolbar_title"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="@dimen/margin_middle"

                        android:minWidth="122dp"
                        android:paddingBottom="@dimen/cpb_stroke_width"
                        android:text=""
                        android:textAppearance="?android:textAppearanceMedium"
                        android:textColor="@color/white" />

                    <com.chatapp.font.RobotoTextView
                        android:id="@+id/toolbar_typing"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/toolbar_title"
                        android:layout_marginLeft="@dimen/margin_middle"
                        android:minWidth="122dp"
                        android:text=""
                        android:textColor="@color/white" />
                </RelativeLayout>
            </com.pluggdd.corporate.chatapp.widgets.MaterialRippleLayout>

        </android.support.v7.widget.Toolbar>

        <vc908.stickerfactory.ui.view.KeyboardHandleRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/sizeNotifierLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <RelativeLayout
                android:id="@+id/container"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

                <RelativeLayout
                    android:id="@+id/bottom"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentBottom="true"
                    android:background="#fff">

                    <com.chatapp.font.RobotoEditText
                        android:id="@+id/messageEdit"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_above="@+id/sticker_image"
                        android:layout_alignTop="@+id/sticker_image"
                        android:background="#fff"
                        android:hint=" Message text"
                        android:inputType="textMultiLine|textCapSentences"
                        android:maxLines="6"
                        android:paddingBottom="10dp"
                        android:paddingLeft="5dp"
                        android:scrollbars="vertical" />

                    <android.support.design.widget.FloatingActionButton
                        android:id="@+id/chatSendButton"
                        style="@style/Fabsend"
                        android:layout_alignParentRight="true"
                        android:layout_below="@+id/messageEdit"
                        android:layout_marginBottom="3dp"
                        android:layout_marginRight="10dp"
                        app:layout_anchor="@+id/container" />

                    <ImageView
                        android:id="@+id/stickers_button"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignBottom="@+id/chatSendButton"
                        android:layout_alignParentLeft="true"
                        android:layout_alignTop="@+id/chatSendButton"
                        android:layout_below="@+id/messageEdit"
                        android:paddingLeft="5dp"
                        android:paddingRight="5dp"
                        android:src="@drawable/smile_icon_24p"
                        android:tint="@color/colorPrimary" />

                    <ImageView
                        android:id="@+id/attach_button"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignBottom="@+id/chatSendButton"
                        android:layout_alignTop="@+id/chatSendButton"
                        android:layout_below="@+id/messageEdit"
                        android:layout_toRightOf="@+id/stickers_button"
                        android:paddingLeft="5dp"
                        android:paddingRight="5dp"
                        android:src="@drawable/imageshare_icon_24p"
                        android:tint="@color/colorPrimary" />

                    <ImageView
                        android:id="@+id/videoshare_button"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignBottom="@+id/chatSendButton"
                        android:layout_alignTop="@+id/chatSendButton"
                        android:layout_below="@+id/messageEdit"
                        android:layout_toRightOf="@+id/attach_button"
                        android:paddingLeft="5dp"
                        android:paddingRight="5dp"
                        android:src="@drawable/video_icon_24p"
                        android:tint="@color/colorPrimary" />

                    <ImageView
                        android:id="@+id/loc_button"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignBottom="@+id/chatSendButton"
                        android:layout_alignTop="@+id/chatSendButton"
                        android:layout_below="@+id/messageEdit"
                        android:layout_toRightOf="@+id/videoshare_button"
                        android:paddingLeft="5dp"
                        android:paddingRight="5dp"
                        android:src="@drawable/location_icon_24p"
                        android:tint="@color/colorPrimary" />
                </RelativeLayout>

                <android.support.v7.widget.RecyclerView
                    android:id="@+id/messagesContainer"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_above="@+id/bottom"
                    android:layout_alignParentLeft="false"
                    android:layout_alignParentTop="false"
                    android:background="@android:color/transparent"
                    android:divider="@null"
                    android:listSelector="@android:color/transparent"
                    android:stackFromBottom="true"
                    android:transcriptMode="alwaysScroll"/>


            </RelativeLayout>

            <FrameLayout
                android:id="@+id/frame"
                android:layout_width="match_parent"
                android:layout_height="240dp"
                android:layout_alignParentBottom="true" />
        </vc908.stickerfactory.ui.view.KeyboardHandleRelativeLayout>
    </LinearLayout>
</android.support.design.widget.CoordinatorLayout>

Here I have added my adapter xml file

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toplayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?android:attr/selectableItemBackground"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/txtInfo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_gravity="center_horizontal"
            android:background="@drawable/roundedcornermsg"
            android:gravity="center"
            android:textColor="@android:color/white" />

        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">


            <LinearLayout
                android:id="@+id/content"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:orientation="horizontal"
                android:weightSum="100">

                <TextView
                    android:id="@+id/front"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="20" />

                <LinearLayout
                    android:id="@+id/contentWithBackground"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="right"
                    android:layout_weight="80"
                    android:background="@drawable/redchat"
                    android:orientation="vertical">

                    <com.chatapp.font.RobotoTextView
                        android:id="@+id/personname"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentLeft="true"
                        android:paddingLeft="5dp"
                        android:paddingTop="5dp"
                        android:singleLine="true"
                        android:text="Mathankumar:"
                        android:textColor="@color/colorPrimary" />

                    <TextView
                        android:id="@+id/txtMessage"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="left"
                        android:autoLink="all"
                        android:minWidth="150dp"
                        android:paddingLeft="10dp"
                        android:textColor="@android:color/white" />

                    <RelativeLayout
                        android:id="@+id/chat_detnot"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:minWidth="160dp"
                        android:visibility="gone">

                        <ImageView
                            android:id="@+id/sticker_image"
                            android:layout_width="160dp"
                            android:layout_height="160dp"
                            android:layout_gravity="left"
                            android:autoLink="all" />

                    </RelativeLayout>

                    <RelativeLayout
                        android:id="@+id/chat_det"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:minWidth="160dp"
                        android:visibility="gone">

                        <com.chatapp.widgets.SquareImageView
                            android:id="@+id/imgView"
                            android:layout_width="200dp"
                            android:layout_height="200dp"
                            android:layout_alignParentLeft="true"
                            android:layout_gravity="left"
                            android:autoLink="all"
                            android:scaleType="centerCrop" />

                        <com.chatapp.circularprogressbar.CircularProgressButton
                            android:id="@+id/circular_progress_bar_1"
                            style="@style/CircularProgressBarStyle.3"
                            android:layout_centerInParent="true" />
                    </RelativeLayout>

                    <RelativeLayout
                        android:id="@+id/rlayouts"
                        android:layout_width="match_parent"
                        android:layout_height="20dp"
                        android:background="#80000000"
                        android:gravity="center_vertical"
                        android:minWidth="160dp">

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:gravity="right|center_vertical"
                            android:layout_alignParentRight="true">

                            <TextView
                                android:id="@+id/time"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:gravity="center_vertical"
                                android:text="12.32"
                                android:textColor="@color/white"
                                android:paddingRight="@dimen/spacing_medium"
                                android:textSize="10dp" />

                            <ImageView
                                android:id="@+id/msgstatus"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_alignBottom="@+id/time"
                                android:layout_alignTop="@+id/time"
                                android:src="@drawable/ic_eye_icon_unread"
                                android:visibility="visible" />
                        </LinearLayout>
                    </RelativeLayout>

                </LinearLayout>

            </LinearLayout>

        </RelativeLayout>
    </LinearLayout>

</FrameLayout>

Here I have added my adapter Java file

 public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.MyViewHolder> implements View.OnClickListener, Target {

   //Initialisation for objects

        public QBChatMessage getItem(int position) {
            if (chatMessages != null) {
                return chatMessages.get(position);
            } else {
                return null;
            }
        }

        public Float imagefloatsize;
        public int Imageintsize;


        public ChatAdapter(ChatActivity context, List<QBChatMessage> chatMessages, ArrayList<String> val) {
            this.context = context;
            this.chatMessages = chatMessages;
            messageidis = val;
            blurTransformation = new BlurTransformation(context, BLUR_RADIUS);
            mRequestQueue = Volley.newRequestQueue(context);
            baseurl = context.getString(R.string.baseurl);
            downloadurl = context.getString(R.string.downloadlink);
            appname = context.getString(R.string.app_name);
            //This Declaration is used to show the Application Crash Reports for Android
            Thread.setDefaultUncaughtExceptionHandler(new ACRA_Page(context));
            imagefloatsize = convertDpToPixel(200, context);
            Imageintsize = Math.round(imagefloatsize);
        }


        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int position) {

            return new MyViewHolder(LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.chat_rv_adapter, parent, false), isFile(getItem(position).getBody()));


        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            QBChatMessage chatMessage = getItem(position);

            final MyViewHolder vs = holder;
            String Showmsg = chatMessage.getProperty("showmsg").toString();
            // int SenderID = Integer.parseInt(chatMessage.getProperty("SenderID").toString());
            senderID = chatMessage.getProperty("SenderID").toString();
            String val[] = Showmsg.split("Mathan%nahtam&idhaya");
            holder.personame.setTag("" + position);
            String sz = val[0];
            boolean isOutgoing = false;

            if (sz.equalsIgnoreCase("1") || senderID == null || senderID.equals(userid + "")) {
                isOutgoing = true;
            } else {
                isOutgoing = false;
            }
            lastPosition = position;
            //  isOutgoing = chatMessage.getSenderId() == null || chatMessage.getSenderId().equals(currentUser.getId());
            setAlignment(holder, isOutgoing, chatMessage);
            holder.rlayouts.setTag(chatMessage);
            holder.txt_undotext.setTextSize(10);
            holder.txt_undoappicon_48.setTextSize(15);
            holder.txt_delete.setTextSize(15);
            holder.txtMessage.setText(Html.fromHtml("" + chatMessage.getBody() + ""
            ));
            holder.time.setTag("1");
            holder.circular_progress_bar_1.setVisibility(View.GONE);
            holder.time.setText(Html.fromHtml("<small>" + getTimeText(chatMessage)
            ));
            String s = getDateText(chatMessage);
            if (position == 0) {
                holder.txtInfo.setVisibility(View.VISIBLE);
                holder.txtInfo.setText(Html.fromHtml("<small>" + s
                ));
            } else {

            }

        }


        private void setAlignment(MyViewHolder holder, boolean isOutgoing, final QBChatMessage qb) {
            if (isOutgoing) {
                if (isFile(qb.getBody())) {
                        holder.contentWithBG.setBackgroundResource(R.drawable.bluechat);
                        layoutParams = (LinearLayout.LayoutParams) holder.chat_det.getLayoutParams();
                        layoutParams.gravity = Gravity.LEFT;
                        holder.chat_det.setLayoutParams(layoutParams);
                        holder.time.setTextColor(Color.parseColor("#ffffff"));
                } else {
                    holder.contentWithBG.setBackgroundResource(R.drawable.bluechat);
                    layoutParams = (LinearLayout.LayoutParams) holder.txtMessage.getLayoutParams();
                    layoutParams.gravity = Gravity.LEFT;
                    holder.contentWithBG.setMinimumWidth(160);
                    holder.txtMessage.setLayoutParams(layoutParams);
                    holder.txtMessage.setTextColor(Color.parseColor("#ffffff"));
                    holder.time.setTextColor(Color.parseColor("#ffffff"));
                }
            } else {
                if (context.dialog.getType().equals(QBDialogType.GROUP)) {
                    holder.personame.setVisibility(View.VISIBLE);
                    if (name.equals("#@Unknown*&%*")) {
                        QBUser user = ChatService.getInstance().getDialogsUsers().get(Integer.parseInt(senderID));
                        holder.personame.setText("" + user.getLogin().replace(ChatActivity.loginprefix, "") + " :");
                    } else {
                        holder.personame.setText("" + name + " :");
                    }
                } else {
                    if (qb.getReadIds().size() > 0) {
                        PrivateChatImpl.readstatus(qb);
                        holder.personame.setVisibility(View.GONE);
                        holder.contentWithBG.setBackgroundResource(R.drawable.whitechat);
                        layoutParams = (LinearLayout.LayoutParams) holder.chat_det.getLayoutParams();
                        layoutParams.gravity = Gravity.LEFT;
                        holder.chat_det.setLayoutParams(layoutParams);
                        holder.time.setTextColor(Color.parseColor("#ffffff"));

                    } else {
                        holder.contentWithBG.setMinimumWidth(160);
                        holder.contentWithBG.setBackgroundResource(R.drawable.whitechat);
                        layoutParams = (LinearLayout.LayoutParams) holder.txtMessage.getLayoutParams();
                        layoutParams.gravity = Gravity.LEFT;
                        layoutParams.setMargins(5, 0, 0, 0);
                        holder.txtMessage.setLayoutParams(layoutParams);
                        holder.txtMessage.setTextColor(Color.parseColor("#000000"));
                        holder.time.setTextColor(Color.parseColor("#000000"));
                    }
                }
            }
        }

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

        public void remove(int position) {
            chatMessages.remove(position);
            messageidis.remove(position);
            notifyItemRemoved(position);
        }

        public void add(QBChatMessage qb) {
            chatMessages.add(qb);
            messageidis.add(qb.getId());
            notifyItemInserted(chatMessages.size() - 1);
            //  notifyDataSetChanged();
        }


        static class MyViewHolder extends RecyclerView.ViewHolder {

            public TextView txtMessage, txtInfo, front, time;
            public LinearLayout content;
            public LinearLayout contentWithBG;
            public ImageView msgstatus;
            public ImageView sticker_image;
            public SquareImageView NimgView;
            public RobotoTextView personame, txt_undotext, txt_delete;
            public CircularProgressButton circular_progress_bar_1;
            public RelativeLayout rlayouts, chat_det, chat_detnot;
            public MaterialDesignIconsTextView txt_undoappicon_48;
            public FrameLayout toplayout;

            MyViewHolder(View v, Boolean s) {
                super(v);
    //Initialization for these objects
            }
        }

        @Override
        public void onClick(View v) {
            MyViewHolder holder1 = (MyViewHolder) v.getTag();
            //Access the Textview from holder1 like below
            int id = v.getId();

        }


    }

Can you please give me any solution to solve these issues.

MathankumarK
  • 2,717
  • 1
  • 17
  • 34
  • post your adapter code – H Raval Mar 05 '16 at 13:14
  • @HRaval I have added my adapter page please look on it. Sorry for the delay. – MathankumarK Mar 05 '16 at 13:37
  • @MathaN `notifyItemInserted(chatMessages.size() - 1);` should be `notifyItemInserted(chatMessages.size());`. It must must the position of the newly inserted item in the dataset. In this case since you are doing `chatMessages.add(qb)`, which effectively equals to append at the end of the list. Accordingly `messagesContainer.scrollToPosition(adapter.getItemCount() - 1);` should be `messagesContainer.scrollToPosition(adapter.getItemCount());`. Tell me if that works. – OneEyeQuestion Mar 28 '16 at 01:40
  • @OneEyeQuestion I tried this before asked this question but it's not worked. Also Issue is happened by the insert query. If call the insert query it's not working. Also query is working perfectly data is added to the database. If I removing the insert query onBindview is working. also If I add insert query inside the OnBindview that time also code is working If I call the insert query before I am inserting data into the adapter onBindviewHolder is not called. – MathankumarK Mar 28 '16 at 08:34

0 Answers0