Saturday, September 20, 2014

Android: switch case conditional

At some point, each application will have to perform some logic based on different cases.

  • extract your CONSTANTS
  • extract your logic into a separate method so it can be called from several places
  • use switch case instead of if else
  • use try catch statement when data types may vary





   private final static double CONVERSION_METERS_TO_YARDS = 1.093613298;
   private final static double CONVERSION_KILOMETERS_TO_MILES = 0.621371192;

   private void calculateResult() {
      Double valueEntered = 0.0;
      try {
         valueEntered = Double.valueOf(valueEnteredEditText.getText().toString());
         showToast("afterTextChanged " + valueEntered);
      }
      catch (NumberFormatException e) {
         resultingValueTextView.setText("");
         return;
      }

      switch (selectedConversion) {
      case 0:
         resultingValueTextView.setText("" + valueEntered * CONVERSION_METERS_TO_YARDS);
         break;
      case 1:
         resultingValueTextView.setText("" + valueEntered * CONVERSION_KILOMETERS_TO_MILES);
         break;
      }
   }