上下文空引用问题

超级难解释。


这是我在报告中遇到的错误:


Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference

当您进出片段时,这似乎是间歇性发生的。该错误似乎发生在适配器中。


这是所谓的地方:


    @Nullable

    @Override

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

        getActivity().setTitle("Shipments");


        myView = inflater.inflate(R.layout.shipments_out_layout, container, false);


        listView = myView.findViewById(R.id.listView);


        fetchShipments();


        return myView;

    }


    /**

     * Fetch shipments

     */

    public void fetchShipments()

    {

        shipmentsService.fetchFromServer(getActivity());

    }


    /**

     * Show shipments

     */

    public void showShipments(){

        RealmResults<Shipment> savedShipments = shipmentsService.all();


        ShipmentsAdaptor adaptor = new ShipmentsAdaptor(savedShipments, this.getContext());


        listView.setAdapter(adaptor);

    }

这是适配器出现错误的地方:


public class ShipmentsAdaptor extends ArrayAdapter<Shipment> {


private RealmResults<Shipment> dataSet;

Context mContext;


// View lookup cache

private static class ViewHolder {

    TextView stockItemId;

    TextView technicianName;

    TextView shipmentDate;

}


public ShipmentsAdaptor(RealmResults<Shipment> data, Context context){

    super(context, R.layout.shipments_out_row_item, data);

    this.dataSet = data;

    this.mContext = context;

}

具体来说就是这行: super(context, R.layout.shipments_out_row_item, data);


我认为这可能与我们将上下文插入适配器,然后在完成页面之前更改页面的方式有关,但事实证明这没有定论。


梵蒂冈之花
浏览 205回答 3
3回答

慕运维8079593

该Fragment#getContext()可为空。null当您的片段与活动分离时,此方法返回。该应用程序崩溃是因为您在未附加片段的情况下创建了适配器,从而导致将其null传递给构造函数。showShipments仅当片段附加到活动时才应调用该方法。有回调onAttach(),onDetach()这将帮助您检测状态。还isAdded()返回一个布尔值,说明该片段是否已附加。选择对您来说方便的东西。祝你好运!

qq_笑_17

看起来您fetchShipments();在返回片段布局视图(myView)之前正在调用,因此在实例化适配器时它为null。尝试:移动fetchShipments();从onCreateView(),并将其放置在的onResume()或覆盖在onStart()和调用它有

慕尼黑的夜晚无繁华

您可以在适配器设置过程中检查是否为null以避免这种情况。在Fragment中,有时getActivity可以在Fragment生命周期的不同时间返回null。例如,在showShipmentsActivity a = getActivity();if( a == null || a.isFinishing() ) {&nbsp; &nbsp; // Not in a valid state to show things anyway, so just stop and exit&nbsp; &nbsp; return;}ShipmentsAdaptor adaptor = new ShipmentsAdaptor(savedShipments, a);您还可以检查isAdded(),如果为false,则可以从中获取null getActivity()。另外,请考虑将呼叫fetchShipments()从onCreateView转移到onActivityCreated。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java