Android Open Source - Joetz-Android-V2 Add Person Activity






From Project

Back to project page Joetz-Android-V2.

License

The source code is released under:

GNU General Public License

If you think the Android project Joetz-Android-V2 listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.example.jens.myapplication.booking;
//from w ww.  j a  v a 2 s. com
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.jens.myapplication.R;
import com.example.jens.myapplication.apimanager.ApiConnection;
import com.example.jens.myapplication.apimanager.SimpleRequestTask;
import com.example.jens.myapplication.apimanager.manager.ProfileManager;
import com.example.jens.myapplication.domain.Person;
import com.example.jens.myapplication.domain.binding.PersonValidatorBinding;
import com.example.jens.myapplication.domain.binding.ValidatorBinding;
import com.example.jens.myapplication.domain.converter.ErrorConverter;
import com.example.jens.myapplication.domain.validator.PersonValidator;
import com.example.jens.myapplication.sam.JoetzApplication;
import com.example.jens.myapplication.util.ActivityUtils;
import com.example.jens.myapplication.util.MyMonths;
import com.example.jens.myapplication.view.MyLinearLayout;

import org.joda.time.DateTime;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class AddPersonActivity extends Activity {
    public static final String EXTRA_PERSON = "person";
    public static final String EXTRA_INDEX = "index";
    public static final String EXTRA_REQUEST_CODE = "requestCode";
    public static final String EXTRA_TYPE = "typeactivity";

    public static final int TYPE_PERSONS = 0;
    public static final int TYPE_PARTICIPANT = 1;

    public static final int REQUEST_NEW = 0;
    public static final int REQUEST_EDIT = 1;

    private static final String SAVE_PERSON = "argperson";

    private MyLinearLayout mLlyRoot;

    private int mType;

    private Button mBtnAdd;
    private Button mBtnCancel;
    private CheckBox mChkAddToMyPersons;
    private CheckBox mChkSameAddress;

    private TextView mTxtTitle;

    private EditText mTxtRijksRegisterNummer;
    private EditText mTxtFirstName;
    private EditText mTxtLastName;
    private EditText mTxtBirthDate;
    private EditText mTxtStreet;
    private EditText mTxtHouseNumber;
    private EditText mTxtBus;
    private EditText mTxtCity;
    private EditText mTxtPostalCode;

    private Person mPerson;
    private PersonValidator mPersonValidator;

    private int mIndex;
    private int mRequestCode;

    private List<ValidatorBinding> mBindings;
    private List<ValidatorBinding> mBindingsAddress = new LinkedList<>();
    private ValidatorBinding mDobValidator;

    private Map<Integer, String> mPreviousValues = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_add_participant);

        mLlyRoot = (MyLinearLayout) findViewById(R.id.llyRootLinearLayout);
        mLlyRoot.setOnDispatchTouchEventListener(new MyLinearLayout.OnDispatchTouchEventListener() {
            @Override
            public void onDispatchTouchEvent(MotionEvent e) {
                clearFocus();
            }
        });

        if (savedInstanceState != null) {
            mPerson = savedInstanceState.getParcelable(SAVE_PERSON);
        } else {
            if (getIntent().getExtras() != null && getIntent().getExtras().containsKey(EXTRA_PERSON)) {
                mPerson = getIntent().getExtras().getParcelable(EXTRA_PERSON);
            } else {
                mPerson = new Person();
            }
        }

        if (getIntent().getExtras() != null) {
            if (getIntent().getExtras().containsKey(EXTRA_INDEX)) {
                mIndex = getIntent().getExtras().getInt(EXTRA_INDEX);
            }
            if (getIntent().getExtras().containsKey(EXTRA_TYPE)) {
                mType = getIntent().getExtras().getInt(EXTRA_TYPE);
            } else {
                mType = TYPE_PARTICIPANT;
            }
            mRequestCode = getIntent().getExtras().getInt(EXTRA_REQUEST_CODE);
        } else {
            mType = TYPE_PARTICIPANT;
        }

        mPersonValidator = new PersonValidator(mPerson);
        mBindings = new LinkedList<ValidatorBinding>();

        mTxtRijksRegisterNummer = (EditText) findViewById(R.id.txtRijksRegisterNummer);
        mTxtFirstName = (EditText) findViewById(R.id.txtFirstName);
        mTxtLastName = (EditText) findViewById(R.id.txtLastName);
        mTxtBirthDate = (EditText) findViewById(R.id.txtDateOfBirth);
        mTxtBirthDate.setKeyListener(null);
        mTxtStreet = (EditText) findViewById(R.id.txtStreet);
        mTxtHouseNumber = (EditText) findViewById(R.id.txtHouseNumber);
        mTxtBus = (EditText) findViewById(R.id.txtBus);
        mTxtCity = (EditText) findViewById(R.id.txtCity);
        mTxtPostalCode = (EditText) findViewById(R.id.txtPostalCode);

        mTxtTitle = (TextView) findViewById(R.id.txtTitle);
        if (mType == TYPE_PERSONS) {
            mTxtTitle.setText(R.string.add_person);
        }

        mBtnAdd = (Button) findViewById(R.id.btnAdd);
        mBtnCancel = (Button) findViewById(R.id.btnCancel);
        //mBtnChooseDob = (Button) findViewById(R.id.btnChooseDob);

        //Different actinos for different states of the fragment
        mBtnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mType == TYPE_PERSONS){
                    if(mRequestCode == REQUEST_EDIT){
                        editPerson();
                    }else{
                        addPerson();
                    }
                }else{
                    addParticipant();
                }
            }
        });

        mBtnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cancel();
            }
        });

        mChkAddToMyPersons = (CheckBox) findViewById(R.id.chkAddToMyPersons);
        if(!(mRequestCode == REQUEST_NEW) || mType != TYPE_PARTICIPANT){
            mChkAddToMyPersons.setVisibility(View.GONE);
        }

        mChkSameAddress = (CheckBox) findViewById(R.id.chkSameAddress);
        Person uPerson = JoetzApplication.getContext().getLoginManager().getUser().getPerson();
        if(uPerson.getStreet() == null || uPerson.getStreet().isEmpty()){
            mChkSameAddress.setVisibility(View.GONE);
        }else{
            mChkSameAddress.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    changeCheckedSameAddress(isChecked);
                }
            });
        }

        if (mRequestCode == REQUEST_EDIT) {
            mBtnAdd.setText(R.string.change);
            if(mType == TYPE_PERSONS){
                mTxtTitle.setText(R.string.edit_person);
            }else{
                mTxtTitle.setText(R.string.edit_participant);
            }
        }

        initValidators();
        fillDateOfBirth();
