de.uni_koblenz_landau.apow.EncounterDetailFragment.java Source code

Java tutorial

Introduction

Here is the source code for de.uni_koblenz_landau.apow.EncounterDetailFragment.java

Source

/**
 * Apow - a mobile EHR Management System for low-resource environments
 * in developing countries, exemplified by rural Ghana
 * Copyright (C) 2014 Martin Landua
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses/.
 */

package de.uni_koblenz_landau.apow;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.openmrs.Encounter;
import org.openmrs.EncounterType;
import org.openmrs.Patient;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.NavUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import de.uni_koblenz_landau.apow.dialogs.DateDialogFragment;
import de.uni_koblenz_landau.apow.dialogs.DateDialogListener;
import de.uni_koblenz_landau.apow.dialogs.TimeDialogFragment;
import de.uni_koblenz_landau.apow.helper.Helper;
import de.uni_koblenz_landau.apow.helper.ListViewItem;
import de.uni_koblenz_landau.apow.tasks.DataUpdateInterface;
import de.uni_koblenz_landau.apow.tasks.EncounterDetailInterface;
import de.uni_koblenz_landau.apow.tasks.EncounterDetailTask;
import de.uni_koblenz_landau.apow.tasks.EncounterUpdateTask;
import de.uni_koblenz_landau.apow.tasks.TaskActivity;
import de.uni_koblenz_landau.apow.tasks.TaskActivityReference;

/**
 * Fragment for showing and updating an encounter.
 * 
 * @author Martin Landua
 * 
 */
