com.terraremote.terrafieldreport.OpenGroundReport.java Source code

Java tutorial

Introduction

Here is the source code for com.terraremote.terrafieldreport.OpenGroundReport.java

Source

package com.terraremote.terrafieldreport;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.DialogFragment;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.MultiAutoCompleteTextView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.terraremote.terrafieldreport.datePickerFragment.DatePickerFragment;
import com.terraremote.terrafieldreport.gps.GPSTracker;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnItemSelected;

public class OpenGroundReport extends AppCompatActivity {
    private static final String TAG = "OpenGroundReport";
    final DecimalFormat df = new DecimalFormat("0.00000");

    // CardViews
    @BindView(R.id.transitDayCard)
    CardView transitDayCard;
    @BindView(R.id.workLocationCard)
    CardView workLocationCard;
    @BindView(R.id.workDescriptionCard)
    CardView workDescriptionCard;

    // TableRows
    @BindView(R.id.satellitePhoneNumberTableRow)
    TableRow mSatellitePhoneNumberTableRow;

    // Spinners
    @BindView(R.id.checkInContactRoleSpinner)
    Spinner mCheckInContactRoleSpinner;
    @BindView(R.id.checkInContactNameSpinner)
    Spinner mCheckInContactNameSpinner;
    @BindView(R.id.satPhoneNumberListSpinner)
    Spinner mSatPhoneNumberListSpinner;
    // RadioGroups
    @BindView(R.id.riskLevelRadioGroup)
    RadioGroup mRiskLevelRadioGroup;
    @BindView(R.id.postRiskLevelRadioGroup)
    RadioGroup mPostRiskLevelRadioGroup;
    // RadioGroups
    @BindView(R.id.minimalRisk)
    RadioButton mMinimalRisk;
    @BindView(R.id.lowRisk)
    RadioButton mLowRisk;
    @BindView(R.id.mediumRisk)
    RadioButton mMediumRisk;
    @BindView(R.id.highRisk)
    RadioButton mHighRisk;
    @BindView(R.id.veryHighRisk)
    RadioButton mVeryHighRisk;
    @BindView(R.id.postMinimalRisk)
    RadioButton mPostMinimalRisk;
    @BindView(R.id.postLowRisk)
    RadioButton mPostLowRisk;
    @BindView(R.id.postMediumRisk)
    RadioButton mPostMediumRisk;
    @BindView(R.id.postHighRisk)
    RadioButton mPostHighRisk;
    @BindView(R.id.postVeryHighRisk)
    RadioButton mPostVeryHighRisk;
    // Checkboxes
    // PPE Comments
    @BindView(R.id.workingAlone)
    CheckBox mWorkingAlone;
    @BindView(R.id.hiVisApparel)
    CheckBox mHiVisApparel;
    @BindView(R.id.clothingForSeason)
    CheckBox mClothingForSeason;
    @BindView(R.id.safetyRatedFootwear)
    CheckBox mSafetyRatedFootwear;
    @BindView(R.id.personalSurvivalKit)
    CheckBox mPersonalSurvivalKit;
    @BindView(R.id.hearingProtection)
    CheckBox mHearingProtection;
    @BindView(R.id.hardHat)
    CheckBox mHardHat;
    // Ground Operations Information
    @BindView(R.id.satellitePhone)
    CheckBox mSatellitePhone;
    @BindView(R.id.radio)
    CheckBox mRadio;
    @BindView(R.id.firstAidKit)
    CheckBox mFirstAidKit;
    @BindView(R.id.fireExtinguisher)
    CheckBox mFireExtinguisher;
    @BindView(R.id.transportingFuel)
    CheckBox mTransportingFuel;
    @BindView(R.id.tdgPlacards)
    CheckBox mTdgPlacards;
    @BindView(R.id.spillKit)
    CheckBox mSpillKit;
    @BindView(R.id.workingInTraffic)
    CheckBox mWorkingInTraffic;
    @BindView(R.id.pylons)
    CheckBox mPylons;
    @BindView(R.id.trafficSigns)
    CheckBox mTrafficSigns;
    @BindView(R.id.appropriateVehicle)
    CheckBox mAppropriateVehicle;
    // Hazard / Risk Assessment
    @BindView(R.id.remoteArea)
    CheckBox mRemoteArea;
    @BindView(R.id.workingInIsolation)
    CheckBox mWorkingInIsolation;
    @BindView(R.id.extremeWeather)
    CheckBox mExtremeWeather;
    @BindView(R.id.transmissionLines)
    CheckBox mTransmissionLines;
    @BindView(R.id.activeMineSite)
    CheckBox mActiveMineSite;
    @BindView(R.id.activeLoggingArea)
    CheckBox mActiveLoggingArea;
    @BindView(R.id.wildlife)
    CheckBox mWildlife;
    @BindView(R.id.fatigue)
    CheckBox mFatigue;
    @BindView(R.id.politicalConflict)
    CheckBox mPoliticalConflict;
    @BindView(R.id.resubmit)
    CheckBox mResubmit;
    @BindView(R.id.transitDay)
    CheckBox mTransitDay;
    @BindView(R.id.rentalVehicle)
    CheckBox mRentalVehicle;
    // TextViews
    @BindView(R.id.transitDayText)
    TextView transitDayText;
    @BindView(R.id.colleaguesTextView)
    TextView tvColleaguesTextView;
    @BindView(R.id.selected_date)
    TextView showDate;
    @BindView(R.id.rentalAgencyTv)
    TextView tvRentalAgencyTv;
    @BindView(R.id.riskLevelDescriptions)
    TextView tvRiskLevelDescriptions;
    @BindView(R.id.riskLevelDescriptionsMoreInfo)
    TextView tvRiskLevelDescriptionsMoreInfo;
    @BindView(R.id.safetyNotice)
    TextView safetyNotice;
    // EditTexts
    @BindView(R.id.name)
    EditText mName;
    @BindView(R.id.phoneNumber)
    EditText mPhoneNumber;
    @BindView(R.id.mobNumber)
    EditText mMobNumber;
    @BindView(R.id.locationStart)
    EditText mLocationStart;
    @BindView(R.id.gpsLatitude)
    EditText mGpsLatitude;
    @BindView(R.id.gpsLongitude)
    EditText mGpsLongitude;
    @BindView(R.id.satellitePhoneNumber)
    EditText mSatellitePhoneNumber;
    @BindView(R.id.otherContactName)
    EditText mOtherContactName;
    @BindView(R.id.ppeComments)
    EditText mPpeComments;
    // Rental Details
    @BindView(R.id.rentalAgency)
    EditText mRentalAgency;
    @BindView(R.id.vehicleMake)
    EditText mVehicleMake;
    @BindView(R.id.vehicleModel)
    EditText mVehicleModel;
    @BindView(R.id.vehicleColour)
    EditText mVehicleColour;
    @BindView(R.id.vehicleLicensePlate)
    EditText mVehicleLicensePlate;
    @BindView(R.id.vehicleOperatorName)
    EditText mVehicleOperatorName;
    // Work Location Details
    @BindView(R.id.cityOfDeparture)
    EditText mCityOfDeparture;
    @BindView(R.id.cityOfArrival)
    EditText mCityOfArrival;
    @BindView(R.id.projectLocation)
    EditText mProjectLocation;
    @BindView(R.id.projectDescription)
    EditText mProjectDescription;
    @BindView(R.id.estimatedWorkDuration)
    EditText mEstimatedWorkDuration;
    @BindView(R.id.preventionMeasures)
    EditText mPreventionMeasures;
    @BindView(R.id.generalComments)
    EditText mGeneralComments;
    // MultiCompleteTextViews
    @BindView(R.id.colleagues)
    MultiAutoCompleteTextView mColleagues;

