java.lang.IndexOutOfBoundsException:检测到不一致。视图持有者适配器positionViewHolder

时间:2018-05-23 07:51:36

标签: android android-recyclerview indexoutofboundsexception

有很多人遇到过这个例外,我尝试过这个例外的可用解决方案,但实际上没有一个能适用于我的情况。

所以我的问题是我的工具栏上有一个过滤器按钮,里面有三个项目1.升序,2。降序,3。具体日期。当我选择升序和降序项目时,数据会在recyclerview内正确填充。但是当我选择日期特定选项并显示一个日期选择器....数据没有填充在recyclerview内部,当我触摸屏应用程序崩溃并给我上述异常时。

我执行这些操作的片段代码: -

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();


    }



}

以下是我的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)

1 个答案:

答案 0 :(得分:1)

在选择日期选择器时,只需执行一项操作,然后在调用main函数之前添加这些行。

onClick

{

 adapter.notifyDataSetChanged();

 recyclerView.getRecycledViewPool().clear();


and then the rest code....


}