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;
      }
   }


As an Amazon Associate I earn from qualifying purchases.

My favorite quotations..


“A man should be able to change a diaper, plan an invasion, butcher a hog, conn a ship, design a building, write a sonnet, balance accounts, build a wall, set a bone, comfort the dying, take orders, give orders, cooperate, act alone, solve equations, analyze a new problem, pitch manure, program a computer, cook a tasty meal, fight efficiently, die gallantly. Specialization is for insects.”  by Robert A. Heinlein

"We are but habits and memories we chose to carry along." ~ Uki D. Lucas


Popular Recent Articles