Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.NullPointerException: Attempt to write to field 'int android.support.v7.widget.RecyclerView

Tags:

java

android

I don't know what the problem is can some one help me it's a problem with my recycler view I am getting valus from a retrofit web service then applying it to the adapter

this is my main code

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

        imgAttachment=(ImageView)findViewById(R.id.img_attachment);
        imgSend=(ImageView)findViewById(R.id.img_send);
        etMessage=(EditText)findViewById(R.id.et_message);

        //get user data
        UserPhone userPhone=new UserPhone();
        userPhone.phone=getIntent().getExtras().getString("receiverNumber");
        WebService.getInstance().getApi().getUserData(userPhone).enqueue(new Callback<UserDataResponse>() {
            @Override
            public void onResponse(Call<UserDataResponse> call, Response<UserDataResponse> response) {
                receiverId=response.body().getUserId();
                AllMessages allMessages=new AllMessages();
                allMessages.receiverID=receiverId;
                allMessages.senderID=MainActivity.userId;
                WebService.getInstance().getApi().getMessages(allMessages).enqueue(new Callback<List<Message>>() {
                    @Override
                    public void onResponse(Call<List<Message>> call, Response<List<Message>> response) {
                        messages=response.body();
                        recyclerChat=(RecyclerView)findViewById(R.id.recycler_chat);
                        LinearLayoutManager layoutManager = new LinearLayoutManager(ChatActivity.this);
                        recyclerChat.setLayoutManager(layoutManager);
                        adapter=new MessagingAdapter(messages,ChatActivity.this);
                        recyclerChat.setAdapter(adapter);
                        recyclerChat.scrollToPosition(messages.size()-1);

                    }

                    @Override
                    public void onFailure(Call<List<Message>> call, Throwable t) {
                    }
                });
            }

            @Override
            public void onFailure(Call<UserDataResponse> call, Throwable t) {

            }
        });
        //end of get user data

    }

this is my logcat

06-20 11:01:09.680 27852-27852/net.paymac.chatty D/ViewRootImpl: ViewPostImeInputStage processPointer 0
06-20 11:01:09.700 27852-27852/net.paymac.chatty D/ViewRootImpl: ViewPostImeInputStage processPointer 1
06-20 11:01:09.710 27852-27852/net.paymac.chatty I/Timeline: Timeline: Activity_launch_request id:net.paymac.chatty time:91556150
06-20 11:01:09.730 27852-27893/net.paymac.chatty D/FA: Logging event (FE): _e, Bundle[{_o=auto, _et=9473, _sc=MainActivity, _si=4899456373428156394}]
06-20 11:01:09.890 27852-27852/net.paymac.chatty D/SecWifiDisplayUtil: Metadata value : none
06-20 11:01:09.890 27852-27852/net.paymac.chatty D/ViewRootImpl: #1 mView = com.android.internal.policy.PhoneWindow$DecorView{b89463c I.E...... R.....ID 0,0-0,0}
06-20 11:01:09.960 27852-27852/net.paymac.chatty E/RecyclerView: No adapter attached; skipping layout
06-20 11:01:09.960 27852-27893/net.paymac.chatty D/FA: Connected to remote service
06-20 11:01:09.960 27852-27852/net.paymac.chatty D/ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 96 - 0, 0) vi=Rect(0, 96 - 0, 0) or=1
06-20 11:01:09.980 27852-27852/net.paymac.chatty E/RecyclerView: No adapter attached; skipping layout
06-20 11:01:09.980 27852-27852/net.paymac.chatty W/DisplayListCanvas: DisplayListCanvas is started on unbinded RenderNode (without mOwningView)
06-20 11:01:09.980 27852-27852/net.paymac.chatty W/DisplayListCanvas: DisplayListCanvas is started on unbinded RenderNode (without mOwningView)
06-20 11:01:10.240 27852-27852/net.paymac.chatty I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@675702f time:91556688
06-20 11:01:10.930 27852-27852/net.paymac.chatty D/AndroidRuntime: Shutting down VM
06-20 11:01:10.930 27852-27852/net.paymac.chatty E/AndroidRuntime: FATAL EXCEPTION: main
                                                                   Process: net.paymac.chatty, PID: 27852
                                                                   java.lang.NullPointerException: Attempt to write to field 'int android.support.v7.widget.RecyclerView$ViewHolder.mItemViewType' on a null object reference
                                                                       at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6368)
                                                                       at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5555)
                                                                       at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5440)
                                                                       at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5436)
                                                                       at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2224)
                                                                       at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1551)
                                                                       at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1511)
                                                                       at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:595)
                                                                       at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3583)
                                                                       at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:3025)
                                                                       at android.view.View.measure(View.java:20151)
                                                                       at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:716)
                                                                       at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:462)
                                                                       at android.view.View.measure(View.java:20151)
                                                                       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6328)
                                                                       at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
                                                                       at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
                                                                       at android.view.View.measure(View.java:20151)
                                                                       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6328)
                                                                       at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:393)
                                                                       at android.view.View.measure(View.java:20151)
                                                                       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6328)
                                                                       at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
                                                                       at android.view.View.measure(View.java:20151)
                                                                       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6328)
                                                                       at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
                                                                       at android.widget.LinearLayout.measureVertical(LinearLayout.java:747)
                                                                       at android.widget.LinearLayout.onMeasure(LinearLayout.java:629)
                                                                       at android.view.View.measure(View.java:20151)
                                                                       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6328)
                                                                       at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
                                                                       at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:3158)
                                                                       at android.view.View.measure(View.java:20151)
                                                                       at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2594)
                                                                       at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1549)
                                                                       at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1841)
                                                                       at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1437)
                                                                       at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7397)
                                                                       at android.view.Choreographer$CallbackRecord.run(Choreographer.java:920)
                                                                       at android.view.Choreographer.doCallbacks(Choreographer.java:695)
                                                                       at android.view.Choreographer.doFrame(Choreographer.java:631)
                                                                       at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:906)
                                                                       at android.os.Handler.handleCallback(Handler.java:739)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                       at android.os.Looper.loop(Looper.java:158)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:7225)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

