首页 > 解决方案 > 重新填充时 RecyclerView 空对象引用错误

问题描述

我在第一次运行时遇到错误,RecyclerViewRecyclerView如果我再次按下 get_data 按钮以随机更改数据列表,它并不总是在第二次尝试时可能在第三次或第四次或第五次尝试时导致应用程序崩溃。错误也是随机的

Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView$LayoutManager.setExactMeasureSpecsFrom(android.support.v7.widget.RecyclerView)' on a null object reference

或者

RecyclerView$LayoutManager.onLayoutChildren(android.support.v7.widget.RecyclerView$Recycler, android.support.v7.widget.RecyclerView$State)' on a null object reference

等我无法找到确切的问题。

public class DCU_Reading_byTask extends Fragment implements View.OnClickListener {

    EditText taskid_edt;
    private APIInterface apiInterface;
    private ProgressDialog mProgressDialog;

    RecyclerView recycler_view_grid_meter_list;
    String DCU = "";
    String group_id, user_id;
    SharedPreferences pref;
    TextView textView_lat;
    Button Send_Data_btn, get_data_btn, back_btn;
    int send_counter = 0;

    DatabaseHandler databaseHandler;
    SharedPreferences.Editor editor;
    TextView Uart_read;
    WBInteraction wbInteraction;
    String URL = "Url here";
    ArrayList<dcumetedata> modelRecyclerArrayList;
    ArrayList<dcumetedata> sortedlist = new ArrayList<>();


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment;
        View view = inflater.inflate(R.layout.fragment_d_c_u__reading_by_task, container, false);
   
        find_view_by_id(view);
        set_on_click_litioner();
        pref = getActivity().getSharedPreferences("my_pref", MODE_PRIVATE);
        DCU = pref.getString("DCU_code", "DCU");
        textView_lat.setText("DCU no.: " + DCU);

       


        

