Search code examples
androidandroid-recyclerviewindexoutofboundsexception

java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder


So many people have faced this exception and i tried the solutions available for this exception but none of it actually worked for my case.

So my problem is i have a filter button at my toolbar and it has three items in it 1. ascending order , 2. descending order , 3. date specific. when i am selecting ascending and descending items data is getting populated correctly inside recyclerview. but when i am selecting the date specific option and showing a datepicker ....the data is not getting populated inside recyclerview and when i touch screen application gets crashed and gives me the above mentioned exception.

my code for fragment where i am performing these operations :-

public class PendingOrders extends Fragment {

    String filterString="date_desc";
    String filterDateString="";
    private int mDay,mMonth,mYear;
    private static final String TAG = "PendingORDERS";

    private RecyclerView mMessagesView;
    private List<PendingOrderModel> mMessages = new ArrayList<PendingOrderModel>();
    CustomItemClickListener listener;
    private PendingOrderAdapter mAdapter;
    private Socket mSocket;
    private Boolean isConnected = true;

    public static final int DIALOG_FRAGMENT = 1;


    String actualPrice,amount,total,filledAmount,orderPrice,proceeds,orderDate,orderType,orderId;
    String currencyname,order,order1,orderType1 , orderDate1,idz;



    public PendingOrders() {
    }



    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mAdapter = new PendingOrderAdapter(context, mMessages,listener);
        if (context instanceof Activity) {

        }
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setHasOptionsMenu(true);
        AppController app = (AppController) getActivity().getApplication();

        SharedPreferences pref = getActivity().getSharedPreferences("MyPREFERENCES", 0);
        idz=pref.getString("ZuserID", null);

        mSocket = app.getSocket();