public class EncounterDetailFragment extends Fragment
        implements EncounterDetailInterface, DataUpdateInterface, TaskActivity, DateDialogListener {

    // Constants
    public static final String ARG_ENCOUNTER_ID = "encounter_id";
    public static final String ARG_PATIENT_ID = "patient_id";
    private static final String ARG_ENCOUNTER = "encounter";
    public static final String ARG_TITLE = "title";
    private static final String ARG_TYPES = "types";
    private static final String DATE_DIALOG_ID = "datedialog";
    private static final String TIME_DIALOG_ID = "timedialog";

    // Tasks
    private EncounterUpdateTask mEncounterUpdateTask;
    private EncounterDetailTask mEncounterDetailTask;

    // UI Variables
    private Encounter mEncounter;
    private List<ListViewItem> mTypes;
    private int mSelectedType;
    private String mSelectedName;
    private String mDate;
    private String mTime;
    private int mPatientID;
    private int mEncounterID;

    // UI references
    private DateDialogFragment mDateDialog;
    private TimeDialogFragment mTimeDialog;
    private TextView mDateView;
    private TextView mTimeView;
    private Spinner mTypesView;

    /**
     * Empty constructor for Instantiation
     */
    public EncounterDetailFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        super.onCreate(savedInstanceState);

        getActivity().setTitle(getArguments().getString(ARG_TITLE));

        // Re-attach Tasks.
        TaskActivityReference.getInstance().attach(EncounterUpdateTask.TASK_ID, this);
        TaskActivityReference.getInstance().attach(EncounterDetailTask.TASK_ID, this);

        if (getArguments().containsKey(ARG_PATIENT_ID)) {
            mPatientID = getArguments().getInt(ARG_PATIENT_ID);
        }
        if (getArguments().containsKey(ARG_ENCOUNTER_ID)) {
            mEncounterID = getArguments().getInt(ARG_ENCOUNTER_ID);
        }
    }

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

        View view = inflater.inflate(R.layout.encounter_detail_fragment, container, false);

        // Create UI references.
        mDateDialog = (DateDialogFragment) getFragmentManager().findFragmentByTag(DATE_DIALOG_ID);
        if (mDateDialog != null) {
            mDateDialog.setListener(this);
        }
        mTimeDialog = (TimeDialogFragment) getFragmentManager().findFragmentByTag(TIME_DIALOG_ID);
        if (mTimeDialog != null) {
            mTimeDialog.setListener(this);
        }
        mDateView = (TextView) view.findViewById(R.id.encounter_detail_date);
        mTimeView = (TextView) view.findViewById(R.id.encounter_detail_time);
        mTypesView = (Spinner) view.findViewById(R.id.encounter_detail_types);

        // Restore UI from saved instance or load data.
        if (savedInstanceState != null) {
            mEncounter = (Encounter) savedInstanceState.getSerializable(ARG_ENCOUNTER);
            if (mEncounter != null) {
                mTypes = savedInstanceState.getParcelableArrayList(ARG_TYPES);
                ArrayAdapter<ListViewItem> adapter = new ArrayAdapter<>(getActivity(),
                        android.R.layout.simple_spinner_item, mTypes);
                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                mTypesView.setAdapter(adapter);
            }
        } else {
            loadEncounter();
        }

        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // Detach tasks for preventing memory leaks.
        TaskActivityReference.getInstance().detach(EncounterUpdateTask.TASK_ID);
        TaskActivityReference.getInstance().detach(EncounterDetailTask.TASK_ID);
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        savedInstanceState.putSerializable(ARG_ENCOUNTER, mEncounter);
        savedInstanceState.putParcelableArrayList(ARG_TYPES, (ArrayList<ListViewItem>) mTypes);
        super.onSaveInstanceState(savedInstanceState);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.encounter_detail, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == android.R.id.home) {
            NavUtils.navigateUpFromSameTask(getActivity());
            return true;
        }

        if (id == R.id.encounter_detail_action_save) {
            save();
            return true;
        }
        if (id == R.id.encounter_detail_action_cancel) {
            Intent back;
            if (mEncounter != null) {
                back = new Intent(getActivity(), ObsListActivity.class);
            } else {
                back = new Intent(getActivity(), EncounterListActivity.class);
            }
            NavUtils.navigateUpTo(getActivity(), back);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * Checks input and saves settings to database.
     */
    private void save() {
        // Abort if task is already running.
        if (mEncounterUpdateTask != null) {
            return;
        }

        // Store UI values.
        mDate = mDateView.getText().toString();
        mTime = mTimeView.getText().toString();
        mSelectedType = ((ListViewItem) mTypesView.getSelectedItem()).getId();
        mSelectedName = ((ListViewItem) mTypesView.getSelectedItem()).getField1();

        // Update encounter object.
        mEncounter.setPatient(new Patient(mPatientID));

        // Merge date and time
        mEncounter.setEncounterDatetime(Helper.mergeDateTime(mDate, mTime, getActivity()));
        mEncounter.setEncounterType(new EncounterType(mSelectedType));
        mEncounter.getEncounterType().setName(mSelectedName);

        // Start update task.
        mEncounterUpdateTask = new EncounterUpdateTask();
        TaskActivityReference.getInstance().addTask(EncounterUpdateTask.TASK_ID, mEncounterUpdateTask, this);
        mEncounterUpdateTask.execute(mEncounter);
    }

    /**
     * Called by update task, when update is finished.
     */
    @Override
    public void onDataUpdateFinished() {
        mEncounterUpdateTask = null;

        // Leave activity.
        Intent back;
        if (mEncounter.getId() != null) {
            back = new Intent(getActivity(), ObsListActivity.class);
            back.putExtra(ObsListFragment.ARG_TITLE, mEncounter.getEncounterType().getName());
        } else {
            back = new Intent(getActivity(), EncounterListActivity.class);
        }
        NavUtils.navigateUpTo(getActivity(), back);
    }

    /**
     * Starts task to load encounters.
     */
    private void loadEncounter() {
        // Abort if task is already running.
        if (mEncounterDetailTask != null) {
            return;
        }

        // Start task.
        mEncounterDetailTask = new EncounterDetailTask();
        TaskActivityReference.getInstance().addTask(EncounterDetailTask.TASK_ID, mEncounterDetailTask, this);
        mEncounterDetailTask.execute(mEncounterID);
    }

    /**
     * Called by EncounterDetailTask, when loading is finished.
     */
    @Override
    public void onEncounterFetched(Encounter encounter, List<ListViewItem> types) {
        mEncounterDetailTask = null;

        // If result is not empty, update UI, else show error message.
        if (types != null) {
            mTypes = types;
            ArrayAdapter<ListViewItem> adapter = new ArrayAdapter<>(getActivity(),
                    android.R.layout.simple_spinner_item, types);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            mTypesView.setAdapter(adapter);

            if (encounter != null) {
                mEncounter = encounter;
                mDateView.setText(Helper.dateToLocaleString(mEncounter.getEncounterDatetime(), getActivity()));
                mTimeView.setText(Helper.dateToLocaleTimeString(mEncounter.getEncounterDatetime(), getActivity()));

                int position = -1;
                for (int i = 0; i < adapter.getCount(); i++) {
                    if (adapter.getItem(i).getId() == mEncounter.getEncounterType().getEncounterTypeId()) {
                        position = i;
                        break;
                    }
                }
                mTypesView.setSelection(position);
            } else {
                mEncounter = new Encounter();
                mDateView.setText(Helper.dateToLocaleString(new Date(), getActivity()));
                mTimeView.setText(Helper.dateToLocaleTimeString(new Date(), getActivity()));
            }
        } else {
            Toast.makeText(getActivity(), R.string.error_database, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * Create and open date dialog.
     * @param view View
     */
    public void openDateDialog(View view) {
        Calendar calendar = Calendar.getInstance();
        // Get date of field. If no date is available, use today.
        Date date = Helper.localeStringToDate(((TextView) view).getText().toString().trim(), getActivity());
        if (date != null) {
            calendar.setTime(date);
        } else {
            calendar = new GregorianCalendar();
        }
        if (view.getId() == R.id.encounter_detail_time) {
            mTimeDialog = TimeDialogFragment.newInstance(calendar);
            mTimeDialog.setListener(this);
            mTimeDialog.show(getActivity().getSupportFragmentManager(), TIME_DIALOG_ID);
        }

        if (view.getId() == R.id.encounter_detail_date) {
            mDateDialog = DateDialogFragment.newInstance(calendar);
            mDateDialog.setListener(this);
            mDateDialog.show(getActivity().getSupportFragmentManager(), DATE_DIALOG_ID);
        }
    }

    /**
     * Callback for date dialog.
     */
    @Override
    public void dateSet(Calendar calendar, String target) {
        // Set field to date.
        if (target.equals(DATE_DIALOG_ID)) {
            mDateView.setText(Helper.dateToLocaleString(calendar.getTime(), getActivity()));
        }
        if (target.equals(TIME_DIALOG_ID)) {
            mTimeView.setText(Helper.dateToLocaleTimeString(calendar.getTime(), getActivity()));
        }
    }

}