        return view;
    }

    public void find_view_by_id(View view) {
        recycler_view_grid_meter_list = (RecyclerView) view.findViewById(R.id.recycler_view_grid_meter_list);
        textView_lat = (TextView) view.findViewById(R.id.textView_lat);
        Send_Data_btn = (Button) view.findViewById(R.id.Send_Data_btn);
        Uart_read = (TextView) view.findViewById(R.id.receivedatatxt);
        taskid_edt = (EditText) view.findViewById(R.id.taskid_edittext);
        get_data_btn = view.findViewById(R.id.get_data_btn);
        back_btn = view.findViewById(R.id.back_btn);


    }

    public void set_on_click_litioner() {
        Send_Data_btn.setOnClickListener(this);
        taskid_edt.setOnClickListener(this);
        get_data_btn.setOnClickListener(this);
        back_btn.setOnClickListener(this);
    }


    @SuppressLint("MissingPermission")
    public boolean isNetworkAvailable() {
        final android.net.ConnectivityManager connectivityManager = ((android.net.ConnectivityManager) getActivity().getSystemService(android.content.Context.CONNECTIVITY_SERVICE));
        return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            
  

            case R.id.get_data_btn:
                
      
                 if (taskid_edt.getText().toString().equals("")) {
                    Toast.makeText(getContext(), "Please Enter Task ID", Toast.LENGTH_SHORT).show();
                } else {
                    AsyncTask1 asyntask = new AsyncTask1();
                    asyntask.execute();
                }
                break;


            case R.id.Send_Data_btn:

                senddata();

                break;
        }
    }


    private class AsyncTask1 extends android.os.AsyncTask {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressDialog = new ProgressDialog(getContext());
            mProgressDialog.setMessage("Please wait...");
            mProgressDialog.setIndeterminate(true);
            mProgressDialog.setCancelable(false);
            mProgressDialog.show();

        }

        @Override
        protected Object doInBackground(Object[] objects) {
            ArrayList<String> wait = new ArrayList<String>();
            wait.add("PLEASE WAIT......");
            Empty_Adpater adapter = new Empty_Adpater(getContext(), wait);
            recycler_view_grid_meter_list.setAdapter(adapter);
            recycler_view_grid_meter_list.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));


            wbInteraction.GetDataList(getContext(), taskid_edt.getText().toString(), new WBInteraction.OnGetDataListener() {
                @Override
                public void onDataChanged(ArrayList<WBInteraction.meterData> list, String mes) {

                    if (!(list == null)) {
                        if (list.size() > 1) {


                             modelRecyclerArrayList = new ArrayList<dcumetedata>();
                            dcumetedata modelRecycler = new dcumetedata();
                            if (!(list == null)) {
                                int j = 0;
                                int count = list.size();
                                for (int i = 0; i < count; i++) {
                                    String device = list.get(i).getDeviceCode();
                                    Log.e("DCU: ", DCU);
                                    Log.e("device: ", device);

                                    if (device.equals(DCU)) {
                                        j++;


                                        modelRecycler.setAnalysis(list.get(i).getAnalysis());
                                        modelRecycler.setBattery(list.get(i).getBattery());
                                        modelRecycler.setCommType(list.get(i).getCommType());
                                        modelRecycler.setCommunicationAddress(list.get(i).getCommunicationAddress());
                                        modelRecycler.setDataStr(list.get(i).getDataStr());
                                        modelRecycler.setDeviceCode(list.get(i).getDeviceCode());
                                        modelRecycler.setFreezeDate(list.get(i).getFreezeDate());
                                        modelRecycler.setGasVolume(list.get(i).getGasVolume());
                                        modelRecycler.setMeterRTC(list.get(i).getMeterRTC());
                                        modelRecycler.setNetID(list.get(i).getNetID());
                                        modelRecycler.setRSSI(list.get(i).getRSSI());
                                        modelRecycler.setState(list.get(i).getState());
                                        modelRecycler.setDate(list.get(i).getDate().toString());

                                        modelRecyclerArrayList.add(modelRecycler);

                                    }

                                }
                                if (j == 0) {
                     Toast.makeText(getContext(), "No data for this DCU no.", Toast.LENGTH_LONG).show();
                                }
                      DCUListAdapter adapter = new DCUListAdapter(getContext(), modelRecyclerArrayList);
                                recycler_view_grid_meter_list.setAdapter(adapter);
                                recycler_view_grid_meter_list.setLayoutManager(new 
                                LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));


                            }


                               
                        } else {
                            ArrayList<dcumetedata> modelRecyclerArrayList = new ArrayList<dcumetedata>();
                            DCUListAdapter adapter = new DCUListAdapter(getContext(), modelRecyclerArrayList);
                            recycler_view_grid_meter_list.setAdapter(adapter);
                            recycler_view_grid_meter_list.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));

                            Toast.makeText(getContext(), "No Data", Toast.LENGTH_SHORT).show();
                        }


                    } else {
                        ArrayList<dcumetedata> modelRecyclerArrayList = new ArrayList<dcumetedata>();
                        DCUListAdapter adapter = new DCUListAdapter(getContext(), modelRecyclerArrayList);
                        recycler_view_grid_meter_list.setAdapter(adapter);
                        recycler_view_grid_meter_list.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));

                        Toast.makeText(getContext(), "No Data", Toast.LENGTH_SHORT).show();
                        Log.e("Data List is null", "");

                    }

                }
            });


            return null;
        }


        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            mProgressDialog.dismiss();
        }
    }

    
}

回收适配器:

public class DCUListAdapter extends  RecyclerView.Adapter<DCUListAdapter.viewholder> {
    private LayoutInflater inflater;
    private ArrayList<dcumetedata> dataModelArrayList;

    public DCUListAdapter(Context ctx, ArrayList<dcumetedata> dataModelArrayList) {

        inflater = LayoutInflater.from(ctx);
        this.dataModelArrayList = dataModelArrayList;

    }

