简体   繁体   中英

How to create fragment after receiving intent from activity?

I receive an array list of cholesterol monitors in the onCreate method of an activity.I'm trying to pass it into the fragment in onPostExecute but currently it passes in a null list? In my onCreate.

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

In my AsyncTask methods

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

EDIT:In my 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;
    }

EDIT: Its because there are null objects in my list so I added a check in my monitor list recycler adapter but no names are displayed?

This is in my 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);


    }

How is it if you first pass data to the fragment

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

Then retrieve in the fragment

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM