如何首先获取Intent,然后仅创建片段?

时间:2019-05-17 11:57:03

标签: android-fragments android-intent android-asynctask oncreate android-intentservice

在我的活动onCreate方法之一中,我将ArrayList从意图传递到片段中以创建片段。但是,我意识到它会抛出空指针异常,因为可能在接收到意图之前就创建了该片段。如何解决此问题?在我的onCreate方法中。

monitor_list= this.getIntent().getParcelableArrayListExtra("monitorList");

    cholesterol_monitor = (ArrayList<CholesterolMonitor>) monitor_list;





    monitorListFragment = MonitorListFragment.newInstance(cholesterol_monitor);
    getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.fragment_monitor_layout, monitorListFragment)
            .commit();

1 个答案:

答案 0 :(得分:0)

首先检查monitor_list是否为null,然后再替换片段

    ArrayList<CholesterolMonitor> monitor_list= this.getIntent().getParcelableArrayListExtra("monitorList");
    if (monitor_list.size()>0){
        cholesterol_monitor = (ArrayList<CholesterolMonitor>) monitor_list;
        monitorListFragment = MonitorListFragment.newInstance(cholesterol_monitor);
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.fragment_monitor_layout, monitorListFragment)
                .commit();
    }else // list is null