    @NonNull
    @Override
    public viewholder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = inflater.inflate(R.layout.recyler_item, viewGroup, false);
        viewholder holder = new viewholder(view);

        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull viewholder viewholder, int i) {
        viewholder.Analysis.setText("Analysis:" + dataModelArrayList.get(i).getAnalysis());
        viewholder.Battery.setText("Battery: " + dataModelArrayList.get(i).getBattery());
        viewholder.CommType.setText("Comm. Type: " + dataModelArrayList.get(i).getCommType());
        viewholder.CommunicationAddres.setText("Comm. Addrs: " + dataModelArrayList.get(i).getCommunicationAddress());
        viewholder.DataSt.setText("Data: " + dataModelArrayList.get(i).getDataStr());
        viewholder.Date.setText("Date: " + dataModelArrayList.get(i).getDate());
        viewholder.DeviceCode.setText("DCU no.: " + dataModelArrayList.get(i).getDeviceCode());
        viewholder.FreezeDate.setText("Freeze Data: " + dataModelArrayList.get(i).getFreezeDate());
        viewholder.GasVolume.setText("Gas Vol.: " + dataModelArrayList.get(i).getGasVolume());
        viewholder.MeterRTC.setText("Meter RTC: " + dataModelArrayList.get(i).getMeterRTC());
        viewholder.NetID.setText("Net ID: " + dataModelArrayList.get(i).getNetID());
        viewholder.RSSI.setText("RSSI: " + dataModelArrayList.get(i).getRSSI());
        viewholder.State.setText("State: " + dataModelArrayList.get(i).getState());

    }


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


    class viewholder extends RecyclerView.ViewHolder {

        TextView Analysis, Battery, CommType, CommunicationAddres, DataSt,Date,DeviceCode,FreezeDate,GasVolume,MeterRTC,NetID,RSSI,State;


        public viewholder(@NonNull View itemView) {
            super(itemView);
            Analysis = (TextView) itemView.findViewById(R.id.Analysis);
            Battery = (TextView) itemView.findViewById(R.id.Battery);
            CommunicationAddres = (TextView) itemView.findViewById(R.id.CommunicationAddres);
            DataSt = (TextView) itemView.findViewById(R.id.DataSt);
            Date = (TextView) itemView.findViewById(R.id.Date);
            DeviceCode = (TextView) itemView.findViewById(R.id.DeviceCode);
            FreezeDate = (TextView) itemView.findViewById(R.id.FreezeDate);
            GasVolume = (TextView) itemView.findViewById(R.id.GasVolume);
            MeterRTC = (TextView) itemView.findViewById(R.id.MeterRTC);
            NetID = (TextView) itemView.findViewById(R.id.NetID);
            RSSI = (TextView) itemView.findViewById(R.id.RSSI);
            State = (TextView) itemView.findViewById(R.id.State);
            CommType = (TextView) itemView.findViewById(R.id.CommType);


        }
    }




}

recycler_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="wrap_content">


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



        <android.support.v7.widget.CardView
            android:id="@+id/card_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            app:cardCornerRadius="5dp">

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


                <LinearLayout

                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="10dp"
                    android:layout_marginTop="10dp"
                    android:orientation="vertical">


                    <TextView
                        android:id="@+id/DeviceCode"
                        android:layout_width="wrap_content"
                        android:layout_height="0dp"
                        android:layout_marginTop="5dp"
                        android:layout_weight="1"
                        android:text=""
                        android:textColor="#CD0808"
                        android:textStyle="bold" />

                    <TextView
                        android:id="@+id/Analysis"
                        android:layout_width="wrap_content"
                        android:layout_height="0dp"
                        android:layout_weight="1"
                        android:text=""
                        android:textColor="#000"
                        android:textStyle="bold" />

                    <TextView
                        android:id="@+id/Battery"
                        android:layout_width="wrap_content"
                        android:layout_height="0dp"
                        android:layout_weight="1"
                        android:text=""
                        android:textColor="#000"
                        android:textStyle="bold" />


                    <TextView
                        android:id="@+id/CommunicationAddres"
                        android:layout_width="wrap_content"
                        android:layout_height="0dp"
                        android:layout_weight="1"
                        android:text=""
                        android:textColor="#000"
                        android:textStyle="bold" />

                    <TextView
                        android:id="@+id/Date"
                        android:layout_width="wrap_content"
                        android:layout_height="0dp"
                        android:layout_weight="1"
                        android:text=""
                        android:textColor="#000"
                        android:textStyle="bold" />
                    <TextView
                        android:id="@+id/FreezeDate"
                        android:layout_width="wrap_content"
                        android:layout_height="0dp"
                        android:layout_weight="1"
                        android:text=""
                        android:textColor="#000"
                        android:textStyle="bold" />
                    <TextView
                        android:id="@+id/GasVolume"
                        android:layout_width="wrap_content"
                        android:layout_height="0dp"
                        android:layout_weight="1"
                        android:text=""
                        android:textColor="#000"
                        android:textStyle="bold" />
                    <TextView
                        android:id="@+id/MeterRTC"
                        android:layout_width="wrap_content"
                        android:layout_height="0dp"
                        android:layout_weight="1"
                        android:text=""
                        android:textColor="#000"
                        android:textStyle="bold" />
                    <TextView
                        android:id="@+id/NetID"
                        android:layout_width="wrap_content"
                        android:layout_height="0dp"
                        android:layout_weight="1"
                        android:text=""
                        android:textColor="#000"
                        android:textStyle="bold" />
                    <TextView
                        android:id="@+id/RSSI"
                        android:layout_width="wrap_content"
                        android:layout_height="0dp"
                        android:layout_weight="1"
                        android:text=""
                        android:textColor="#000"
                        android:textStyle="bold" />
                    <TextView
                        android:id="@+id/State"
                        android:layout_width="wrap_content"
                        android:layout_height="0dp"
                        android:layout_weight="1"
                        android:text=""
                        android:textColor="#000"
                        android:textStyle="bold" />
                    <TextView
                        android:id="@+id/CommType"
                        android:layout_width="wrap_content"
                        android:layout_height="0dp"
                        android:layout_weight="1"
                        android:text=""
                        android:textColor="#000"
                        android:textStyle="bold" />
                    <TextView
                        android:id="@+id/DataSt"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:text=""
                        android:textColor="#000"
                        android:textStyle="bold" />


                </LinearLayout>
            </LinearLayout>

        </android.support.v7.widget.CardView>
    </LinearLayout>