    private static final String COMMON_SHARED_PREFERENCES = "commonSharedPreferences";
    private static final String OPEN_GROUND_SHARED_PREFERENCES = "openGroundSharedPreferences";
    int mobNumberInt, selectedRisk, postSelectedRisk;
    double gpsLatitudeDouble, gpsLongitudeDouble;
    RadioButton selectedRiskLevel, postSelectedRiskLevel;
    Boolean workingAloneBool, hiVisApparelBool, clothingForSeasonBool, safetyRatedFootwearBool,
            personalSurvivalKitBool, hearingProtectionBool, hardHatBool, satellitePhoneBool, radioBool,
            firstAidKitBool, fireExtinguisherBool, transportingFuelBool, tdgPlacardsBool, spillKitBool,
            workingInTrafficBool, pylonsBool, trafficSignsBool, appropriateVehicleBool, remoteAreaBool,
            workingInIsolationBool, extremeWeatherBool, transmissionLinesBool, activeMineSiteBool,
            activeLoggingAreaBool, wildlifeBool, fatigueBool, politicalConflictBool, transitDayBool,
            rentalVehicleBool, reSubmitBool;
    // PPE Checklist
    String hiVisApparel, clothingForSeason, safetyRatedFootwear, personalSurvivalKit, hearingProtection, hardHat;
    // Rental Vehicle Information
    String rentalVehicle, rentalAgency, vehicleMake, vehicleModel, vehicleColour, vehicleLicensePlate,
            vehicleOperatorName;
    // Ground Operations Information
    String cityOfDeparture, cityOfArrival, projectLocation, projectDescription, estimatedWorkDuration,
            checkInContactRole, checkInContactName, satellitePhone, satellitePhoneNumberListSelection, radio,
            firstAidKit, fireExtinguisher, transportingFuel, tdgPlacards, spillKit, workingInTraffic, pylons,
            trafficSigns, appropriateVehicle,
            // Hazard / Risk Assessment
            remoteArea, workingInIsolation, extremeWeather, transmissionLines, activeMineSite, activeLoggingArea,
            wildlife, fatigue, politicalConflict, riskLevel, postRiskLevel;
    String name, phoneNumber, userSelectedDateGround, submissionDate, mobNumber, locationStart, transitDay,
            workingAlone, gpsLatitude, gpsLongitude, satellitePhoneNumber, otherContactName, ppeComments,
            colleagues, preventionMeasures, generalComments, reSubmit, jsonText;

    //    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    //    final DecimalFormat df = new DecimalFormat("0.00000");
    int savedCheckInContactRolePosition, savedCheckInContactOtherNamePosition, savedSatNumberPosition;
    GPSTracker gps;

    // Field Staff Position - 0
    @OnItemSelected(R.id.checkInContactRoleSpinner)
    void checkInContactRoleSpinnerSelected(int position) {
        position = mCheckInContactRoleSpinner.getSelectedItemPosition();
        if (position == 0) {
            ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(OpenGroundReport.this,
                    R.array.check_in_contact_data_checker_names, android.R.layout.simple_spinner_item);
            // Specify the layout to use when the list of choices appears
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            mCheckInContactNameSpinner.setVisibility(View.VISIBLE);
            mOtherContactName.setVisibility(View.GONE);
            mOtherContactName.setText("");
            // Apply the adapter to the spinner
            mCheckInContactNameSpinner.setAdapter(adapter);
        }
    }

    // OHS Administrator Position - 1
    @OnItemSelected(R.id.checkInContactRoleSpinner)
    void ohsAdministratorSpinnerSelected(int position) {
        position = mCheckInContactRoleSpinner.getSelectedItemPosition();
        if (position == 1) {
            // Create an ArrayAdapter using the string array and a default spinner layout
            ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(OpenGroundReport.this,
                    R.array.check_in_contact_ohs_administrator_names, android.R.layout.simple_spinner_item);
            // Specify the layout to use when the list of choices appears
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            mCheckInContactNameSpinner.setVisibility(View.VISIBLE);
            mOtherContactName.setVisibility(View.GONE);
            mOtherContactName.setText("");
            // Apply the adapter to the spinner
            mCheckInContactNameSpinner.setAdapter(adapter);
        }
    }

    // Field Supervisor Position - 2
    @OnItemSelected(R.id.checkInContactRoleSpinner)
    void fieldSupervisorSpinnerSelected(int position) {
        position = mCheckInContactRoleSpinner.getSelectedItemPosition();
        if (position == 2) {
            // Create an ArrayAdapter using the string array and a default spinner layout
            ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(OpenGroundReport.this,
                    R.array.check_in_contact_field_supervisor_names, android.R.layout.simple_spinner_item);
            // Specify the layout to use when the list of choices appears
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            mCheckInContactNameSpinner.setVisibility(View.VISIBLE);
            mOtherContactName.setVisibility(View.GONE);
            mOtherContactName.setText("");
            // Apply the adapter to the spinner
            mCheckInContactNameSpinner.setAdapter(adapter);
        }
    }

    // Manager - Aerial Operations Position - 3
    @OnItemSelected(R.id.checkInContactRoleSpinner)
    void aerialOperationsSpinnerSelected(int position) {
        position = mCheckInContactRoleSpinner.getSelectedItemPosition();
        if (position == 3) {
            // Create an ArrayAdapter using the string array and a default spinner layout
            ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(OpenGroundReport.this,
                    R.array.check_in_contact_aerial_manager_names, android.R.layout.simple_spinner_item);
            // Specify the layout to use when the list of choices appears
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            mCheckInContactNameSpinner.setVisibility(View.VISIBLE);
            mOtherContactName.setVisibility(View.GONE);
            mOtherContactName.setText("");
            // Apply the adapter to the spinner
            mCheckInContactNameSpinner.setAdapter(adapter);
        }
    }

    // Other Position - 4
    @OnItemSelected(R.id.checkInContactRoleSpinner)
    void otherSpinnerSelected(int position) {
        position = mCheckInContactRoleSpinner.getSelectedItemPosition();
        if (position == 4) {
            // Create an ArrayAdapter using the string array and a default spinner layout
            ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(OpenGroundReport.this,
                    R.array.check_in_contact_other, android.R.layout.simple_spinner_item);
            // Specify the layout to use when the list of choices appears
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            mCheckInContactNameSpinner.setVisibility(View.GONE);
            mOtherContactName.setVisibility(View.VISIBLE);
            // Apply the adapter to the spinner
            mCheckInContactNameSpinner.setAdapter(adapter);
        }
    }