//        validateAll();
    }

    /**
     * Clear focus of the textfields (for setError issues)
     */
    private void clearFocus() {
        View view = getCurrentFocus();
        if (view == null || view == mLlyRoot) {
            return;
        }

        mLlyRoot.requestFocus();
    }

    /**
     * Choose a date of birth for the person
     */
    private void chooseDob() {
        ActivityUtils.chooseDateOfBirth(this, mPerson, new ActivityUtils.OnDateChosenListener() {
            @Override
            public void onDateChosen(int year, int monthOfYear, int dayOfMonth) {
                mPerson.setDateOfBirth(new DateTime(year, monthOfYear, dayOfMonth, 0, 0));
                //fillDateOfBirth();
                //validateDateOfBirth();
                mDobValidator.fillValue();
                mDobValidator.validate();
                mTxtBirthDate.requestFocus();
            }
        });
    }

    /**
     * Fill the date of birth textfield (not handled by binding)
     */
    private void fillDateOfBirth() {
        DateTime dob = mPerson.getDateOfBirth();
        if (dob == null) {
            return;
        }
        String monthString = getString(MyMonths.getMonthShortResId(dob.getMonthOfYear()));
        mTxtBirthDate.setText(dob.getDayOfMonth() + " " + monthString + " " + dob.getYear());
    }

    /**
     * Called when the "same address" checkbox is checked or unchecked
     * @param checked
     */
    private void changeCheckedSameAddress(boolean checked){
        Person me = JoetzApplication.getContext().getLoginManager().getUser().getPerson();
        fillIfAvailable(mTxtStreet, me.getStreet(), checked);
        fillIfAvailable(mTxtHouseNumber, me.getHouseNumber() > 0
                ? String.valueOf(me.getHouseNumber()) : "", checked);
        fillIfAvailable(mTxtBus, me.getBus(), checked);
        fillIfAvailable(mTxtCity, me.getCity(), checked);
        fillIfAvailable(mTxtPostalCode, me.getPostalCode() > 0
                ? String.valueOf(me.getPostalCode()) : "", checked);

        for(ValidatorBinding binding : mBindingsAddress){
            binding.validate();
        }
    }

    /**
     * [Used for sameaddress checked change]<br />
     * Fill the field with value if the value is not empty or null or empty the field <br />
     * if checked is false
     * @param field The textfield that should be changed
     * @param value The value to be entered in the field
     * @param checked Whether the checkbox for sameadress is checked or not
     */
    private void fillIfAvailable(EditText field, String value, boolean checked){
        if(value == null || value.isEmpty()){
            return;
        }

        if(checked){
            mPreviousValues.put(field.getId(), field.getText().toString());
            field.setText(value);
            field.setEnabled(false);
        }else{
            field.setText(mPreviousValues.get(field.getId()));
            field.setEnabled(true);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelable(SAVE_PERSON, mPerson);
    }

    /**
     * Check if the form contains any validation errors
     * @return True if errors are present, false if no errors
     */
    private boolean existsErrors() {
        validateDateOfBirth();
        validateAll();

        if (mTxtBirthDate.getError() != null) {
            return true;
        }
        for (ValidatorBinding binding : mBindings) {
            if (binding.getView().getError() != null) {
                return true;
            }
        }
        return false;
    }

    /**
     * Check if errors are present (using existsErrors) and show a Toast if there are errors
     * @return
     *
     */
    private boolean checkErrors() {
        if (existsErrors()) {
            Toast.makeText(this, R.string.error_errors_exist, Toast.LENGTH_SHORT).show();
            return true;
        }
        return false;
    }

    /**
     * Call when the mode is "PERSON" and request type is "EDIT"
     */
    private void editPerson(){
        if(checkErrors()){
            return;
        }

        setViewsEnabled(false);
        SimpleRequestTask afterTask = new SimpleRequestTask() {
            @Override
            public void doTask(int statusCode) {
                if(ApiConnection.isSuccessCode(statusCode)){
                    AlertDialog.OnClickListener neutralListener = new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finishWithResult();
                        }
                    };

                    AlertDialog.OnCancelListener cancelListener = new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            finishWithResult();
                        }
                    };

                    new AlertDialog.Builder(AddPersonActivity.this)
                            .setMessage(R.string.edit_person_success)
                            .setNeutralButton(R.string.ok, neutralListener)
                            .setOnCancelListener(cancelListener).create().show();
                }else{
                    new AlertDialog.Builder(AddPersonActivity.this)
                            .setMessage(R.string.edit_person_failed)
                            .setNeutralButton(R.string.ok, null);
                }
                setViewsEnabled(true);
            }
        };
        ProfileManager.editPerson(mPerson, afterTask);
    }

    /**
     * Call when the mode is "PERSON" and the request type is "ADD"
     */
    private void addPerson(){
        if(checkErrors()){
            return;
        }

        setViewsEnabled(false);
        SimpleRequestTask afterTask = new SimpleRequestTask() {
            @Override
            public void doTask(int statusCode) {
                if(ApiConnection.isSuccessCode(statusCode)){
                    AlertDialog.OnClickListener neutralListener = new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finishWithResult();
                        }
                    };

                    AlertDialog.OnCancelListener cancelListener = new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            finishWithResult();
                        }
                    };

                    new AlertDialog.Builder(AddPersonActivity.this)
                            .setMessage(R.string.add_person_success)
                            .setNeutralButton(R.string.ok, neutralListener)
                            .setOnCancelListener(cancelListener).create().show();
                }else{
                    new AlertDialog.Builder(AddPersonActivity.this)
                            .setMessage(R.string.add_person_failed)
                            .setNeutralButton(R.string.ok, null);
                }
                setViewsEnabled(true);
            }
        };
        ProfileManager.addPerson(mPerson, afterTask);
    }

    /**
     * Set the usable fields enabled or disabled during requests
     * @param enabled true if fields should be enabled, false for disabled
     */
    private void setViewsEnabled(boolean enabled){
        mBtnAdd.setEnabled(enabled);
        for(ValidatorBinding binding : mBindings){
            binding.getView().setEnabled(enabled);
        }
    }

    /**
     * Call when the mode is "PARTICIPANT" and request type either ADD or EDIT
     */
    private void addParticipant() {
        if (checkErrors()) {
            return;
        }

        if(mRequestCode == REQUEST_NEW && mChkAddToMyPersons.isChecked()){
            ProfileManager.addPerson(mPerson, null);
        }

        if(mRequestCode == REQUEST_EDIT){
            //Log.v("AddPersonActivity", "Edited person: personId: " + mPerson.getId());
            if(mPerson.getId() >= 0){
                ProfileManager.editPerson(mPerson, null);
            }
        }

        finishWithResult();
    }

    /**
     * Set the requested data as result with setResult and finish the activity
     */
    private void finishWithResult(){
        Intent i = new Intent();
        i.putExtra(EXTRA_PERSON, mPerson);
        i.putExtra(EXTRA_INDEX, mIndex);
        setResult(RESULT_OK, i);
        finish();
    }

    /**
     * Finish the activity with a cancelled result
     */
    private void cancel() {
        setResult(RESULT_CANCELED);
        finish();
    }

    /**
     * Initialize the bindings for the edit texts
     */
    private void initValidators() {
        mBindings.clear();

        mBindings.add(new PersonValidatorBinding(mPersonValidator,
                mTxtRijksRegisterNummer, PersonValidatorBinding.FIELD_RIJKSREGISTERNUMMER,
                mTxtRijksRegisterNummer.getHint().toString()));

        mBindings.add(new PersonValidatorBinding(mPersonValidator,
                mTxtFirstName, PersonValidatorBinding.FIELD_FIRST_NAME,
                mTxtFirstName.getHint().toString()));

        mBindings.add(new PersonValidatorBinding(mPersonValidator,
                mTxtLastName, PersonValidatorBinding.FIELD_LAST_NAME,
                mTxtLastName.getHint().toString()));

        ValidatorBinding bindingStreet = new PersonValidatorBinding(mPersonValidator,
                mTxtStreet, PersonValidatorBinding.FIELD_STREET,
                mTxtStreet.getHint().toString());
        mBindings.add(bindingStreet);
        mBindingsAddress.add(bindingStreet);

        ValidatorBinding bindingHouseNumber = new PersonValidatorBinding(mPersonValidator,
                mTxtHouseNumber, PersonValidatorBinding.FIELD_HOUSE_NUMBER,
                mTxtHouseNumber.getHint().toString());
        mBindings.add(bindingHouseNumber);
        mBindingsAddress.add(bindingHouseNumber);

        ValidatorBinding bindingBus = new PersonValidatorBinding(mPersonValidator,
                mTxtBus, PersonValidatorBinding.FIELD_BUS,
                mTxtBus.getHint().toString(), false);
        mBindings.add(bindingBus);
        mBindingsAddress.add(bindingBus);

        ValidatorBinding bindingCity = new PersonValidatorBinding(mPersonValidator,
                mTxtCity, PersonValidatorBinding.FIELD_CITY,
                mTxtCity.getHint().toString());
        mBindings.add(bindingCity);
        mBindingsAddress.add(bindingCity);

        ValidatorBinding bindingPostalCode = new PersonValidatorBinding(mPersonValidator,
                mTxtPostalCode, PersonValidatorBinding.FIELD_POSTAL_CODE,
                mTxtPostalCode.getHint().toString());
        mBindings.add(bindingPostalCode);
        mBindingsAddress.add(bindingPostalCode);

        mDobValidator = new PersonValidatorBinding(mPersonValidator,
                mTxtBirthDate, PersonValidatorBinding.FIELD_DATE_OF_BIRTH,
                mTxtBirthDate.getHint().toString());
        mDobValidator.addOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    chooseDob();
                }
            }
        });
    }

    /**
     * Manually validate the date of birth
     */
    private void validateDateOfBirth() {
        if (mTxtBirthDate.getText().toString().isEmpty()) {
            mTxtBirthDate.setError(getString(R.string.$_need_filled_in, mTxtBirthDate.getHint().toString()));
            return;
        }
        List<Integer> errors = new LinkedList<Integer>();
        mPersonValidator.validateDateOfBirth(errors);

        mTxtBirthDate.setError(
                ErrorConverter.createErrorsString(errors, mTxtBirthDate.getHint().toString()));
    }

    /**
     * Validate all the fields
     */
    private void validateAll() {
        validateDateOfBirth();
        for (ValidatorBinding binding : mBindings) {
            binding.validate();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            // This ID represents the Home or Up button. In the case of this
            cancel();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}




Java Source Code List

com.example.jens.myapplication.ApplicationTest.java
com.example.jens.myapplication.account.FragmentAccount.java
com.example.jens.myapplication.account.LoginDialogActivity.java
com.example.jens.myapplication.account.LoginFragment.java
com.example.jens.myapplication.account.PersonsFragment.java
com.example.jens.myapplication.account.ProfileFragment.java
com.example.jens.myapplication.account.RegisterDialogActivity.java
com.example.jens.myapplication.account.RegisterFragment.java
com.example.jens.myapplication.account.TabsPagerAdapter.java
com.example.jens.myapplication.activities.ActivityDetailActivity.java
com.example.jens.myapplication.activities.ActivityDetailFragment.java
com.example.jens.myapplication.activities.FragmentListActivities.java
com.example.jens.myapplication.activities.JoetzActivitiesAdapter.java
com.example.jens.myapplication.activities.JoetzActivity.java
com.example.jens.myapplication.activities.StartActivity.java
com.example.jens.myapplication.apimanager.ApiConnection.java
com.example.jens.myapplication.apimanager.CancellableTask.java
com.example.jens.myapplication.apimanager.JSONParsingTask.java
com.example.jens.myapplication.apimanager.PostRequestTask.java
com.example.jens.myapplication.apimanager.RequestParams.java
com.example.jens.myapplication.apimanager.SimpleRequestTask.java
com.example.jens.myapplication.apimanager.filter.PersonFilter.java
com.example.jens.myapplication.apimanager.manager.ActivityManager.java
com.example.jens.myapplication.apimanager.manager.AuthToken.java
com.example.jens.myapplication.apimanager.manager.BookingManager.java
com.example.jens.myapplication.apimanager.manager.CampManager.java
com.example.jens.myapplication.apimanager.manager.ImageManager.java
com.example.jens.myapplication.apimanager.manager.LoginManager.java
com.example.jens.myapplication.apimanager.manager.ProfileManager.java
com.example.jens.myapplication.apimanager.manager.RegisterManager.java
com.example.jens.myapplication.booking.AddPersonActivity.java
com.example.jens.myapplication.booking.BookingActivity.java
com.example.jens.myapplication.booking.BookingBondFragment.java
com.example.jens.myapplication.booking.BookingContactFragment.java
com.example.jens.myapplication.booking.BookingExtraFragment.java
com.example.jens.myapplication.booking.BookingParticipantsFragment.java
com.example.jens.myapplication.bookingHistory.BookingHistoryDetailActivity.java
com.example.jens.myapplication.bookingHistory.BookingHistoryDetailFragment.java
com.example.jens.myapplication.bookingHistory.BookingHistoryOverviewFragment.java
com.example.jens.myapplication.bookingHistory.BookingsAdapter.java
com.example.jens.myapplication.calendar.FragmentCalendar.java
com.example.jens.myapplication.calendar.KalenderAdapter.java
com.example.jens.myapplication.calendar.KalenderItem.java
com.example.jens.myapplication.camps.CampAdapter.java
com.example.jens.myapplication.camps.CampDetailActivity.java
com.example.jens.myapplication.camps.CampFilterActivity.java
com.example.jens.myapplication.camps.FilterFragment.java
com.example.jens.myapplication.camps.FragmentListCamps.java
com.example.jens.myapplication.camps.ImageActivity.java
com.example.jens.myapplication.camps.ImagePagerFragment.java
com.example.jens.myapplication.camps.InfoFragment.java
com.example.jens.myapplication.camps.PhotoFragment.java
com.example.jens.myapplication.camps.RecyclerItemClickListener.java
com.example.jens.myapplication.camps.SquareImageView.java
com.example.jens.myapplication.camps.TabsPagerAdapter.java
com.example.jens.myapplication.domain.BookingStatus.java
com.example.jens.myapplication.domain.Booking.java
com.example.jens.myapplication.domain.Camp.java
com.example.jens.myapplication.domain.PeriodCategory.java
com.example.jens.myapplication.domain.Person.java
com.example.jens.myapplication.domain.UserRole.java
com.example.jens.myapplication.domain.User.java
com.example.jens.myapplication.domain.binding.PersonValidatorBinding.java
com.example.jens.myapplication.domain.binding.UserValidatorBinding.java
com.example.jens.myapplication.domain.binding.ValidatorBinding.java
com.example.jens.myapplication.domain.converter.ErrorConverter.java
com.example.jens.myapplication.domain.converter.MyStringParser.java
com.example.jens.myapplication.domain.converter.UnixDateTimeConverter.java
com.example.jens.myapplication.domain.validator.PersonValidator.java
com.example.jens.myapplication.domain.validator.UserValidator.java
com.example.jens.myapplication.domain.validator.Validator.java
com.example.jens.myapplication.home.AanbevolenAdapter.java
com.example.jens.myapplication.home.HomeFragment.java
com.example.jens.myapplication.home.ImageSlideAdapter.java
com.example.jens.myapplication.home.Reclame.java
com.example.jens.myapplication.lib.RangeSeekBar.java
com.example.jens.myapplication.main.MainActivity.java
com.example.jens.myapplication.main.NavDrawerAdapter.java
com.example.jens.myapplication.main.NavDrawerItem.java
com.example.jens.myapplication.main.NavMenuItem.java
com.example.jens.myapplication.main.NavMenuSection.java
com.example.jens.myapplication.sam.JoetzApplication.java
com.example.jens.myapplication.sam.MyFragment.java
com.example.jens.myapplication.sam.MySaveableFragment.java
com.example.jens.myapplication.util.AESEncryption.java
com.example.jens.myapplication.util.ActivityUtils.java
com.example.jens.myapplication.util.BindingUtils.java
com.example.jens.myapplication.util.DateTimeStringConverter.java
com.example.jens.myapplication.util.JsonUtils.java
com.example.jens.myapplication.util.MyMonths.java
com.example.jens.myapplication.util.StringUtils.java
com.example.jens.myapplication.view.MyLinearLayout.java