</RelativeLayout>

错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView$LayoutManager.onLayoutChildren(android.support.v7.widget.RecyclerView$Recycler, android.support.v7.widget.RecyclerView$State)' on a null object reference
        at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3812)
        at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3529)
        at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:4082)
        at android.view.View.layout(View.java:21949)
        at android.view.ViewGroup.layout(ViewGroup.java:6260)
        at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1103)
        at android.view.View.layout(View.java:21949)
        at android.view.ViewGroup.layout(ViewGroup.java:6260)
        at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1103)
        at android.view.View.layout(View.java:21949)
        at android.view.ViewGroup.layout(ViewGroup.java:6260)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:332)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
        at android.view.View.layout(View.java:21949)
        at android.view.ViewGroup.layout(ViewGroup.java:6260)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:332)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
        at android.view.View.layout(View.java:21949)
        at android.view.ViewGroup.layout(ViewGroup.java:6260)
        at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:444)
        at android.view.View.layout(View.java:21949)
        at android.view.ViewGroup.layout(ViewGroup.java:6260)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:332)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
        at android.view.View.layout(View.java:21949)
        at android.view.ViewGroup.layout(ViewGroup.java:6260)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1829)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1673)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1582)
        at android.view.View.layout(View.java:21949)
        at android.view.ViewGroup.layout(ViewGroup.java:6260)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:332)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
        at com.android.internal.policy.DecorView.onLayout(DecorView.java:790)
        at android.view.View.layout(View.java:21949)
        at android.view.ViewGroup.layout(ViewGroup.java:6260)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:3081)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2591)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1722)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7621)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1029)
        at android.view.Choreographer.doCallbacks(Choreographer.java:852)
        at android.view.Choreographer.doFrame(Choreographer.java:787)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1014)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:235)
        at android.app.ActivityThread.main(ActivityThread.java:7441)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:935)

标签: javaandroid-recyclerview

解决方案


indoInBackground一切都在后台线程上执行,而onPreExecuteonPostExecute在 UI 线程上执行。

所以你的 recyclerview 是空的,因为你正在后台线程上运行操作

您可以在runOnUiThread内部添加回调doInBackground以在 UI 线程上执行操作。

像这样

@Override
protected Object doInBackground(Object[] objects) {
    ((MainActivity)getContext()).runOnUiThread(new Runnable() {
        public void run() { // executed on UI thread
            ArrayList<String> wait = new ArrayList<String>();
            wait.add("PLEASE WAIT......");
            Empty_Adpater adapter = new Empty_Adpater(getContext(), wait);
            recycler_view_grid_meter_list.setAdapter(adapter);
            recycler_view_grid_meter_list.setLayoutManager(new 
            LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        }
    });
    ...
}

推荐阅读