    // Buttons
    @OnClick(R.id.clearAllBtn)
    void clearAll() {
        AlertDialog.Builder builder = new AlertDialog.Builder(OpenGroundReport.this);
        builder.setMessage(R.string.are_you_sure)
                .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        showDate.setText(sdf.format(new Date()));
                        mTransitDay.setChecked(false);
                        transitDayCard.setBackgroundColor(Color.WHITE);
                        transitDayText.setTextColor(getResources().getColor(android.R.color.tertiary_text_dark));
                        workLocationCard.setVisibility(View.VISIBLE);
                        workDescriptionCard.setVisibility(View.VISIBLE);
                        mWorkingAlone.setChecked(false);
                        tvColleaguesTextView.setVisibility(View.VISIBLE);
                        mColleagues.setVisibility(View.VISIBLE);
                        mColleagues.setText("");
                        mLocationStart.setText("");
                        mGpsLatitude.setText("");
                        mGpsLongitude.setText("");
                        // PPE Checklist
                        mHiVisApparel.setChecked(false);
                        mClothingForSeason.setChecked(false);
                        mSafetyRatedFootwear.setChecked(false);
                        mPersonalSurvivalKit.setChecked(false);
                        mHearingProtection.setChecked(false);
                        mHardHat.setChecked(false);
                        mPpeComments.setText("");
                        // Vehicle Details
                        //                                hasRentalVehicle.setChecked(false);
                        //                                rentalAgencyTextView.setVisibility(View.GONE);
                        //                                hasRentalAgency.setVisibility(View.GONE);
                        //                                hasRentalAgency.setText("");
                        //                                hasVehicleMake.setText("");
                        //                                hasVehicleModel.setText("");
                        //                                hasVehicleColor.setText("");
                        //                                hasVehicleLicensePlate.setText("");
                        //                                hasVehicleOperatorsName.setText("");
                        // Ground Operations Information
                        mCityOfDeparture.setText("");
                        mCityOfArrival.setText("");
                        mProjectLocation.setText("");
                        mProjectDescription.setText("");
                        mEstimatedWorkDuration.setText("");
                        // Check in Contact
                        //                                checkInContactRoleSpinner.setSelection(0);
                        //                                checkInContactNameSpinner.setSelection(0);
                        //                                otherContactName.setText("");
                        mSatellitePhone.setChecked(false);
                        mSatellitePhoneNumberTableRow.setVisibility(View.GONE);
                        mSatellitePhoneNumber.setText("");
                        mRadio.setChecked(false);
                        mFirstAidKit.setChecked(false);
                        mFireExtinguisher.setChecked(false);
                        mTransportingFuel.setChecked(false);
                        mTdgPlacards.setChecked(false);
                        mSpillKit.setChecked(false);
                        mWorkingInTraffic.setChecked(false);
                        mPylons.setChecked(false);
                        mTrafficSigns.setChecked(false);
                        mAppropriateVehicle.setChecked(false);
                        // Hazard / Risk Assessment
                        mRemoteArea.setChecked(false);
                        mWorkingInIsolation.setChecked(false);
                        mExtremeWeather.setChecked(false);
                        mTransmissionLines.setChecked(false);
                        mActiveMineSite.setChecked(false);
                        mActiveLoggingArea.setChecked(false);
                        mWildlife.setChecked(false);
                        mFatigue.setChecked(false);
                        mPoliticalConflict.setChecked(false);
                        mMinimalRisk.setChecked(false);
                        mLowRisk.setChecked(false);
                        mMediumRisk.setChecked(true);
                        mHighRisk.setChecked(false);
                        mVeryHighRisk.setChecked(false);
                        mPreventionMeasures.setText("");
                        mPostMinimalRisk.setChecked(false);
                        mPostLowRisk.setChecked(false);
                        mPostMediumRisk.setChecked(true);
                        mPostHighRisk.setChecked(false);
                        mPostVeryHighRisk.setChecked(false);
                        mGeneralComments.setText("");
                    }
                }).setNegativeButton(R.string.cancel, null);

        AlertDialog alert = builder.create();
        alert.show();
    }

    @OnClick(R.id.transitDay)
    void transitDay() {
        if (mTransitDay.isChecked()) {
            workLocationCard.setVisibility(View.GONE);
            workDescriptionCard.setVisibility(View.GONE);
            transitDayCard.setBackgroundColor(Color.rgb(210, 51, 224));
            transitDayText.setTextColor(Color.WHITE);
        } else {
            workLocationCard.setVisibility(View.VISIBLE);
            workDescriptionCard.setVisibility(View.VISIBLE);
            transitDayCard.setBackgroundColor(Color.WHITE);
            transitDayText.setTextColor(getResources().getColor(android.R.color.tertiary_text_dark));
        }
    }

    @OnClick(R.id.getGpsBtn)
    void getGpsLocation() {
        askForLocationPermission();
        // create class object
        gps = new GPSTracker(OpenGroundReport.this);

        // check if GPS enabled
        if (gps.canGetLocation()) {

            double latitude = gps.getLatitude();
            double longitude = gps.getLongitude();

            mGpsLatitude.setText(df.format(latitude));
            mGpsLongitude.setText(df.format(longitude));
        } else {
            // can't get location
            // GPS or Network is not enabled
            // Ask user to enable GPS/network in settings
            gps.showSettingsAlert();
        }
    }

    @OnClick(R.id.workingAlone)
    void workingAlone() {
        if (mWorkingAlone.isChecked()) {
            mColleagues.setVisibility(View.GONE);
            tvColleaguesTextView.setVisibility(View.GONE);
        } else {
            mColleagues.setVisibility(View.VISIBLE);
            mColleagues.setText("");
            tvColleaguesTextView.setVisibility(View.VISIBLE);
        }
    }

    @OnClick(R.id.rentalVehicle)
    void rentalVehicle() {
        if (mRentalVehicle.isChecked()) {
            tvRentalAgencyTv.setVisibility(View.VISIBLE);
            mRentalAgency.setVisibility(View.VISIBLE);
        } else {
            tvRentalAgencyTv.setVisibility(View.GONE);
            tvRentalAgencyTv.setVisibility(View.GONE);
            mRentalAgency.setText("");
        }
    }

    @OnClick(R.id.clearVehicleInfo)
    void clearVehicleInfo() {
        AlertDialog.Builder builder = new AlertDialog.Builder(OpenGroundReport.this);
        builder.setMessage(R.string.clear_vehicle_info_prompt)
                .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // Vehicle Details
                        mRentalVehicle.setChecked(false);
                        tvRentalAgencyTv.setVisibility(View.GONE);
                        mRentalAgency.setVisibility(View.GONE);
                        mRentalAgency.setText("");
                        mVehicleMake.setText("");
                        mVehicleModel.setText("");
                        mVehicleColour.setText("");
                        mVehicleLicensePlate.setText("");
                        mVehicleOperatorName.setText("");
                        // Check in Contact
                        mCheckInContactRoleSpinner.setSelection(0);
                        mCheckInContactNameSpinner.setSelection(0);
                        mOtherContactName.setText("");
                    }
                }).setNegativeButton(R.string.cancel, null);

        AlertDialog alert = builder.create();
        alert.show();
    }

    @OnClick(R.id.satellitePhone)
    void satellitePhoneNumber() {
        if (mSatellitePhone.isChecked()) {
            mSatellitePhoneNumberTableRow.setVisibility(View.VISIBLE);
            if (mSatPhoneNumberListSpinner.getSelectedItem() == getString(R.string.satPhoneOther)) {
                mSatellitePhoneNumber.setVisibility(View.VISIBLE);
            }
        } else {
            mSatellitePhoneNumberTableRow.setVisibility(View.GONE);
            mSatellitePhoneNumber.setText("");
            mSatellitePhoneNumber.setVisibility(View.GONE);
        }
    }

    @OnItemSelected(R.id.satPhoneNumberListSpinner)
    void satPhoneNumberListSpinnerSelected(int position) {
        if (mSatPhoneNumberListSpinner.getSelectedItem() == getResources().getString(R.string.satPhoneOther)) {
            mSatellitePhoneNumber.setVisibility(View.VISIBLE);
        } else {
            mSatellitePhoneNumber.setVisibility(View.GONE);
            mSatellitePhoneNumber.setText("");
        }
    }

    @OnClick(R.id.submitGroundReportBtn)
    void submitReport() {
        mobNumberInt = mMobNumber.getText().length();
        if (mobNumberInt != 7) {
            Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content),
                    R.string.incorrect_mob_number_format, Snackbar.LENGTH_LONG);
            snackbar.show();
        } else {
            submitDailyGroundTailgate();
        }
    }
    //    RadioButton selectedRiskLevel, postSelectedRiskLevel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.open_ground_layout);
        ButterKnife.bind(this);

        loadSharedPreferences();

        Typeface customTypeface = Typeface.createFromAsset(getAssets(), "Raleway-Medium.ttf");
        TextView open_ground_text_font = findViewById(R.id.open_ground_text);
        open_ground_text_font.setTypeface(customTypeface);

        //        final DecimalFormat df = new DecimalFormat("0.00000");
        // Grab the current date and update the string variable 'userSelectedDateGround' with its value.
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        showDate.setText(sdf.format(new Date()));
        submissionDate = sdf.format(new Date());

        // get the defined string array of field team names
        ArrayAdapter<String> enterNameAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_dropdown_item_1line,
                getResources().getStringArray(R.array.TerraFieldTeamNames));
        AutoCompleteTextView enterNameTextView = (AutoCompleteTextView) mName;
        //set adapter for the auto complete fields
        enterNameTextView.setAdapter(enterNameAdapter);
        // specify the minimum type of characters before drop-down list is shown
        enterNameTextView.setThreshold(1);
        // comma to separate the different names
        enterNameTextView.setAdapter(enterNameAdapter);

        // get the defined string array of field team names
        ArrayAdapter<String> fieldTeamNameAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_dropdown_item_1line,
                getResources().getStringArray(R.array.TerraFieldTeamNames));
        MultiAutoCompleteTextView fieldTeamNameTextView = mColleagues;
        //set adapter for the auto complete fields
        fieldTeamNameTextView.setAdapter(fieldTeamNameAdapter);
        // specify the minimum type of characters before drop-down list is shown
        fieldTeamNameTextView.setThreshold(1);
        // comma to separate the different names
        fieldTeamNameTextView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());

        // get the defined string array of helicopter color names
        ArrayAdapter<String> vehicleColorAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_dropdown_item_1line, getResources().getStringArray(R.array.vehicle_colors));
        AutoCompleteTextView vehicleColorsTextView = (AutoCompleteTextView) mVehicleColour;
        //set adapter for the auto complete fields
        vehicleColorsTextView.setAdapter(vehicleColorAdapter);
        // specify the minimum type of characters before drop-down list is shown
        vehicleColorsTextView.setThreshold(1);
        // set adapter
        vehicleColorsTextView.setAdapter(vehicleColorAdapter);

        // get the defined string array of vehicle makes
        ArrayAdapter<String> vehicleMakeAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_dropdown_item_1line, getResources().getStringArray(R.array.vehicle_make));
        AutoCompleteTextView vehicleMakeTextView = (AutoCompleteTextView) mVehicleMake;
        //set adapter for the auto complete fields
        vehicleMakeTextView.setAdapter(vehicleMakeAdapter);
        // specify the minimum type of characters before drop-down list is shown
        vehicleMakeTextView.setThreshold(1);
        // set adapter
        vehicleMakeTextView.setAdapter(vehicleMakeAdapter);

        // get the defined string array of car rental agencies
        ArrayAdapter<String> rentalAgencyAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_dropdown_item_1line,
                getResources().getStringArray(R.array.rental_agencies));
        AutoCompleteTextView rentalAgencyTv = (AutoCompleteTextView) mRentalAgency;
        //set adapter for the auto complete fields
        rentalAgencyTv.setAdapter(rentalAgencyAdapter);
        // specify the minimum type of characters before drop-down list is shown
        rentalAgencyTv.setThreshold(1);
        // set adapter
        rentalAgencyTv.setAdapter(rentalAgencyAdapter);

        // get the defined string array of vehicle operator names
        ArrayAdapter<String> vehicleOperatorNameAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_dropdown_item_1line,
                getResources().getStringArray(R.array.check_in_contact_data_checker_names));
        AutoCompleteTextView vehicleOperatorNameTextView = (AutoCompleteTextView) mVehicleOperatorName;
        //set adapter for the auto complete fields
        vehicleOperatorNameTextView.setAdapter(vehicleOperatorNameAdapter);
        // specify the minimum type of characters before drop-down list is shown
        vehicleOperatorNameTextView.setThreshold(1);
        // set adapter
        vehicleOperatorNameTextView.setAdapter(vehicleOperatorNameAdapter);

    }

    private void askForLocationPermission() {
        // Checks for location permission
        if (ActivityCompat.checkSelfPermission(this,
                android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Log.d("PLAYGROUND", "Permission is not granted, requesting");
            ActivityCompat.requestPermissions(this,
                    new String[] { android.Manifest.permission.ACCESS_FINE_LOCATION }, 123);

        } else {
            Log.d("PLAYGROUND", "Permission is granted");
        }
    }

    @Override
    protected void onStop() {
        // called when the application is about to exit
        super.onStop();
        savedSharedPreferences();
    }

    // When "High" or "Very High" radio button is selected, show yellow alert dialog
    public void highRiskAlert(View v) {
        RadioButton postHighRisk = findViewById(R.id.postHighRisk);
        RadioButton postVeryHighRisk = findViewById(R.id.postVeryHighRisk);
        TextView safetyNotice = findViewById(R.id.safetyNotice);

        if (postHighRisk.isChecked() || postVeryHighRisk.isChecked()) {
            safetyNotice.setVisibility(View.VISIBLE);
        } else {
            safetyNotice.setVisibility(View.GONE);
        }
    }

    // Show and hide the Perception of Risk Level Definitions
    public void showRiskLevelDescriptions(View v) {
        if (tvRiskLevelDescriptions.getVisibility() == View.GONE) {
            tvRiskLevelDescriptions.setVisibility(View.VISIBLE);
            tvRiskLevelDescriptionsMoreInfo.setText(getString(R.string.less_info));
        } else {
            tvRiskLevelDescriptions.setVisibility(View.GONE);
            tvRiskLevelDescriptionsMoreInfo.setText(R.string.risk_level_descriptions);
        }
    }

    private JSONObject GroundJsonObjectBuilder() {

        // Create main JSON Object
        JSONObject groundJsonObject = new JSONObject();
        // Create additional JSON Objects so I can bundle project number information together.
        JSONObject ppeCheckList = new JSONObject();
        JSONObject vehicleInformation = new JSONObject();
        JSONObject groundOperationsInformation = new JSONObject();
        JSONObject hazardAssessment = new JSONObject();

        try {
            // Add data to the JSON Objects
            groundJsonObject.put("ReportTitle", "Ground");
            groundJsonObject.put("User", name);
            groundJsonObject.put("UserPhoneNumber", phoneNumber);
            groundJsonObject.put("ReSubmit", reSubmitBool);
            groundJsonObject.put("ReportDate", userSelectedDateGround);
            groundJsonObject.put("DateSubmitted", submissionDate);
            groundJsonObject.put("MobNumber", mobNumberInt);
            groundJsonObject.put("TransitDay", transitDayBool);
            groundJsonObject.put("WorkingAlone", workingAloneBool);
            groundJsonObject.put("Colleagues", colleagues);
            groundJsonObject.put("LocationStart", locationStart);
            groundJsonObject.put("Latitude", gpsLatitudeDouble);
            groundJsonObject.put("Longitude", gpsLongitudeDouble);
            groundJsonObject.put("GeneralComments", generalComments);
            // PPE Checklist
            ppeCheckList.put("HiVisApparel", hiVisApparelBool);
            ppeCheckList.put("ClothingForSeason", clothingForSeasonBool);
            ppeCheckList.put("SafetyRatedFootwear", safetyRatedFootwearBool);
            ppeCheckList.put("PersonalSurvivalKit", personalSurvivalKitBool);
            ppeCheckList.put("HearingProtection", hearingProtectionBool);
            ppeCheckList.put("HardHat", hardHatBool);
            ppeCheckList.put("PpeComments", ppeComments);
            // Vehicle Information
            vehicleInformation.put("RentalVehicle", rentalVehicleBool);
            vehicleInformation.put("RentalAgency", rentalAgency);
            vehicleInformation.put("VehicleMake", vehicleMake);
            vehicleInformation.put("VehicleModel", vehicleModel);
            vehicleInformation.put("VehicleColour", vehicleColour);
            vehicleInformation.put("VehicleLicensePlate", vehicleLicensePlate);
            vehicleInformation.put("VehicleOperatorName", vehicleOperatorName);
            // Ground Operations Information
            groundOperationsInformation.put("CityOfDeparture", cityOfDeparture);
            groundOperationsInformation.put("CityOfArrival", cityOfArrival);
            groundOperationsInformation.put("WhereWillYouBeWorking", projectLocation);
            groundOperationsInformation.put("DescribeYourWork", projectDescription);
            groundOperationsInformation.put("EstimatedWorkDuration", estimatedWorkDuration);
            groundOperationsInformation.put("CheckInContactRole", checkInContactRole);
            groundOperationsInformation.put("ContactName", checkInContactName);
            // Ground Operations Information Checkboxes
            groundOperationsInformation.put("SatellitePhone", satellitePhoneBool);
            groundOperationsInformation.put("SatellitePhoneNumber", satellitePhoneNumber);
            groundOperationsInformation.put("Radio", radioBool);
            groundOperationsInformation.put("FirstAidKit", firstAidKitBool);
            groundOperationsInformation.put("FireExtinguisher", fireExtinguisherBool);
            groundOperationsInformation.put("TransportingFuel", transportingFuelBool);
            groundOperationsInformation.put("TdgPlacards", tdgPlacardsBool);
            groundOperationsInformation.put("SpillKit", spillKitBool);
            groundOperationsInformation.put("WorkingInTraffic", workingInTrafficBool);
            groundOperationsInformation.put("Pylons", pylonsBool);
            groundOperationsInformation.put("TrafficSigns", trafficSignsBool);
            groundOperationsInformation.put("AppropriateVehicle", appropriateVehicleBool);
            // Hazard / Risk Assessment
            hazardAssessment.put("RemoteArea", remoteAreaBool);
            hazardAssessment.put("WorkingInIsolation", workingInIsolationBool);
            hazardAssessment.put("ExtremeWeather", extremeWeatherBool);
            hazardAssessment.put("TransmissionLines", transmissionLinesBool);
            hazardAssessment.put("ActiveMineSite", activeMineSiteBool);
            hazardAssessment.put("ActiveLoggingArea", activeLoggingAreaBool);
            hazardAssessment.put("Wildlife", wildlifeBool);
            hazardAssessment.put("Fatigue", fatigueBool);
            hazardAssessment.put("PoliticalConflict", politicalConflictBool);
            hazardAssessment.put("PerceptionOfRisk", riskLevel);
            hazardAssessment.put("PreventionMeasures", preventionMeasures);
            hazardAssessment.put("PostPerceptionOfRisk", postRiskLevel);

            // Put Json Objects into main OpenGroundReport Json object
            groundJsonObject.put("PPECheckList", ppeCheckList);
            groundJsonObject.put("LocationDetails", groundOperationsInformation);
            groundJsonObject.put("VehicleInformation", vehicleInformation);
            groundJsonObject.put("HazardAssessment", hazardAssessment);

        } catch (JSONException e) {
            e.printStackTrace();
        }

        jsonText = groundJsonObject.toString();
        // Log finished JSON Object for testing/verification.
        writeJsonFileToExternalStorage();
        return groundJsonObject;
    }

    private void writeJsonFileToExternalStorage() {
        String state;
        state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {

            //This file path works running on my device but not on the emulator
            File Dir = new File(String.valueOf(getExternalFilesDir(null)) + "/GroundReports");

            if (!Dir.exists()) {
                Dir.mkdir();
            }

            File file = new File(Dir, "OpenGround_Report.json");

            try {
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                fileOutputStream.write(jsonText.getBytes());
                fileOutputStream.close();
                Toast.makeText(getApplicationContext(), R.string.report_generated, Toast.LENGTH_SHORT).show();

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            Toast.makeText(getApplicationContext(), R.string.external_storage_not_found, Toast.LENGTH_LONG).show();
        }

    }

    public void submitDailyGroundTailgate() {

        gatherValues();
        GroundJsonObjectBuilder();

        String dailyTailgateText = createDailyTailgate(name, userSelectedDateGround, submissionDate, reSubmit,
                transitDay, phoneNumber, mobNumber, workingAlone, colleagues, locationStart, gpsLatitude,
                gpsLongitude, hiVisApparel, clothingForSeason, safetyRatedFootwear, personalSurvivalKit,
                hearingProtection, hardHat, ppeComments, rentalVehicle, rentalAgency, vehicleMake, vehicleModel,
                vehicleColour, vehicleLicensePlate, vehicleOperatorName, cityOfDeparture, cityOfArrival,
                projectLocation, projectDescription, estimatedWorkDuration, checkInContactRole, checkInContactName,
                satellitePhone, satellitePhoneNumber, radio, firstAidKit, fireExtinguisher, transportingFuel,
                tdgPlacards, spillKit, workingInTraffic, pylons, trafficSigns, appropriateVehicle, remoteArea,
                workingInIsolation, extremeWeather, transmissionLines, activeMineSite, activeLoggingArea, wildlife,
                fatigue, politicalConflict, riskLevel, preventionMeasures, postRiskLevel, generalComments);

        writeJsonFileToExternalStorage();

        // New email method (attaching .json file instead of .csv)
        File Dir = new File(String.valueOf(getExternalFilesDir(null)) + "/GroundReports");
        String jsonReportTextFileName = "OpenGround_Report.json";
        File jsonReportFile = new File(Dir, jsonReportTextFileName);

        Uri uri = FileProvider.getUriForFile(OpenGroundReport.this, BuildConfig.APPLICATION_ID + ".provider",
                jsonReportFile);

        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("plain/text");
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        intent.putExtra(Intent.EXTRA_EMAIL, new String[] { getString(R.string.email_address) });
        intent.putExtra(Intent.EXTRA_SUBJECT, "Open Ground Report" + "-" + "MOB(" + mobNumber + ")-" + name + "-"
                + userSelectedDateGround + "-" + "Field_Report");
        intent.putExtra(Intent.EXTRA_TEXT, dailyTailgateText);

        if (!jsonReportFile.exists() || !jsonReportFile.canRead()) {
            return;
        }

        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivity(Intent.createChooser(intent, getString(R.string.pick_email_provider)));
        }
    }

    // creates string that goes in the body of the email
    private String createDailyTailgate(String name, String userSelectedDateGround, String submissionDate,
            String reSubmit, String transitDay, String phoneNumber, String mobNumber, String workingAlone,
            String colleagues, String locationStart, String gpsLatitude, String gpsLongitude, String hiVisApparel,
            String clothingForSeason, String safetyRatedFootwear, String personalSurvivalKit,
            String hearingProtection, String hardHat, String ppeComments, String rentalVehicle, String rentalAgency,
            String vehicleMake, String vehicleModel, String vehicleColor, String vehicleLicensePlate,
            String vehicleOperatorsName, String cityOfDeparture, String cityOfArrival, String projectLocation,
            String projectAreaDescription, String estimatedWorkDuration, String checkInContactRole,
            String checkInContactName, String satellitePhone, String satellitePhoneNumber, String radio,
            String firstAidKit, String fireExtinguisher, String transportingFuel, String tdgPlacards,
            String spillKit, String workingInTraffic, String pylons, String trafficSigns, String appropriateVehicle,
            String remoteArea, String workingInIsolation, String extremeWeather, String transmissionsLines,
            String activeMineSite, String activeLoggingArea, String wildlife, String fatigue,
            String politicalConflict, String riskLevel, String preventionMeasures, String postRiskLevel,
            String generalComments) {

        return "\nOpen Ground Report" + "\n" + "\nName: " + " . . . . . . . . . . . . . . . . . . " + name
                + "\nDate: " + " . . . . . . . . . . . . . . . . . . . " + userSelectedDateGround
                + "\nSubmission Date: " + " . . . . . . . . . . " + submissionDate
                + "\nIs this report being resubmitted?" + ". . . " + reSubmit + "\nTransit Day: "
                + ". . . . . . . . . . . . . . " + transitDay + "\nPhone Number: " + " . . . . . . . . . . . "
                + phoneNumber + "\n" + "\nMOB Number: " + " . . . . . . . . . . . " + mobNumber
                + "\nWorking Alone: " + " . . . . . . . . . . . " + workingAlone + "\nColleagues present: "
                + " . . . . . . . . " + colleagues + "\n" + "\nLOCATION DETAILS" + "\nLocation Start: "
                + " . . . . . . . . . . . " + locationStart + "\nGPS Latitude: " + " . . . . . . . . . . . . "
                + gpsLatitude + "\nGPS Longitude: " + " . . . . . . . . . . . " + gpsLongitude + "\n"
                + "\nPPE CHECKLIST" + "\nHi Vis Apparel: " + " . . . . . . . . . . . " + hiVisApparel
                + "\nClothing For Season: " + " . . . . . . " + clothingForSeason + "\nSafety Rated Footwear: "
                + " . . . . " + safetyRatedFootwear + "\nPersonal Survival Kit: " + " . . . . . . "
                + personalSurvivalKit + "\n" + "Hearing Protection: " + ". . . . . . . . " + hearingProtection
                + "\nHard Hat: " + " . . . . . . . . . . . . . . . " + hardHat + "\nPPE Comments: "
                + ". . . . . . . . . . " + ppeComments + "\n" + "\nVEHICLE INFORMATION" + "\nRenting Vehicle?: "
                + " . . . . . . . . . . . . . " + rentalVehicle + "\nRental Agency "
                + " . . . . . . . . . . . . . . . " + rentalAgency + "\nVehicle Make: "
                + " . . . . . . . . . . . . . . . " + vehicleMake + "\nVehicle Model: "
                + " . . . . . . . . . . . . . . . " + vehicleModel + "\nVehicle Colour: "
                + " . . . . . . . . . . . . . . . " + vehicleColor + "\nVehicle License Plate: "
                + " . . . . . . . . . . " + vehicleLicensePlate + "\nVehicle Operators Name: " + " . . . . . . . "
                + vehicleOperatorsName + "\n" + "\nGROUND OPERATIONS INFORMATION" + "\nCity of Departure: "
                + " . . . . . . . . . . " + cityOfDeparture + "\nCity of Arrival: " + " . . . . . . . . . . . . . "
                + cityOfArrival + "\nWhere will you be working?: " + " . . " + projectLocation
                + "\nDescribe your work: " + " . . . . . . . . . " + projectAreaDescription
                + "\nEstimated Work Duration: " + " . . . . . " + estimatedWorkDuration
                + "\nCheck In Contact Role: " + " . . . . . . . " + checkInContactRole + "\nCheck In Contact Name: "
                + " . . . . . . " + checkInContactName + "\n" + "\nSatellite Phone: "
                + " . . . . . . . . . . . . . . . . . " + satellitePhone + "\nSatellite Phone Number: "
                + " . . . . . . . . . . " + satellitePhoneNumber + "\nRadio: "
                + " . . . . . . . . . . . . . . . . . . . . . . . . " + radio + "\nFirst Aid Kit: "
                + " . . . . . . . . . . . . . . . . . . . " + firstAidKit + "\nFire Extinguisher: "
                + " . . . . . . . . . . . . . . . " + fireExtinguisher + "\nTransporting Fuel: "
                + " . . . . . . . . . . . . . . . " + transportingFuel + "\nTDG Placards: "
                + " . . . . . . . . . . . . . . . . . . " + tdgPlacards + "\nSpill Kit: "
                + ". . . . . . . . . . . . . . . . . . . . . . . " + spillKit + "\nWorking In Traffic: "
                + " . . . . . . . . . . . . . . . " + workingInTraffic + "\nPylons: "
                + " . . . . . . . . . . . . . . . . . . . . . . . . " + pylons + "\nTraffic Signs: "
                + " . . . . . . . . . . . . . . . . . . . " + trafficSigns + "\nAppropriate Vehicle: "
                + " . . . . . . . . . . . . . " + appropriateVehicle + "\n" + "\nHAZARD / RISK ASSESSMENT"
                + "\nRemote Area: " + " . . . . . . . . . . . . . . . . . . . . " + remoteArea + "\nWorking Alone: "
                + " . . . . . . . . . . . . . . . . . . . " + workingInIsolation + "\nExtreme Weather: "
                + " . . . . . . . . . . . . . . . . . " + extremeWeather + "\nTransmission Lines: "
                + " . . . . . . . . . . . . . . . . " + transmissionsLines + "\nActive Mine Site: "
                + " . . . . . . . . . . . . . . . . . . " + activeMineSite + "\nActive Logging Area: "
                + " . . . . . . . . . . . . . . . " + activeLoggingArea + "\nWildlife: "
                + " . . . . . . . . . . . . . . . . . . . . . . . . . " + wildlife + "\nFatigue: "
                + " . . . . . . . . . . . . . . . . . . . . . . . . . " + fatigue + "\nPolitical Conflict: "
                + " . . . . . . . . . . . . . . . . . . " + politicalConflict + "\n"
                + "\nPerception of risk level / rating: " + " . . . . . . . " + riskLevel + "\n"
                + "\nPrevention Measures Taken: " + preventionMeasures + "\n"
                + "\nPost Prevention Measures - Perception of risk level / rating: " + " . . " + postRiskLevel
                + "\n" + "\nGeneral Comments: " + generalComments;
    }

    private void gatherValues() {

        userSelectedDateGround = showDate.getText().toString();
        mobNumber = mMobNumber.getText().toString();
        mobNumberInt = Integer.parseInt(mobNumber);
        name = mName.getText().toString().trim();
        phoneNumber = mPhoneNumber.getText().toString();
        reSubmitBool = mResubmit.isChecked();
        reSubmit = reSubmitBool ? "Yes" : "No";
        transitDayBool = mTransitDay.isChecked();
        transitDay = transitDayBool ? "Yes" : "No";
        colleagues = mColleagues.getText().toString();
        workingAloneBool = mWorkingAlone.isChecked();
        workingAlone = workingAloneBool ? "Yes" : "No";

        locationStart = mLocationStart.getText().toString();
        // GPS Location
        gpsLatitude = mGpsLatitude.getText().toString();
        if (gpsLatitude.equals("")) {
            gpsLatitude = "0";
        }
        gpsLatitudeDouble = Double.parseDouble(gpsLatitude);

        gpsLongitude = mGpsLongitude.getText().toString();
        if (gpsLongitude.equals("")) {
            gpsLongitude = "0";
        }
        gpsLongitudeDouble = Double.parseDouble(gpsLongitude);
        //PPE Checklist checkboxes and PPE Comments
        hiVisApparelBool = mHiVisApparel.isChecked();
        hiVisApparel = hiVisApparelBool ? "Yes" : "No";
        clothingForSeasonBool = mClothingForSeason.isChecked();
        clothingForSeason = clothingForSeasonBool ? "Yes" : "No";
        safetyRatedFootwearBool = mSafetyRatedFootwear.isChecked();
        safetyRatedFootwear = safetyRatedFootwearBool ? "Yes" : "No";
        personalSurvivalKitBool = mPersonalSurvivalKit.isChecked();
        personalSurvivalKit = personalSurvivalKitBool ? "Yes" : "No";
        hearingProtectionBool = mHearingProtection.isChecked();
        hearingProtection = hearingProtectionBool ? "Yes" : "No";
        hardHatBool = mHardHat.isChecked();
        hardHat = hardHatBool ? "Yes" : "No";
        ppeComments = mPpeComments.getText().toString();
        // Vehicle Information
        rentalVehicleBool = mRentalVehicle.isChecked();
        rentalVehicle = rentalVehicleBool ? "Yes" : "No";
        rentalAgency = mRentalAgency.getText().toString();
        vehicleMake = mVehicleMake.getText().toString();
        vehicleModel = mVehicleModel.getText().toString();
        vehicleColour = mVehicleColour.getText().toString();
        vehicleLicensePlate = mVehicleLicensePlate.getText().toString();
        vehicleOperatorName = mVehicleOperatorName.getText().toString();
        // Ground Operations Information
        cityOfDeparture = mCityOfDeparture.getText().toString();
        cityOfArrival = mCityOfArrival.getText().toString();
        projectLocation = mProjectLocation.getText().toString();
        projectDescription = mProjectDescription.getText().toString();
        estimatedWorkDuration = mEstimatedWorkDuration.getText().toString();
        checkInContactRole = mCheckInContactRoleSpinner.getSelectedItem().toString();
        if (mCheckInContactRoleSpinner.getSelectedItem().toString().equals("Other")) {
            checkInContactName = mOtherContactName.getText().toString();
        } else {
            checkInContactName = mCheckInContactNameSpinner.getSelectedItem().toString();
        }
        // Satellite Phone
        satellitePhoneBool = mSatellitePhone.isChecked();
        satellitePhone = satellitePhoneBool ? "Yes" : "No";
        satellitePhoneNumberListSelection = mSatPhoneNumberListSpinner.getSelectedItem().toString();
        satellitePhoneNumber = "";
        if (satellitePhoneNumberListSelection.equals("Other")) {
            satellitePhoneNumber = mSatellitePhoneNumber.getText().toString();
        } else {
            if (mSatPhoneNumberListSpinner.getSelectedItem() == getResources().getString(R.string.satPhoneBlack)) {
                satellitePhoneNumber = getResources().getString(R.string.blackSatPhone);
            } else if (mSatPhoneNumberListSpinner.getSelectedItem() == getResources()
                    .getString(R.string.satPhoneBlue)) {
                satellitePhoneNumber = getResources().getString(R.string.blueSatPhone);
            } else if (mSatPhoneNumberListSpinner.getSelectedItem() == getResources()
                    .getString(R.string.satPhoneRed)) {
                satellitePhoneNumber = getResources().getString(R.string.redSatPhone);
            } else if (mSatPhoneNumberListSpinner.getSelectedItem() == getResources()
                    .getString(R.string.satPhoneOrange)) {
                satellitePhoneNumber = getResources().getString(R.string.orangeSatPhone);
            }
        }
        radioBool = mRadio.isChecked();
        radio = radioBool ? "Yes" : "No";
        firstAidKitBool = mFirstAidKit.isChecked();
        firstAidKit = firstAidKitBool ? "Yes" : "No";
        fireExtinguisherBool = mFireExtinguisher.isChecked();
        fireExtinguisher = fireExtinguisherBool ? "Yes" : "No";
        transportingFuelBool = mTransportingFuel.isChecked();
        transportingFuel = transportingFuelBool ? "Yes" : "No";
        tdgPlacardsBool = mTdgPlacards.isChecked();
        tdgPlacards = tdgPlacardsBool ? "Yes" : "No";
        spillKitBool = mSpillKit.isChecked();
        spillKit = spillKitBool ? "Yes" : "No";
        workingInTrafficBool = mWorkingInTraffic.isChecked();
        workingInTraffic = workingInTrafficBool ? "Yes" : "No";
        pylonsBool = mPylons.isChecked();
        pylons = pylonsBool ? "Yes" : "No";
        trafficSignsBool = mTrafficSigns.isChecked();
        trafficSigns = trafficSignsBool ? "Yes" : "No";
        appropriateVehicleBool = mAppropriateVehicle.isChecked();
        appropriateVehicle = appropriateVehicleBool ? "Yes" : "No";
        // Hazard / Risk Assessment
        remoteAreaBool = mRemoteArea.isChecked();
        remoteArea = remoteAreaBool ? "Yes" : "No";
        workingInIsolationBool = mWorkingInIsolation.isChecked();
        workingInIsolation = workingInIsolationBool ? "Yes" : "No";
        extremeWeatherBool = mExtremeWeather.isChecked();
        extremeWeather = extremeWeatherBool ? "Yes" : "No";
        transmissionLinesBool = mTransmissionLines.isChecked();
        transmissionLines = transmissionLinesBool ? "Yes" : "No";
        activeMineSiteBool = mActiveMineSite.isChecked();
        activeMineSite = activeMineSiteBool ? "Yes" : "No";
        activeLoggingAreaBool = mActiveLoggingArea.isChecked();
        activeLoggingArea = activeLoggingAreaBool ? "Yes" : "No";
        wildlifeBool = mWildlife.isChecked();
        wildlife = wildlifeBool ? "Yes" : "No";
        fatigueBool = mFatigue.isChecked();
        fatigue = fatigueBool ? "Yes" : "No";
        politicalConflictBool = mPoliticalConflict.isChecked();
        politicalConflict = politicalConflictBool ? "Yes" : "No";
        // Perception of Risk Level/Rating
        // Returns an integer which represents the selected radio button's ID
        selectedRisk = mRiskLevelRadioGroup.getCheckedRadioButtonId();
        // Gets a reference to our selected radio button. This isn't using Butterknife because it could be 1 of 5 options.
        selectedRiskLevel = findViewById(selectedRisk);
        riskLevel = selectedRiskLevel.getText().toString();

        // Returns an integer which represents the selected radio button's ID
        postSelectedRisk = mPostRiskLevelRadioGroup.getCheckedRadioButtonId();
        // Gets a reference to our selected radio button
        postSelectedRiskLevel = findViewById(postSelectedRisk);
        postRiskLevel = postSelectedRiskLevel.getText().toString();

        preventionMeasures = mPreventionMeasures.getText().toString();
        generalComments = mGeneralComments.getText().toString();
    }

    public void showDatePickerDialog(View v) {
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getSupportFragmentManager(), "datePicker");
    }

    private void loadSharedPreferences() {

        SharedPreferences preferences = getSharedPreferences(COMMON_SHARED_PREFERENCES, Context.MODE_PRIVATE);
        mMobNumber.setText(preferences.getString("mobNumber", ""));
        mName.setText(preferences.getString("name", ""));
        mPhoneNumber.setText(preferences.getString("cellPhoneNumber", ""));

        // initiate SharedPreferences
        SharedPreferences settings = getSharedPreferences(OPEN_GROUND_SHARED_PREFERENCES, Context.MODE_PRIVATE);
        // put in default/saved values
        showDate.setText(settings.getString("groundSubmissionDate", ""));
        if (settings.getBoolean("workingAloneGround", false)) {
            mWorkingAlone.setChecked(true);
            tvColleaguesTextView.setVisibility(View.GONE);
            mColleagues.setVisibility(View.GONE);
        }
        mColleagues.setText(settings.getString("colleaguesGround", ""));
        // Transit Day
        if (settings.getBoolean("transitDayOpenGround", false)) {
            mTransitDay.setChecked(true);
            workLocationCard.setVisibility(View.GONE);
            workDescriptionCard.setVisibility(View.GONE);
            transitDayCard.setBackgroundColor(Color.rgb(210, 51, 224));
            transitDayText.setTextColor(Color.WHITE);
        }
        // Location Details
        mLocationStart.setText(settings.getString("locationStart", ""));
        mGpsLatitude.setText(settings.getString("gpsLatitudeOpenGround", ""));
        mGpsLongitude.setText(settings.getString("gpsLongitudeOpenGround", ""));
        // PPE Checklist
        if (settings.getBoolean("hiVisApparelGround", false)) {
            mHiVisApparel.setChecked(true);
        }
        if (settings.getBoolean("clothingForSeasonGround", false)) {
            mClothingForSeason.setChecked(true);
        }
        if (settings.getBoolean("safetyRatedFootwearGround", false)) {
            mSafetyRatedFootwear.setChecked(true);
        }
        if (settings.getBoolean("personalSurvivalKitGround", false)) {
            mPersonalSurvivalKit.setChecked(true);
        }
        if (settings.getBoolean("hearingProtectionGround", false)) {
            mHearingProtection.setChecked(true);
        }
        if (settings.getBoolean("hardHatGround", false)) {
            mHardHat.setChecked(true);
        }
        mPpeComments.setText(settings.getString("ppeCommentsGround", ""));
        // Vehicle Details
        if (settings.getBoolean("hasRentalVehicle", false)) {
            mRentalVehicle.setChecked(true);
            tvRentalAgencyTv.setVisibility(View.VISIBLE);
            mRentalAgency.setVisibility(View.VISIBLE);
        }
        mRentalAgency.setText(settings.getString("rentalAgency", ""));
        mVehicleMake.setText(settings.getString("vehicleMake", ""));
        mVehicleModel.setText(settings.getString("vehicleModel", ""));
        mVehicleColour.setText(settings.getString("vehicleColor", ""));
        mVehicleLicensePlate.setText(settings.getString("vehicleLicensePlate", ""));
        mVehicleOperatorName.setText(settings.getString("vehicleOperatorName", ""));
        // Ground Operations Information
        mCityOfDeparture.setText(settings.getString("cityOfDepartureGround", ""));
        mCityOfArrival.setText(settings.getString("cityOfArrivalGround", ""));
        mProjectLocation.setText(settings.getString("projectLocationGround", ""));
        mProjectDescription.setText(settings.getString("workDescriptionGround", ""));
        mEstimatedWorkDuration.setText(settings.getString("estimatedWorkDurationGround", ""));
        // Check in Contact
        mCheckInContactRoleSpinner.setSelection(settings.getInt("checkInContactRolePositionGround", 0));
        mCheckInContactNameSpinner.setSelection(settings.getInt("checkInContactDataCheckerPositionGround", 0));
        mOtherContactName.setText(settings.getString("checkInContactOtherNameGround", ""));

        if (settings.getBoolean("satellitePhoneGround", false)) {
            mSatellitePhone.setChecked(true);
            mSatellitePhoneNumberTableRow.setVisibility(View.VISIBLE);
            mSatPhoneNumberListSpinner.setSelection(settings.getInt("satellitePhoneNumberPositionGround", 0));
            if (mSatPhoneNumberListSpinner.getSelectedItem() == getString(R.string.satPhoneOther)) {
                mSatellitePhoneNumber.setText(settings.getString("satellitePhoneNumberOtherGround", ""));
            }
        }
        if (settings.getBoolean("radioGround", false)) {
            mRadio.setChecked(true);
        }
        if (settings.getBoolean("firstAidKitGround", false)) {
            mFirstAidKit.setChecked(true);
        }
        if (settings.getBoolean("fireExtinguisherGround", false)) {
            mFireExtinguisher.setChecked(true);
        }
        if (settings.getBoolean("transportingFuelGround", false)) {
            mTransportingFuel.setChecked(true);
        }
        if (settings.getBoolean("tdgPlacardsGround", false)) {
            mTdgPlacards.setChecked(true);
        }
        if (settings.getBoolean("spillKitGround", false)) {
            mSpillKit.setChecked(true);
        }
        if (settings.getBoolean("workingInTrafficGround", false)) {
            mWorkingInTraffic.setChecked(true);
        }
        if (settings.getBoolean("pylonsGround", false)) {
            mPylons.setChecked(true);
        }
        if (settings.getBoolean("trafficSignsGround", false)) {
            mTrafficSigns.setChecked(true);
        }
        if (settings.getBoolean("appropriateVehicleGround", false)) {
            mAppropriateVehicle.setChecked(true);
        }
        // Hazard / Risk Assessment
        if (settings.getBoolean("remoteAreaGround", false)) {
            mRemoteArea.setChecked(true);
        }
        if (settings.getBoolean("workingInIsolationGround", false)) {
            mWorkingInIsolation.setChecked(true);
        }
        if (settings.getBoolean("extremeWeatherGround", false)) {
            mExtremeWeather.setChecked(true);
        }
        if (settings.getBoolean("transmissionLinesGround", false)) {
            mTransmissionLines.setChecked(true);
        }
        if (settings.getBoolean("activeMineSiteGround", false)) {
            mActiveMineSite.setChecked(true);
        }
        if (settings.getBoolean("activeLoggingAreaGround", false)) {
            mActiveLoggingArea.setChecked(true);
        }
        if (settings.getBoolean("wildLifeGround", false)) {
            mWildlife.setChecked(true);
        }
        if (settings.getBoolean("fatigueGround", false)) {
            mFatigue.setChecked(true);
        }
        if (settings.getBoolean("politicalConflictGround", false)) {
            mPoliticalConflict.setChecked(true);
        }
        // Perception of Risk Radio Group Buttons
        if (settings.getBoolean("minimalRisk", false)) {
            mMinimalRisk.setChecked(true);
        }
        if (settings.getBoolean("lowRisk", false)) {
            mLowRisk.setChecked(true);
        }
        if (settings.getBoolean("mediumRisk", false)) {
            mMediumRisk.setChecked(true);
        }
        if (settings.getBoolean("highRisk", false)) {
            mHighRisk.setChecked(true);
        }
        if (settings.getBoolean("veryHighRisk", false)) {
            mVeryHighRisk.setChecked(true);
        }
        mPreventionMeasures.setText(settings.getString("preventionMeasuresGround", ""));
        // Post Prevention Measures - Perception of Risk Radio Group Buttons
        if (settings.getBoolean("postMinimalRisk", false)) {
            mPostMinimalRisk.setChecked(true);
        }
        if (settings.getBoolean("postLowRisk", false)) {
            mPostLowRisk.setChecked(true);
        }
        if (settings.getBoolean("postMediumRisk", false)) {
            mPostMediumRisk.setChecked(true);
        }
        if (settings.getBoolean("postHighRisk", false)) {
            mPostHighRisk.setChecked(true);
            safetyNotice.setVisibility(View.VISIBLE);
        }
        if (settings.getBoolean("postVeryHighRisk", false)) {
            mPostVeryHighRisk.setChecked(true);
            safetyNotice.setVisibility(View.VISIBLE);
        }
        mGeneralComments.setText(settings.getString("generalCommentsGround", ""));
    }

    private void savedSharedPreferences() {
        // this first instance of SharedPreferences is for values that should be saved across activities (name, number, mobNumber)
        SharedPreferences preferences = getSharedPreferences(COMMON_SHARED_PREFERENCES, Context.MODE_PRIVATE);
        SharedPreferences.Editor constantsEditor = preferences.edit();
        constantsEditor.putString("mobNumber", mMobNumber.getText().toString());
        constantsEditor.putString("name", mName.getText().toString());
        constantsEditor.putString("cellPhoneNumber", mPhoneNumber.getText().toString());
        constantsEditor.apply();

        // second instance of SharedPreferences is for Activity specific values
        SharedPreferences settings = getSharedPreferences(OPEN_GROUND_SHARED_PREFERENCES, Context.MODE_PRIVATE);
        // to makes changes we need to get an editor
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("groundSubmissionDate", showDate.getText().toString());
        editor.putBoolean("transitDayOpenGround", mTransitDay.isChecked());
        editor.putBoolean("workingAloneGround", mWorkingAlone.isChecked());
        editor.putString("colleaguesGround", mColleagues.getText().toString());
        // Location Details
        editor.putString("locationStart", mLocationStart.getText().toString());
        editor.putString("gpsLatitudeOpenGround", mGpsLatitude.getText().toString());
        editor.putString("gpsLongitudeOpenGround", mGpsLongitude.getText().toString());
        // PPE Checklist
        editor.putBoolean("hiVisApparelGround", mHiVisApparel.isChecked());
        editor.putBoolean("clothingForSeasonGround", mClothingForSeason.isChecked());
        editor.putBoolean("safetyRatedFootwearGround", mSafetyRatedFootwear.isChecked());
        editor.putBoolean("personalSurvivalKitGround", mPersonalSurvivalKit.isChecked());
        editor.putBoolean("hearingProtectionGround", mHearingProtection.isChecked());
        editor.putBoolean("hardHatGround", mHardHat.isChecked());
        editor.putString("ppeCommentsGround", mPpeComments.getText().toString());
        // Vehicle Details
        editor.putBoolean("hasRentalVehicle", mRentalVehicle.isChecked());
        editor.putString("rentalAgency", mRentalAgency.getText().toString());
        editor.putString("vehicleMake", mVehicleMake.getText().toString());
        editor.putString("vehicleModel", mVehicleModel.getText().toString());
        editor.putString("vehicleColor", mVehicleColour.getText().toString());
        editor.putString("vehicleLicensePlate", mVehicleLicensePlate.getText().toString());
        editor.putString("vehicleOperatorName", mVehicleOperatorName.getText().toString());
        // Ground Operations Information
        editor.putString("cityOfDepartureGround", mCityOfDeparture.getText().toString());
        editor.putString("cityOfArrivalGround", mCityOfArrival.getText().toString());
        editor.putString("projectLocationGround", mProjectLocation.getText().toString());
        editor.putString("workDescriptionGround", mProjectDescription.getText().toString());
        editor.putString("estimatedWorkDurationGround", mEstimatedWorkDuration.getText().toString());
        // check in contact name spinner
        savedCheckInContactRolePosition = mCheckInContactRoleSpinner.getSelectedItemPosition();
        savedCheckInContactOtherNamePosition = mCheckInContactNameSpinner.getSelectedItemPosition();
        editor.putInt("checkInContactRolePositionGround", savedCheckInContactRolePosition);
        editor.putInt("checkInContactDataCheckerPositionGround", savedCheckInContactOtherNamePosition);
        editor.putString("checkInContactOtherNameGround", mOtherContactName.getText().toString());
        // Ground Operations Information - checkboxes
        // Satellite Phone
        editor.putBoolean("satellitePhoneGround", mSatellitePhone.isChecked());
        savedSatNumberPosition = mSatPhoneNumberListSpinner.getSelectedItemPosition();
        if (mSatellitePhone.isChecked()) {
            editor.putInt("satellitePhoneNumberPositionGround", savedSatNumberPosition);
            if (mSatPhoneNumberListSpinner.getSelectedItem() == getResources().getString(R.string.satPhoneOther)) {
                editor.putString("satellitePhoneNumberOtherGround", mSatellitePhoneNumber.getText().toString());
            }
        } else {
            editor.putInt("satellitePhoneNumberPositionGround", 0);
        }
        editor.putBoolean("radioGround", mRadio.isChecked());
        editor.putBoolean("firstAidKitGround", mFirstAidKit.isChecked());
        editor.putBoolean("fireExtinguisherGround", mFireExtinguisher.isChecked());
        editor.putBoolean("transportingFuelGround", mTransportingFuel.isChecked());
        editor.putBoolean("tdgPlacardsGround", mTdgPlacards.isChecked());
        editor.putBoolean("spillKitGround", mSpillKit.isChecked());
        editor.putBoolean("workingInTrafficGround", mWorkingInTraffic.isChecked());
        editor.putBoolean("pylonsGround", mPylons.isChecked());
        editor.putBoolean("trafficSignsGround", mTrafficSigns.isChecked());
        editor.putBoolean("appropriateVehicleGround", mAppropriateVehicle.isChecked());
        // Hazard / Risk Assessment
        editor.putBoolean("remoteAreaGround", mRemoteArea.isChecked());
        editor.putBoolean("workingInIsolationGround", mWorkingInIsolation.isChecked());
        editor.putBoolean("extremeWeatherGround", mExtremeWeather.isChecked());
        editor.putBoolean("transmissionLinesGround", mTransmissionLines.isChecked());
        editor.putBoolean("activeMineSiteGround", mActiveMineSite.isChecked());
        editor.putBoolean("activeLoggingAreaGround", mActiveLoggingArea.isChecked());
        editor.putBoolean("wildLifeGround", mWildlife.isChecked());
        editor.putBoolean("fatigueGround", mFatigue.isChecked());
        editor.putBoolean("politicalConflictGround", mPoliticalConflict.isChecked());
        // perception of risk
        editor.putBoolean("minimalRisk", mMinimalRisk.isChecked());
        editor.putBoolean("lowRisk", mLowRisk.isChecked());
        editor.putBoolean("mediumRisk", mMediumRisk.isChecked());
        editor.putBoolean("highRisk", mHighRisk.isChecked());
        editor.putBoolean("veryHighRisk", mVeryHighRisk.isChecked());
        editor.putString("preventionMeasuresGround", mPreventionMeasures.getText().toString());
        // post perception of risk
        editor.putBoolean("postMinimalRisk", mPostMinimalRisk.isChecked());
        editor.putBoolean("postLowRisk", mPostLowRisk.isChecked());
        editor.putBoolean("postMediumRisk", mPostMediumRisk.isChecked());
        editor.putBoolean("postHighRisk", mPostHighRisk.isChecked());
        editor.putBoolean("postVeryHighRisk", mPostVeryHighRisk.isChecked());
        editor.putString("generalCommentsGround", mGeneralComments.getText().toString());
        editor.apply();
    }
}