my adapter

public class MessagingAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private List<Message> messages;
    private Context context;

    /**
     * Constructor for Adapter
     *
     * @param messages list of messages will showed
     * @param context  context
     */
    public MessagingAdapter(List<Message> messages, Context context) {
        this.messages = messages;
        this.context = context;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        /**
         * check the type of view and return holder
         */
        if (viewType == MessageType.SENT_TEXT) {
            return new SentTextHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.message_sent, parent, false));
        } else if (viewType == MessageType.SENT_IMAGE) {
            return new SentImageHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.message_sent_img, parent, false));
        } else if (viewType == MessageType.RECEIVED_TEXT) {
            return new ReceivedTextHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.message_recieved, parent, false));
        } else if (viewType == MessageType.RECEIVED_IMAGE) {
            return new ReceivedImageHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.message_received_img, parent, false));
        }

        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder mHolder, int position) {

        int type = getItemViewType(position);
        Message message = messages.get(position);
        /**
         * check message type and init holder to user it and set data in the right place for every view
         */
        if (type == MessageType.SENT_TEXT) {
            SentTextHolder holder = (SentTextHolder) mHolder;
            holder.tvTime.setText(message.getTime());
            holder.tvMessageContent.setText(message.getContent());

        } else if (type == MessageType.SENT_IMAGE) {
            //SentImageHolder holder = (SentImageHolder) mHolder;
            //holder.tvTime.setText(message.getTime());
            //Glide.with(context).load(Urls.IMAGES_URL + message.getContent()).into(holder.imgMsg);


        } else if (type == MessageType.RECEIVED_TEXT) {
            ReceivedTextHolder holder = (ReceivedTextHolder) mHolder;
            holder.tvTime.setText(message.getTime());
            holder.tvMessageContent.setText(message.getContent());


        } else if (type == MessageType.RECEIVED_IMAGE) {
            //ReceivedImageHolder holder = (ReceivedImageHolder) mHolder;
            //holder.tvTime.setText(message.getTime());
            //holder.tvUsername.setText(message.getUsername());
            //Glide.with(context).load(Urls.IMAGES_URL + message.getContent()).into(holder.imgMsg);

        }

    }


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

    @Override
    public int getItemViewType(int position) {
        /**
         * check the user id to detect if message sent or received
         * then check if message is text or img
         */

        String userID = MainActivity.userId;
        Message message = messages.get(position);

        if (userID == message.getUserId()) {

            if (message.getType().equals("1")) {
                return MessageType.SENT_TEXT;
            } else if (message.getType().equals("2")) {
                return MessageType.SENT_IMAGE;
            }

        } else {

            if (message.getType().equals("1")) {
                return MessageType.RECEIVED_TEXT;
            } else if (message.getType().equals("2")) {
                return MessageType.RECEIVED_IMAGE;
            }

        }
        return super.getItemViewType(position);
    }

    // sent message holders
    class SentMessageHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.tv_time)
        TextView tvTime;

        public SentMessageHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    // sent message with type text
    class SentTextHolder extends SentMessageHolder {
        @BindView(R.id.tv_message_content)
        TextView tvMessageContent;

        public SentTextHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);

        }
    }

    // sent message with type image
    class SentImageHolder extends SentMessageHolder {
        @BindView(R.id.img_msg)
        ImageView imgMsg;

        public SentImageHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    // received message holders
    class ReceivedMessageHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.tv_username)
        TextView tvUsername;
        @BindView(R.id.tv_time)
        TextView tvTime;

        public ReceivedMessageHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    // received message with type text
    class ReceivedTextHolder extends ReceivedMessageHolder {
        @BindView(R.id.tv_message_content)
        TextView tvMessageContent;

        public ReceivedTextHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    // received message with type image

    class ReceivedImageHolder extends ReceivedMessageHolder {
        @BindView(R.id.img_msg)
        ImageView imgMsg;

        public ReceivedImageHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }


}
like image 950
RealDEV Avatar asked Nov 30 '22 15:11

RealDEV


1 Answers

Your probably returning a null on onCreateViewHolder on your adapter class

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    /**
     * check the type of view and return holder
     */
    if (viewType == MessageType.SENT_TEXT) {
        return new SentTextHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.message_sent, parent, false));
    } else if (viewType == MessageType.SENT_IMAGE) {
        return new SentImageHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.message_sent_img, parent, false));
    } else if (viewType == MessageType.RECEIVED_TEXT) {
        return new ReceivedTextHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.message_recieved, parent, false));
    } else if (viewType == MessageType.RECEIVED_IMAGE) {
        return new ReceivedImageHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.message_received_img, parent, false));
    }

    return null; // This shouldn't return null in any case or error 
                 // will be thrown.

}
like image 113
Ahmad Moussa Avatar answered Dec 04 '22 12:12

Ahmad Moussa