        mSocket.on("pending_orders_data", orderCompletedData);
        mSocket.connect();


    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_pending_orders, container, false);
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);


        mMessagesView = (RecyclerView) view.findViewById(R.id.rv_pending_orders);

        mMessagesView.setLayoutManager(new LinearLayoutManager(getActivity()));



        mMessagesView.setItemAnimator(null);


        mAdapter =  new PendingOrderAdapter(getActivity(), mMessages, new CustomItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {



                String orderid = mMessages.get(position).getmOrderId();



                FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
                Fragment prev = getActivity().getSupportFragmentManager().findFragmentByTag("dialog");
                if (prev != null) {
                    ft.remove(prev);
                }
                ft.addToBackStack(null);
                DialogFragment dialogFrag = PendingCancelDialog.newInstance(123);
                dialogFrag.show(getActivity().getFragmentManager().beginTransaction(), "dialog");
                Bundle args =  new Bundle();
                args.putString("ID",orderid);
                dialogFrag.setArguments(args);





            }
        });


        mMessagesView.setAdapter(mAdapter);






        initObjects();

    }





    private void initObjects() {






        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("user_id", idz);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        mSocket.emit("register_user", jsonObject.toString());


        mSocket.emit("fetch_pending_orders", getSendMessageString(""));




    }




    public String getSendMessageString(String message) {
        try {

            JSONObject jsonObject = new JSONObject();

            jsonObject.put("page_no", "1"); //1: text message 2: multimedia message
            jsonObject.put("user_id", idz);
            jsonObject.put("records_per_page", "5");
            jsonObject.put("filter", filterString);

            Log.i("??", "filterString: "+filterString);

            jsonObject.put("filter_date", filterDateString);

            Log.i("??", "filterDateString: "+filterDateString);

            return jsonObject.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return message;
    }





    private void addMessage(String orderId,String order,String currencyname,String amount,String filledAmount,String proceeds,String orderPrice,String orderDate,String orderType) {


        mMessages.add(new PendingOrderModel.Builder(PendingOrderModel.RECEIVER)
                .orderid(orderId).order(order).amount(amount).currencyname(currencyname).filledamount(filledAmount).orderprice(orderPrice).proceeds(proceeds).orderdate(orderDate).ordertype(orderType).build());


        mMessagesView.getRecycledViewPool().clear();
        mAdapter.notifyDataSetChanged();




    }



    private Emitter.Listener orderCompletedData = new Emitter.Listener() {



        @Override
        public void call(final Object... args) {




            if(getActivity() != null) {
                getActivity().runOnUiThread(() -> {


                    JSONArray object1 = (JSONArray) args[0];

                    if(object1 != null){


                        JSONArray array = new JSONArray();

                        array = object1.optJSONArray(0);

                        int arraylength = array.length();

                        for(int j=0; j<array.length();j++){


                            JSONObject obj = new JSONObject();
                            try {
                                obj = array.getJSONObject(j);

                                currencyname = obj.getString("coin");
                                orderId = obj.getString("id");
                                order1 = obj.getString("order");
                                filledAmount = obj.getString("coin_quantity");
                                amount = obj.getString("total_amount");
                                proceeds = obj.getString("remaining");
                                orderPrice = obj.getString("order_price");
                                orderDate1 = obj.getString("create_time");
                                orderType1= obj.getString("order_type");




                            } catch (JSONException e) {
                                e.printStackTrace();
                            }


                            if(order1 == "1"){

                                order = "Limit";

                            }
                            else{

                                order = "Market";
                            }


                            if(orderType1 == "1"){


                                orderType = "Sell";
                            }else{

                                orderType = "buy";
                            }


                            String [] date = orderDate1.split("T");

                            orderDate = date[0].trim();



                            addMessage(orderId,order,currencyname,amount,filledAmount,proceeds,orderPrice,orderDate,orderType);




                        }
                    }
                });
            }
        }

    };



    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.asc_order:
                filterString="date asc";
                filterDateString="";
                mMessages.clear();
                mSocket.emit("fetch_pending_orders", getSendMessageString(""));

                return true;
            case R.id.desc_order:
                filterString="date desc";
                mMessages.clear();
                mSocket.emit("fetch_pending_orders", getSendMessageString(""));

                return true;
            case R.id.pick_date:
                filterString="date specific";
                mMessages.clear();
                pickdate();
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void pickdate() {


        Calendar c1 = Calendar.getInstance();
        mYear = c1.get(Calendar.YEAR);
        mMonth = c1.get(Calendar.MONTH);
        mDay = c1.get(Calendar.DAY_OF_MONTH);






        DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(),R.style.DAte_Theme,
                (view, year, monthOfYear, dayOfMonth) -> {



                    int month = monthOfYear + 1;
                    String formattedMonth = "" + month;
                    String formattedDayOfMonth = "" + dayOfMonth;


                    if(month < 10){

                        formattedMonth = "0" + month;
                    }
                    if(dayOfMonth < 10){

                        formattedDayOfMonth = "0" + dayOfMonth;
                    }


                    filterDateString= formattedDayOfMonth + "/" + formattedMonth + "/" + year;

                    Log.i("date",filterDateString);

                    mSocket.emit("fetch_pending_orders", getSendMessageString(""));
//                    updateDate(filterDateString);

                }, mYear, mMonth, mDay);
        datePickerDialog.show();


    }



}

Below is my Logcat :-

  java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder{cfdb59c position=3 id=-1, oldPos=-1, pLpos:-1 no parent} android.support.v7.widget.RecyclerView{476168c VFED..... .F...... 0,0-1080,1560 #7f090169 app:id/rv_pending_orders}, adapter:com.vamediabox.greenpay.adapters.PendingOrderAdapter@d6e71d5, layout:android.support.v7.widget.LinearLayoutManager@e738dea, context:com.vamediabox.greenpay.activities.MyorderActivity@70a64f9
        at android.support.v7.widget.RecyclerView$Recycler.validateViewHolderForOffsetPosition(RecyclerView.java:5421)
        at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5603)
        at android.support.v7.widget.GapWorker.prefetchPositionWithDeadline(GapWorker.java:285)
        at android.support.v7.widget.GapWorker.flushTaskWithDeadline(GapWorker.java:342)
        at android.support.v7.widget.GapWorker.flushTasksWithDeadline(GapWorker.java:358)
        at android.support.v7.widget.GapWorker.prefetch(GapWorker.java:365)
        at android.support.v7.widget.GapWorker.run(GapWorker.java:396)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Solution

  • See just do one thing when you select the date picker then add these lines before calling the main function.

    onClick
    
    {
    
     adapter.notifyDataSetChanged();
    
     recyclerView.getRecycledViewPool().clear();
    
    
    and then the rest code....
    
    
    }