Java tutorial
package nl.inversion.carexpense; import java.text.DateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import com.bugsense.trace.BugSenseHandler; import android.os.Bundle; import android.app.Activity; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.database.Cursor; import android.graphics.Color; import android.support.v4.app.NavUtils; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.DatePicker; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class EditCar_Activity extends Activity { private DatabaseUtil dbHelper; boolean saved = false; int changed = 0; int numberOfBlankFields = 0; int carID = 0; int red = Color.rgb(255, 100, 100); int black = Color.rgb(10, 10, 10); private static final String BugsenseAPIKey = "c05fc191"; TextView purDateInput; TextView MOTInput; TextView buildDateInput; TextView carMakeLabel; TextView carModelLabel; EditText carMakeInput; EditText carModelInput; EditText licenseplateInput; EditText purPriceInput; String carMake = null; String carModel = null; int purPrice = 0; String licensePlate = null; long purDate = 0L; long MOT = 0L; long buildDate = 0L; int buildDateYear, buildDateMonth, buildDateDay; int MOTDateYear, MOTDateMonth, MOTDateDay; int purDateYear, purDateMonth, purDateDay; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); BugSenseHandler.initAndStartSession(this, BugsenseAPIKey); setContentView(R.layout.activity_edit_car); // Get Intent extra values Bundle extras = getIntent().getExtras(); if (extras != null) { carID = extras.getInt("CarID"); } // Open database dbHelper = new DatabaseUtil(this); dbHelper.open(); putCarData(carID); addListenerOnTextViews(); } private void putCarData(int CarID) { Cursor cursor = dbHelper.getCar(CarID); purDateInput = (TextView) findViewById(R.id.editPurDateInput); MOTInput = (TextView) findViewById(R.id.editMOTInput); buildDateInput = (TextView) findViewById(R.id.editBuildDateInput); carMakeInput = (EditText) findViewById(R.id.editMakeInput); carModelInput = (EditText) findViewById(R.id.editModelInput); licenseplateInput = (EditText) findViewById(R.id.editLicenseplateInput); purPriceInput = (EditText) findViewById(R.id.editPurPriceInput); // Set data from DB in text views carMakeInput.setText(cursor.getString(cursor.getColumnIndexOrThrow("make"))); carModelInput.setText(cursor.getString(cursor.getColumnIndexOrThrow("model"))); licenseplateInput.setText(cursor.getString(cursor.getColumnIndexOrThrow("licenseplate"))); purPriceInput.setText(Integer.toString(cursor.getInt(cursor.getColumnIndexOrThrow("purPrice")))); // Get dates from DB purDate = cursor.getLong(cursor.getColumnIndexOrThrow("purDate")); MOT = cursor.getLong(cursor.getColumnIndexOrThrow("MOT")); buildDate = cursor.getLong(cursor.getColumnIndexOrThrow("buildDate")); buildDateYear = Utils.epochToYear(buildDate); buildDateMonth = Utils.epochToMonth(buildDate); buildDateDay = Utils.epochToDay(buildDate); MOTDateYear = Utils.epochToYear(MOT); MOTDateMonth = Utils.epochToMonth(MOT); MOTDateDay = Utils.epochToDay(MOT); purDateYear = Utils.epochToYear(purDate); purDateMonth = Utils.epochToMonth(purDate); purDateDay = Utils.epochToDay(purDate); // Set dates to text views purDateInput.setText(Utils.epochToDate(this, purDate)); MOTInput.setText(Utils.epochToDate(this, MOT)); buildDateInput.setText(Utils.epochToDate(this, buildDate)); cursor.close(); } public void addListenerOnTextViews() { TextView purDateInput = (TextView) findViewById(R.id.editPurDateInput); TextView MOTInput = (TextView) findViewById(R.id.editMOTInput); TextView buildDateInput = (TextView) findViewById(R.id.editBuildDateInput); // Listen to user clicks on the dates purDateInput.setOnClickListener(new View.OnClickListener() { @SuppressWarnings("deprecation") @Override public void onClick(View v) { showDialog(1); } }); MOTInput.setOnClickListener(new View.OnClickListener() { @SuppressWarnings("deprecation") @Override public void onClick(View v) { showDialog(2); } }); buildDateInput.setOnClickListener(new View.OnClickListener() { @SuppressWarnings("deprecation") @Override public void onClick(View v) { showDialog(3); } }); } @SuppressWarnings("deprecation") @Override protected Dialog onCreateDialog(int id) { switch (id) { case 1: // set date picker as current date return new DatePickerDialog(this, purDatePickerListener, purDateYear, purDateMonth, purDateDay); case 2: // set date picker as current date return new DatePickerDialog(this, MOTDatePickerListener, MOTDateYear, MOTDateMonth, MOTDateDay); case 3: // set date picker as current date return new DatePickerDialog(this, buildDatePickerListener, buildDateYear, buildDateMonth, buildDateDay); } return null; } private DatePickerDialog.OnDateSetListener purDatePickerListener = new DatePickerDialog.OnDateSetListener() { // when dialog box is closed, below method will be called. @Override public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay) { // Convert received integer values to date variable Date selectedDate = new GregorianCalendar(selectedYear, selectedMonth, selectedDay).getTime(); // Convert date variable to locale date format DateFormat formatter = android.text.format.DateFormat.getDateFormat(EditCar_Activity.this); String today = formatter.format(selectedDate); // set selected date into text view using formatted date TextView purDateInput = (TextView) findViewById(R.id.editPurDateInput); purDateInput.setText(today); // Also set selected date (Epoch format) to variable so we can write this to the DB instead // of preformatted to the locale date purDate = selectedDate.getTime(); } }; private DatePickerDialog.OnDateSetListener MOTDatePickerListener = new DatePickerDialog.OnDateSetListener() { // when dialog box is closed, below method will be called. @Override public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay) { // Convert received integer values to Epoch Date selectedDate = new GregorianCalendar(selectedYear, selectedMonth, selectedDay).getTime(); // Convert Epoch to locale date format DateFormat formatter = android.text.format.DateFormat.getDateFormat(EditCar_Activity.this); String today = formatter.format(selectedDate); // set selected date into text view TextView MOTInput = (TextView) findViewById(R.id.editMOTInput); MOTInput.setText(today); MOT = selectedDate.getTime(); } }; private DatePickerDialog.OnDateSetListener buildDatePickerListener = new DatePickerDialog.OnDateSetListener() { // when dialog box is closed, below method will be called. @Override public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay) { // Convert received integer values to Epoch Date selectedDate = new GregorianCalendar(selectedYear, selectedMonth, selectedDay).getTime(); // Convert Epoch to locale date format DateFormat formatter = android.text.format.DateFormat.getDateFormat(EditCar_Activity.this); String today = formatter.format(selectedDate); // set selected date into text view TextView buildDateInput = (TextView) findViewById(R.id.editBuildDateInput); buildDateInput.setText(today); buildDate = selectedDate.getTime(); } }; protected void onPause() { BugSenseHandler.closeSession(EditCar_Activity.this); super.onPause(); dbHelper.close(); } protected void onResume() { BugSenseHandler.initAndStartSession(this, BugsenseAPIKey); dbHelper.open(); super.onResume(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.edit_car, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // Check if something changed // Using exitCheck to fill the changed and numberOfBlankFields variables and no coloring of empty fields exitCheck("noColor"); if (changed > 0 && !saved) { savedWarning(); return true; } if (changed == 0) { dbHelper.close(); BugSenseHandler.closeSession(EditCar_Activity.this); NavUtils.navigateUpFromSameTask(this); return true; } else { // If update car was success if (dbHelper.updateCar(carID, carMake, carModel, purPrice, purDate, MOT, licensePlate, buildDate)) { Toast.makeText(getBaseContext(), getString(R.string.carEditMSG), Toast.LENGTH_LONG).show(); } else { new AlertDialog.Builder(this).setTitle("Update failed!").setMessage("Update of the car failed!") .setNeutralButton(getString(R.string.ok), null).create().show(); } dbHelper.close(); BugSenseHandler.closeSession(EditCar_Activity.this); NavUtils.navigateUpFromSameTask(this); return true; } case R.id.save: if (!saved) { if (!exitCheck("color")) { // exitCheck returned false which means there required fields are left blank new AlertDialog.Builder(this).setTitle(getString(R.string.EmptyFieldsHeader)) .setMessage(numberOfBlankFields + " " + getString(R.string.EmptyFieldsMSG1) + "\n" + getString(R.string.EmptyFieldsMSG2)) .setNeutralButton(getString(R.string.ok), null).create().show(); return true; } if (!dateLogicCheck()) { // No logical dates unlogicalDateWarning(); return true; } else { // If update car was success if (dbHelper.updateCar(carID, carMake, carModel, purPrice, purDate, MOT, licensePlate, buildDate)) { Toast.makeText(getBaseContext(), getString(R.string.carEditMSG), Toast.LENGTH_LONG).show(); } else { new AlertDialog.Builder(this).setTitle("Update failed!") .setMessage("Update of the car failed!") .setNeutralButton(getString(R.string.ok), null).create().show(); } saved = true; dbHelper.close(); BugSenseHandler.closeSession(EditCar_Activity.this); setResult(RESULT_OK, getIntent()); EditCar_Activity.super.onBackPressed(); } } return true; case R.id.delete: // Check if something changed // Using exitCheck to fill the changed and numberOfBlankFields variables exitCheck("noColoring"); if (changed > 0 && !saved) { AlertDialog.Builder adb = new AlertDialog.Builder(this); adb.setTitle(getString(R.string.Cancel) + "?"); adb.setMessage(getString(R.string.CancelAllInput)) .setNegativeButton(getString(R.string.Cancel), null) .setPositiveButton(getString(R.string.ok), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); adb.create().show(); } else if (changed > 0 && saved) { finish(); return true; } else if (changed == 0) { finish(); return true; } return true; case R.id.about: DialogHandler.AboutMsg(this); return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("ConstantConditions") private boolean exitCheck(String strColor) { /* * Method to check if fields have been changed. * Returns: returns true if there are no required fields left blank * Returns: returns false if there are required fields left blank * */ carMakeLabel = (TextView) findViewById(R.id.editMakeLabel); carModelLabel = (TextView) findViewById(R.id.editModelLabel); carMakeInput = (EditText) findViewById(R.id.editMakeInput); carModelInput = (EditText) findViewById(R.id.editModelInput); licenseplateInput = (EditText) findViewById(R.id.editLicenseplateInput); purPriceInput = (EditText) findViewById(R.id.editPurPriceInput); // Let's start blank changed = 0; numberOfBlankFields = 0; boolean color = false; if (strColor.equals("color")) { color = true; } carMake = carMakeInput.getText().toString(); carModel = carModelInput.getText().toString(); if (hasNoContent(purPriceInput)) { purPrice = 0; } else { purPrice = Integer.parseInt(purPriceInput.getText().toString()); } licensePlate = licenseplateInput.getText().toString(); // Required fields check // Make if (hasNoContent(carMakeInput)) { numberOfBlankFields++; if (color) { carMakeLabel.setTextColor(red); } } else { changed++; saved = false; if (color) { carMakeLabel.setTextColor(black); } } // Model if (hasNoContent(carModelInput)) { numberOfBlankFields++; if (color) { carModelLabel.setTextColor(red); } } else { changed++; saved = false; if (color) { carModelLabel.setTextColor(black); } } // Check other fields to see if anything changed if (!hasNoContent(purPriceInput)) { changed++; saved = false; } if (!hasNoContent(licenseplateInput)) { changed++; saved = false; } if (!hasNoContent(purPriceInput)) { changed++; saved = false; } if (numberOfBlankFields == 0) { return true; } else { return false; } } private boolean dateLogicCheck() { // Long purDate; // Long MOT; // Long buildDate; // 3600000 = 60min boolean warning = false; /* * If the user didn't touch the datepicker the value of that picker is zero, * filling them with current date. * */ if (purDate == 0) { purDate = Utils.convertDateToLong(Calendar.getInstance().getTime()); return true; } if (MOT == 0) { MOT = Utils.convertDateToLong(Calendar.getInstance().getTime()); return true; } if (buildDate == 0) { buildDate = Utils.convertDateToLong(Calendar.getInstance().getTime()); return true; } if (purDate < buildDate) { if (!warning) { unlogicalDateWarning(); } warning = true; return false; } if (MOT < buildDate) { if (!warning) { unlogicalDateWarning(); } warning = true; return false; } if (MOT < purDate) { if (!warning) { unlogicalDateWarning(); } warning = true; return false; } if (MOT == purDate) { if (!warning) { unlogicalDateWarning(); } warning = true; return false; } else return true; } @SuppressWarnings("ConstantConditions") private boolean hasNoContent(TextView tv) { // Always assume true until proven otherwise boolean bHasNoContent = true; if (tv.getText().toString().trim().length() > 0) { // String got content, set false bHasNoContent = false; } return bHasNoContent; } @SuppressWarnings("ConstantConditions") private boolean hasNoContent(EditText et) { // Always assume true until proven otherwise boolean bHasNoContent = true; if (et.getText().toString().trim().length() > 0) { // String got content, set false bHasNoContent = false; } return bHasNoContent; } private void savedWarning() { new AlertDialog.Builder(this).setTitle(getString(R.string.Exit) + "?") .setMessage(getString(R.string.exitWithoutSaveMSG1)).setNegativeButton(android.R.string.no, null) .setPositiveButton(android.R.string.yes, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { EditCar_Activity.super.onBackPressed(); } }).create().show(); } private void unlogicalDateWarning() { new AlertDialog.Builder(this).setTitle(getString(R.string.UnlogicalDate)) .setMessage(getString(R.string.UnlogicalDateTxt)).setNeutralButton(android.R.string.no, null) .create().show(); } }