从活动中收到意图后如何创建片段?

时间:2019-05-18 08:22:27

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

我在活动的onCreate方法中收到胆固醇监测仪的数组列表。我正在尝试将其传递到onPostExecute的片段中,但当前它传递的是空列表? 在我的onCreate中。

cholesterol_monitor= this.getIntent().getParcelableArrayListExtra("monitorList");
        CholesterolFragment cholesterolFragment= new CholesterolFragment();
        cholesterolFragment.execute(cholesterol_monitor);

在我的AsyncTask方法中

 private class CholesterolFragment extends AsyncTask<ArrayList<CholesterolMonitor>, Void, ArrayList<CholesterolMonitor>> {


        @Override
        protected ArrayList<CholesterolMonitor> doInBackground(ArrayList<CholesterolMonitor>... arrayLists) {
            cholesterol_monitor=arrayLists[0];
            return cholesterol_monitor;

        }
        @Override
        protected void onPostExecute(ArrayList<CholesterolMonitor> result){
            cholesterol_monitor= result;
            monitorListFragment = MonitorListFragment.newInstance(cholesterol_monitor);
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fragment_monitor_layout, monitorListFragment)
                    .commit();
        }
    }

编辑:在我的monitorListFragment中

 public static MonitorListFragment newInstance(ArrayList<CholesterolMonitor> monitor_list) {
        MonitorListFragment fragment = new MonitorListFragment();
        Bundle args = new Bundle();
        args.putParcelableArrayList(ARG_MONITOR_LIST, monitor_list);

        fragment.setArguments(args);
        return fragment;
    }

编辑:这是因为列表中没有空对象,所以我在监视器列表回收器适配器中添加了一个检查,但是没有显示名称吗?

这在我的monitorlistrecyclerAdapter中

 public void onBindViewHolder(final MonitorListRecyclerAdapter.ViewHolder holder, int position) {
    if (!(data.get(position).getPatient()== null)){
       String patient = "Patient: " + data.get(position).getPatient().getName().get(0).getNameAsSingleString();
       String  cholesterolLevel = "Cholesterol: "
            + String.format("%.2f", data.get(position).getPatientCholesterolLevel()) + " "
            + data.get(position).getUnitsMeasurement();
        holder.patientNameView.setText(patient);
        holder.cholesterolView.setText(cholesterolLevel);


    }

1 个答案:

答案 0 :(得分:0)

如果您首先将数据传递给片段,该怎么办

    Bundle bundle = new Bundle();
    bundle.putStringArrayList(key,value);
    fragment.setArguments(bundle);

然后在片段中检索

Bundle bundle = this.getArguments();
if (bundle != null) {
  // execute AsyncTask class  
}