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.Build; import android.os.Bundle; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.app.Dialog; import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface; 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; @SuppressLint("NewApi") public class AddCar_Activity extends Activity { private static final String BugsenseAPIKey = "c05fc191"; boolean saved = false; int changed = 0; int numberOfBlankFields = 0; boolean RequiredAddCar = false; int red = Color.rgb(255, 100, 100); int black = Color.rgb(10, 10, 10); private DatabaseUtil dbHelper; TextView purDateInput; TextView MOTInput; TextView buildDateInput; int year; int month; int day; String carMake = null; String carModel = null; int purPrice = 0; String licensePlate = null; long purDate = 0L; long MOT = 0L; long buildDate = 0L; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Initiate database dbHelper = new DatabaseUtil(this); // Open database dbHelper.open(); // Activate loaded theme. // Utils.SetTheme(this, Utils.GetThemeSetting(this)); // Show the layout. BugSenseHandler.initAndStartSession(this, BugsenseAPIKey); // Get Intent extra values Bundle extras = getIntent().getExtras(); if (extras != null) { RequiredAddCar = extras.getBoolean("RequiredAddCar"); } setContentView(R.layout.activity_add_car); // Show the Up button in the action bar. setupActionBar(); TextView purDateInput = (TextView) findViewById(R.id.purDate); TextView MOTInput = (TextView) findViewById(R.id.MOT); TextView buildDateInput = (TextView) findViewById(R.id.buildDate); // Set current date in date picker textviews purDateInput.setText(Utils.convertDateToString(this, Calendar.getInstance().getTime())); MOTInput.setText(Utils.convertDateToString(this, Calendar.getInstance().getTime())); buildDateInput.setText(Utils.convertDateToString(this, Calendar.getInstance().getTime())); // set variables for date picker suggested date (current date) initDate(); addListenerOnTextViews(); } @Override public void onBackPressed() { // Check if something changed exitCheck("noColor"); // Act accordingly if (changed > 0 && saved == false && RequiredAddCar == false) { savedWarning(); } if (RequiredAddCar == true) { noCarsCreatedWarning(); } // Only exit if it's not required to add a car because of empty DB else { dbHelper.close(); BugSenseHandler.closeSession(AddCar_Activity.this); AddCar_Activity.super.onBackPressed(); } } public void onPause() { BugSenseHandler.closeSession(AddCar_Activity.this); super.onPause(); } public void addListenerOnTextViews() { TextView purDateInput = (TextView) findViewById(R.id.purDate); TextView MOTInput = (TextView) findViewById(R.id.MOT); TextView buildDateInput = (TextView) findViewById(R.id.buildDate); // 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); } }); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case 1: // set date picker as current date return new DatePickerDialog(this, purDatePickerListener, year, month, day); case 2: // set date picker as current date return new DatePickerDialog(this, MOTDatePickerListener, year, month, day); case 3: // set date picker as current date return new DatePickerDialog(this, buildDatePickerListener, year, month, day); } 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 int 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(getApplicationContext()); String today = formatter.format(selectedDate); // set selected date into textview using formatted date TextView purDateInput = (TextView) findViewById(R.id.purDate); 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 int values to Epoch Date selectedDate = new GregorianCalendar(selectedYear, selectedMonth, selectedDay).getTime(); // Convert Epoch to locale date format DateFormat formatter = android.text.format.DateFormat.getDateFormat(getApplicationContext()); String today = formatter.format(selectedDate); // set selected date into textview TextView MOTInput = (TextView) findViewById(R.id.MOT); 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 int values to Epoch Date selectedDate = new GregorianCalendar(selectedYear, selectedMonth, selectedDay).getTime(); // Convert Epoch to locale date format DateFormat formatter = android.text.format.DateFormat.getDateFormat(getApplicationContext()); String today = formatter.format(selectedDate); // set selected date into textview TextView buildDateInput = (TextView) findViewById(R.id.buildDate); buildDateInput.setText(today); buildDate = selectedDate.getTime(); } }; public void initDate() { // TODO netjes oplossen en niet 2x de datum en tijd opvragen en in verschillende vars stoppen final Calendar c = Calendar.getInstance(); year = c.get(Calendar.YEAR); month = c.get(Calendar.MONTH); day = c.get(Calendar.DAY_OF_MONTH); } /** * Set up the {@link android.app.ActionBar}, if the API is available. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void setupActionBar() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { getActionBar().setDisplayHomeAsUpEnabled(true); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.add_car_activity, 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 == false && RequiredAddCar == false) { savedWarning(); return true; } if (changed == 0 && RequiredAddCar == false) { dbHelper.close(); BugSenseHandler.closeSession(AddCar_Activity.this); NavUtils.navigateUpFromSameTask(this); return true; } else if (!RequiredAddCar) { dbHelper.createCar(carMake, carModel, purPrice, purDate, MOT, licensePlate, buildDate); Toast.makeText(getBaseContext(), getString(R.string.carCreatedMSG), Toast.LENGTH_LONG).show(); dbHelper.close(); BugSenseHandler.closeSession(AddCar_Activity.this); NavUtils.navigateUpFromSameTask(this); return true; } case R.id.save: if (saved == false) { if (exitCheck("color") == false) { // 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 { dbHelper.createCar(carMake, carModel, purPrice, purDate, MOT, licensePlate, buildDate); Toast.makeText(getBaseContext(), getString(R.string.carCreatedMSG), Toast.LENGTH_LONG).show(); saved = true; dbHelper.close(); BugSenseHandler.closeSession(AddCar_Activity.this); setResult(RESULT_OK, getIntent()); AddCar_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 == false && RequiredAddCar == false) { AlertDialog.Builder adb = new AlertDialog.Builder(this); adb.setTitle(getString(R.string.Delete) + "?"); adb.setMessage(getString(R.string.DeleteAllInput)) .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 == true && RequiredAddCar == false) { finish(); return true; } else if (changed == 0 && RequiredAddCar == false) { finish(); return true; } return true; case R.id.about: DialogHandler.AboutMsg(this); return true; } return super.onOptionsItemSelected(item); } private boolean exitCheck(String strColor) { /* * Method to check if fields have been changed: * Returns true if there are no required fields left blank * Returns false if there are required fields left blank * */ // Let's start blank changed = 0; numberOfBlankFields = 0; boolean color = false; if (strColor == "color") { color = true; } EditText carMakeET = (EditText) findViewById(R.id.make); TextView carMakeLabel = (TextView) findViewById(R.id.makeLabel); EditText carModelET = (EditText) findViewById(R.id.model); TextView carModelLabel = (TextView) findViewById(R.id.modelLabel); EditText licenseplateET = (EditText) findViewById(R.id.licenseplate); EditText purPriceET = (EditText) findViewById(R.id.purPrice); carMake = carMakeET.getText().toString(); carModel = carModelET.getText().toString(); if (hasNoContent(purPriceET)) { purPrice = 0; } else { purPrice = Integer.parseInt(purPriceET.getText().toString()); } licensePlate = licenseplateET.getText().toString(); // Required fields check // Make if (hasNoContent(carMakeET)) { numberOfBlankFields++; if (color == true) { carMakeLabel.setTextColor(red); } } else { changed++; saved = false; if (color == true) { carMakeLabel.setTextColor(black); } } // Model if (hasNoContent(carModelET)) { numberOfBlankFields++; if (color == true) { carModelLabel.setTextColor(red); } } else { changed++; saved = false; if (color == true) { carModelLabel.setTextColor(black); } } // Check other fields to see if anything changed if (hasNoContent(purPriceET) == false) { changed++; saved = false; } if (hasNoContent(licenseplateET) == false) { changed++; saved = false; } if (hasNoContent(purPriceET) == false) { 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 == false) { unlogicalDateWarning(); } warning = true; return false; } if (MOT < buildDate) { if (warning == false) { unlogicalDateWarning(); } warning = true; return false; } if (MOT < purDate) { if (warning == false) { unlogicalDateWarning(); } warning = true; return false; } if (MOT == purDate) { if (warning == false) { unlogicalDateWarning(); } warning = true; return false; } else return true; } 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; } 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) { AddCar_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(); } private void noCarsCreatedWarning() { new AlertDialog.Builder(this).setTitle(getString(R.string.Exit) + "?") .setMessage(getString(R.string.CreateText)).setNegativeButton(getString(R.string.Create), null) .setPositiveButton(getString(R.string.Exit), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { setResult(RESULT_CANCELED, getIntent()); finish(); } }).create().show(); } }