Difference between revisions of "Android Studio: Cara Membuat Android Apps 8"

From OnnoWiki
Jump to navigation Jump to search
(New page: In this tutorial we take it to the next level. In the last video we designed the interface for our Android conversion app. This time we will create the whole backend and finish the app. T...)
 
 
Line 107: Line 107:
 
/src/build.gradle
 
/src/build.gradle
  
apply plugin: 'android'
+
apply plugin: 'android'
 
+
android {
+
android {
    compileSdkVersion 19
+
    compileSdkVersion 19
    buildToolsVersion "19.1.0"
+
    buildToolsVersion "19.1.0"
 
+
    defaultConfig {
+
    defaultConfig {
        minSdkVersion 14
+
        minSdkVersion 14
        targetSdkVersion 19
+
        targetSdkVersion 19
        versionCode 1
+
        versionCode 1
        versionName "1.0"
+
        versionName "1.0"
    }
+
    }
    buildTypes {
+
    buildTypes {
        release {
+
        release {
            runProguard false
+
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
+
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
+
        }
    }
+
    }
}
+
}
 
+
dependencies {
+
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
+
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:19.+'
+
    compile 'com.android.support:appcompat-v7:19.+'
}
+
}
  
 
Quantity.java
 
Quantity.java
  
package com.newthinktank.derekbanas.conversion;
+
package com.newthinktank.derekbanas.conversion;
 
+
import java.text.DecimalFormat;
+
import java.text.DecimalFormat;
 
+
public class Quantity {
+
public class Quantity {
 
+
    // Each object will have both a value and a unit of measure
+
    // Each object will have both a value and a unit of measure
    final double value;
+
    final double value;
    final Unit unit;
+
    final Unit unit;
 
+
    // Enum types use a constant key to represent a value
+
    // Enum types use a constant key to represent a value
    // They allow use to easily define how to convert all the other types
+
    // They allow use to easily define how to convert all the other types
    // of measurements to convert from teaspoon to anything. Then to make
+
    // of measurements to convert from teaspoon to anything. Then to make
    // any conversion we convert from the starting type to teaspoon and then
+
    // any conversion we convert from the starting type to teaspoon and then
    // to the final required type.
+
    // to the final required type.
 
+
    public static enum Unit {
+
    public static enum Unit {
        tsp(1.0d), tbs(0.3333d), cup(0.0208d), oz(0.1666d),
+
        tsp(1.0d), tbs(0.3333d), cup(0.0208d), oz(0.1666d),
        pint(0.0104d), quart(0.0052d), gallon(0.0013), pound(0.0125d),
+
        pint(0.0104d), quart(0.0052d), gallon(0.0013), pound(0.0125d),
        ml(4.9289d), liter(0.0049d), mg(5687.5d), kg(0.0057d);
+
        ml(4.9289d), liter(0.0049d), mg(5687.5d), kg(0.0057d);
 
+
        // We define that tsp will be the base unit of measure that we will
+
        // We define that tsp will be the base unit of measure that we will
        // convert to and then convert from.
+
        // convert to and then convert from.
        final static Unit baseUnit = tsp;
+
        final static Unit baseUnit = tsp;
 
+
        // Will hold the number of tsp the original unit converts to
+
        // Will hold the number of tsp the original unit converts to
        final double byBaseUnit;
+
        final double byBaseUnit;
 
+
        // Receives the number of tsps the starting unit equals
+
        // Receives the number of tsps the starting unit equals
        private Unit(double inTsp) {
+
        private Unit(double inTsp) {
            this.byBaseUnit = inTsp;
+
            this.byBaseUnit = inTsp;
        }
+
        }
 
+
        // Converts any other unit value to the number of tsps
+
        // Converts any other unit value to the number of tsps
        public double toBaseUnit(double value) {
+
        public double toBaseUnit(double value) {
            return value / byBaseUnit;
+
            return value / byBaseUnit;
        }
+
        }
 
 
        // We convert to another unit by using the teaspoon conversion percent
 
        // defined in the enum
 
        public double fromBaseUnit(double value) {
 
            return value * byBaseUnit;
 
        }
 
 
 
    }
 
 
 
    // The constructor that receives the value and unit of measure
 
    public Quantity(double value, Unit unit) {
 
        super();
 
        this.value = value;
 
        this.unit = unit;
 
    }
 
 
 
    // Converts from tsp to the desired unit type
 
    public Quantity to(Unit newUnit) {
 
        Unit oldUnit = this.unit;
 
        return new Quantity(newUnit.fromBaseUnit(oldUnit.toBaseUnit(value)),
 
                newUnit);
 
    }
 
 
 
    // Prints out to screen the unit amount and unit type
 
    @Override
 
    public String toString() {
 
 
 
        DecimalFormat df = new DecimalFormat("#.0000");
 
 
 
        return df.format(value) + " " + unit.name();
 
    }
 
  
}
+
        // We convert to another unit by using the teaspoon conversion percent
 +
        // defined in the enum
 +
        public double fromBaseUnit(double value) {
 +
            return value * byBaseUnit;
 +
        }
 +
 +
    }
 +
 +
    // The constructor that receives the value and unit of measure
 +
    public Quantity(double value, Unit unit) {
 +
        super();
 +
        this.value = value;
 +
        this.unit = unit;
 +
    }
 +
 +
    // Converts from tsp to the desired unit type
 +
    public Quantity to(Unit newUnit) {
 +
        Unit oldUnit = this.unit;
 +
        return new Quantity(newUnit.fromBaseUnit(oldUnit.toBaseUnit(value)),
 +
                newUnit);
 +
    }
 +
 +
    // Prints out to screen the unit amount and unit type
 +
    @Override
 +
    public String toString() {
 +
 +
        DecimalFormat df = new DecimalFormat("#.0000");
 +
 +
        return df.format(value) + " " + unit.name();
 +
    }
 +
 +
}
  
 
MainActivity.java
 
MainActivity.java
  
package com.newthinktank.derekbanas.conversion;
+
package com.newthinktank.derekbanas.conversion;
 
+
import android.os.Bundle;
+
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
+
import android.support.v7.app.ActionBarActivity;
import android.view.View;
+
import android.view.View;
import android.widget.AdapterView;
+
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
+
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
+
import android.widget.ArrayAdapter;
import android.widget.EditText;
+
import android.widget.EditText;
import android.widget.Spinner;
+
import android.widget.Spinner;
import android.widget.TextView;
+
import android.widget.TextView;
 
+
 
 
+
public class MainActivity extends ActionBarActivity {
+
public class MainActivity extends ActionBarActivity {
 +
 +
    private Spinner unitTypeSpinner;
 +
 +
    private EditText amountTextView;
 +
 +
    TextView teaspoonTextView, tablespoonTextView, cupTextView, ounceTextView,
 +
            pintTextView, quartTextView, gallonTextView, poundTextView,
 +
            milliliterTextView, literTextView, milligramTextView, kilogramTextView;
 +
 +
    @Override
 +
    protected void onCreate(Bundle savedInstanceState) {
 +
        super.onCreate(savedInstanceState);
 +
        setContentView(R.layout.activity_main);
 +
 +
        // Fills the spinner with the unit options
 +
        addItemsToUnitTypeSpinner();
 +
 +
        // Add listener to the Spinner
 +
        addListenerToUnitTypeSpinner();
 +
 +
        // Get a reference to the edit text view to retrieve the amount of the unit type
 +
        amountTextView = (EditText) findViewById(R.id.amount_text_view);
 +
 +
        initializeTextViews();
 +
 +
    }
  
    private Spinner unitTypeSpinner;
+
    public void initializeTextViews(){
 +
 +
        teaspoonTextView = (TextView) findViewById(R.id.tsp_text_view);
 +
        tablespoonTextView = (TextView) findViewById(R.id.tbs_text_view);
 +
        cupTextView = (TextView) findViewById(R.id.cup_text_view);
 +
        ounceTextView = (TextView) findViewById(R.id.oz_text_view);
 +
        pintTextView = (TextView) findViewById(R.id.pint_text_view);
 +
        quartTextView = (TextView) findViewById(R.id.quart_text_view);
 +
        gallonTextView = (TextView) findViewById(R.id.gallon_text_view);
 +
        poundTextView = (TextView) findViewById(R.id.pound_text_view);
 +
        milliliterTextView = (TextView) findViewById(R.id.ml_text_view);
 +
        literTextView = (TextView) findViewById(R.id.liter_text_view);
 +
        milligramTextView = (TextView) findViewById(R.id.mg_text_view);
 +
        kilogramTextView = (TextView) findViewById(R.id.kg_text_view);
 +
 +
    }
 +
 +
    public void addItemsToUnitTypeSpinner(){
 +
 +
        // Get a reference to the spinner
 +
        unitTypeSpinner = (Spinner) findViewById(R.id.unit_type_spinner);
 +
 +
        // Create an ArrayAdapter using the string array and a default spinner layout
 +
        ArrayAdapter<CharSequence> unitTypeSpinnerAdapter = ArrayAdapter.createFromResource(this,
 +
                R.array.conversion_types, android.R.layout.simple_spinner_item);
 +
 +
        // Specify the layout to use when the list of choices appears
 +
          unitTypeSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
 +
 +
        // Apply the adapter to the spinner
 +
        unitTypeSpinner.setAdapter(unitTypeSpinnerAdapter);
 +
 +
    }
 +
 +
    public void addListenerToUnitTypeSpinner() {
 +
        unitTypeSpinner = (Spinner) findViewById(R.id.unit_type_spinner);
 +
        unitTypeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
 +
            public void onItemSelected(AdapterView<?> parent, View arg1, int pos, long arg3)
 +
            {
 +
                // Get the item selected in the Spinner
 +
                String itemSelectedInSpinner = parent.getItemAtPosition(pos).toString();
 +
 +
                // Verify if I'm converting from teaspoon so that I use the right
 +
                // conversion algorithm
 +
                checkIfConvertingFromTsp(itemSelectedInSpinner);
 +
 +
            }
 +
            public void onNothingSelected(AdapterView<?> arg0)
 +
            {
 +
                // TODO maybe add something here later
 +
            }
 +
        });
 +
    }
 +
 +
    public void checkIfConvertingFromTsp(String currentUnit){
 +
 +
        if(currentUnit.equals("teaspoon")){
 +
 +
            updateUnitTypesUsingTsp(Quantity.Unit.tsp);
 +
 +
        } else {
 +
 +
            if(currentUnit.equals("tablespoon")){
 +
 +
                updateUnitTypesUsingOther(Quantity.Unit.tbs);
 +
 +
            } else if(currentUnit.equals("cup")){
 +
 +
                updateUnitTypesUsingOther(Quantity.Unit.cup);
 +
 +
            } else if(currentUnit.equals("ounce")){
 +
 +
                updateUnitTypesUsingOther(Quantity.Unit.oz);
 +
 +
            } else if(currentUnit.equals("pint")){
 +
 +
                updateUnitTypesUsingOther(Quantity.Unit.pint);
 +
 +
            } else if(currentUnit.equals("quart")){
 +
 +
                updateUnitTypesUsingOther(Quantity.Unit.quart);
 +
 +
            } else if(currentUnit.equals("gallon")){
 +
 +
                updateUnitTypesUsingOther(Quantity.Unit.gallon);
 +
 +
            } else if(currentUnit.equals("pound")){
 +
 +
                updateUnitTypesUsingOther(Quantity.Unit.pound);
 +
 +
            } else if(currentUnit.equals("milliliter")){
 +
 +
                updateUnitTypesUsingOther(Quantity.Unit.ml);
 +
 +
            } else if(currentUnit.equals("liter")){
 +
 +
                updateUnitTypesUsingOther(Quantity.Unit.liter);
 +
 +
            } else if(currentUnit.equals("milligram")){
 +
 +
                updateUnitTypesUsingOther(Quantity.Unit.mg);
 +
 +
            } else {
 +
 +
                updateUnitTypesUsingOther(Quantity.Unit.kg);
 +
 +
            }
 +
 +
        }
 +
 +
    }
 +
 +
    public void updateUnitTypesUsingTsp(Quantity.Unit currentUnit){
 +
 +
        // Convert the value in the EditText box to a double
 +
        double doubleToConvert = Double.parseDouble(amountTextView.getText().toString());
 +
 +
        // Combine value to unit
 +
        String teaspoonValueAndUnit = doubleToConvert + " tsp";
 +
 +
        // Change the value for the teaspoon TextView
 +
        teaspoonTextView.setText(teaspoonValueAndUnit);
 +
 +
        // Update all the Unit Text Fields
 +
        updateUnitTextFieldUsingTsp(doubleToConvert, Quantity.Unit.tbs, tablespoonTextView);
 +
        updateUnitTextFieldUsingTsp(doubleToConvert, Quantity.Unit.cup, cupTextView);
 +
        updateUnitTextFieldUsingTsp(doubleToConvert, Quantity.Unit.oz, ounceTextView);
 +
        updateUnitTextFieldUsingTsp(doubleToConvert, Quantity.Unit.pint, pintTextView);
 +
        updateUnitTextFieldUsingTsp(doubleToConvert, Quantity.Unit.quart, quartTextView);
 +
        updateUnitTextFieldUsingTsp(doubleToConvert, Quantity.Unit.gallon, gallonTextView);
 +
        updateUnitTextFieldUsingTsp(doubleToConvert, Quantity.Unit.pound, poundTextView);
 +
        updateUnitTextFieldUsingTsp(doubleToConvert, Quantity.Unit.ml, milliliterTextView);
 +
        updateUnitTextFieldUsingTsp(doubleToConvert, Quantity.Unit.liter, literTextView);
 +
        updateUnitTextFieldUsingTsp(doubleToConvert, Quantity.Unit.mg, milligramTextView);
 +
        updateUnitTextFieldUsingTsp(doubleToConvert, Quantity.Unit.kg, kilogramTextView);
 +
 +
    }
 +
 +
    public void updateUnitTextFieldUsingTsp(double doubleToConvert, Quantity.Unit unitConvertingTo,
 +
                                            TextView theTextView){
 +
 +
        Quantity unitQuantity = new Quantity(doubleToConvert, Quantity.Unit.tsp);
 +
 +
        String tempUnit = unitQuantity.to(unitConvertingTo).toString();
 +
 +
        theTextView.setText(tempUnit);
 +
 +
    }
 +
 +
    public void updateUnitTypesUsingOther(Quantity.Unit currentUnit){
 +
 +
        // Convert the value in the EditText box to a double
 +
        double doubleToConvert = Double.parseDouble(amountTextView.getText().toString());
 +
 +
        // Create a Quantity using the teaspoon unit
 +
        Quantity currentQuantitySelected = new Quantity(doubleToConvert, currentUnit);
 +
 +
        // Create the String for the teaspoon TextView
 +
        String valueInTeaspoons = currentQuantitySelected.to(Quantity.Unit.tsp).toString();
  
    private EditText amountTextView;
+
        // Set the text for the teaspoon TextView
 +
        teaspoonTextView.setText(valueInTeaspoons);
 +
 +
        updateUnitTextFieldUsingTsp(doubleToConvert, currentUnit,
 +
                Quantity.Unit.tbs, tablespoonTextView);
 +
 +
        updateUnitTextFieldUsingTsp(doubleToConvert, currentUnit,
 +
                Quantity.Unit.cup, cupTextView);
 +
 +
        updateUnitTextFieldUsingTsp(doubleToConvert, currentUnit,
 +
                Quantity.Unit.oz, ounceTextView);
 +
 +
        updateUnitTextFieldUsingTsp(doubleToConvert, currentUnit,
 +
                Quantity.Unit.pint, pintTextView);
 +
 +
        updateUnitTextFieldUsingTsp(doubleToConvert, currentUnit,
 +
                Quantity.Unit.quart, quartTextView);
  
    TextView teaspoonTextView, tablespoonTextView, cupTextView, ounceTextView,
+
        updateUnitTextFieldUsingTsp(doubleToConvert, currentUnit,
            pintTextView, quartTextView, gallonTextView, poundTextView,
+
                Quantity.Unit.gallon, gallonTextView);
            milliliterTextView, literTextView, milligramTextView, kilogramTextView;
+
 +
        updateUnitTextFieldUsingTsp(doubleToConvert, currentUnit,
 +
                Quantity.Unit.pound, poundTextView);
 +
 +
        updateUnitTextFieldUsingTsp(doubleToConvert, currentUnit,
 +
                Quantity.Unit.ml, milliliterTextView);
  
    @Override
+
        updateUnitTextFieldUsingTsp(doubleToConvert, currentUnit,
    protected void onCreate(Bundle savedInstanceState) {
+
                Quantity.Unit.liter, literTextView);
        super.onCreate(savedInstanceState);
+
        setContentView(R.layout.activity_main);
+
        updateUnitTextFieldUsingTsp(doubleToConvert, currentUnit,
 +
                Quantity.Unit.mg, milligramTextView);
 +
 +
        updateUnitTextFieldUsingTsp(doubleToConvert, currentUnit,
 +
                Quantity.Unit.kg, kilogramTextView);
 +
 +
 +
        // Set the currently selected unit to the number in the EditText
 +
          if(currentUnit.name().equals(currentQuantitySelected.unit.name())){
 +
 +
            // Create the TextView text by taking the value in EditText and adding
 +
            // on the currently selected unit in the spinner
 +
            String currentUnitTextViewText = doubleToConvert + " " +
 +
                    currentQuantitySelected.unit.name();
 +
 +
            // Create the TextView name to change by getting the currently
 +
            // selected quantities unit name and tacking on _text_view
 +
            String currentTextViewName = currentQuantitySelected.unit.name() +
 +
                    "_text_view";
 +
 +
            // Get the resource id needed for the textView to use in findViewById
 +
            int currentId = getResources().getIdentifier(currentTextViewName, "id",
 +
                    MainActivity.this.getPackageName());
 +
 +
            // Create an instance of the TextView we want to change
 +
            TextView currentTextView = (TextView) findViewById(currentId);
 +
 +
            // Put the right data in the TextView
 +
            currentTextView.setText(currentUnitTextViewText);
  
        // Fills the spinner with the unit options
+
        }
        addItemsToUnitTypeSpinner();
+
 
+
    }
        // Add listener to the Spinner
+
        addListenerToUnitTypeSpinner();
+
    public void updateUnitTextFieldUsingTsp(double doubleToConvert, Quantity.Unit currentUnit,
 
+
                                            Quantity.Unit preferredUnit, TextView targetTextView){
        // Get a reference to the edit text view to retrieve the amount of the unit type
+
        amountTextView = (EditText) findViewById(R.id.amount_text_view);
+
        Quantity currentQuantitySelected = new Quantity(doubleToConvert, currentUnit);
 
+
        initializeTextViews();
+
        // Algorithm used quantityInTbs.to(Unit.tsp).to(Unit.ounce)
 
+
    }
+
        String tempTextViewText = currentQuantitySelected.to(Quantity.Unit.tsp).
 
+
                to(preferredUnit).toString();
    public void initializeTextViews(){
+
 
+
        targetTextView.setText(tempTextViewText);
        teaspoonTextView = (TextView) findViewById(R.id.tsp_text_view);
+
        tablespoonTextView = (TextView) findViewById(R.id.tbs_text_view);
+
        cupTextView = (TextView) findViewById(R.id.cup_text_view);
+
    }  
        ounceTextView = (TextView) findViewById(R.id.oz_text_view);
+
        pintTextView = (TextView) findViewById(R.id.pint_text_view);
+
}
        quartTextView = (TextView) findViewById(R.id.quart_text_view);
 
        gallonTextView = (TextView) findViewById(R.id.gallon_text_view);
 
        poundTextView = (TextView) findViewById(R.id.pound_text_view);
 
        milliliterTextView = (TextView) findViewById(R.id.ml_text_view);
 
        literTextView = (TextView) findViewById(R.id.liter_text_view);
 
        milligramTextView = (TextView) findViewById(R.id.mg_text_view);
 
        kilogramTextView = (TextView) findViewById(R.id.kg_text_view);
 
 
 
    }
 
 
 
    public void addItemsToUnitTypeSpinner(){
 
 
 
        // Get a reference to the spinner
 
        unitTypeSpinner = (Spinner) findViewById(R.id.unit_type_spinner);
 
 
 
        // Create an ArrayAdapter using the string array and a default spinner layout
 
        ArrayAdapter<CharSequence> unitTypeSpinnerAdapter = ArrayAdapter.createFromResource(this,
 
                R.array.conversion_types, android.R.layout.simple_spinner_item);
 
 
 
        // Specify the layout to use when the list of choices appears
 
        unitTypeSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
 
 
 
        // Apply the adapter to the spinner
 
        unitTypeSpinner.setAdapter(unitTypeSpinnerAdapter);
 
 
 
    }
 
 
 
    public void addListenerToUnitTypeSpinner() {
 
        unitTypeSpinner = (Spinner) findViewById(R.id.unit_type_spinner);
 
        unitTypeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
 
            public void onItemSelected(AdapterView<?> parent, View arg1, int pos, long arg3)
 
            {
 
                // Get the item selected in the Spinner
 
                String itemSelectedInSpinner = parent.getItemAtPosition(pos).toString();
 
 
 
                // Verify if I'm converting from teaspoon so that I use the right
 
                // conversion algorithm
 
                checkIfConvertingFromTsp(itemSelectedInSpinner);
 
 
 
            }
 
            public void onNothingSelected(AdapterView<?> arg0)
 
            {
 
                // TODO maybe add something here later
 
            }
 
        });
 
    }
 
 
 
    public void checkIfConvertingFromTsp(String currentUnit){
 
 
 
        if(currentUnit.equals("teaspoon")){
 
 
 
            updateUnitTypesUsingTsp(Quantity.Unit.tsp);
 
 
 
        } else {
 
 
 
            if(currentUnit.equals("tablespoon")){
 
 
 
                updateUnitTypesUsingOther(Quantity.Unit.tbs);
 
 
 
            } else if(currentUnit.equals("cup")){
 
 
 
                updateUnitTypesUsingOther(Quantity.Unit.cup);
 
 
 
            } else if(currentUnit.equals("ounce")){
 
 
 
                updateUnitTypesUsingOther(Quantity.Unit.oz);
 
 
 
            } else if(currentUnit.equals("pint")){
 
 
 
                updateUnitTypesUsingOther(Quantity.Unit.pint);
 
 
 
            } else if(currentUnit.equals("quart")){
 
 
 
                updateUnitTypesUsingOther(Quantity.Unit.quart);
 
 
 
            } else if(currentUnit.equals("gallon")){
 
 
 
                updateUnitTypesUsingOther(Quantity.Unit.gallon);
 
 
 
            } else if(currentUnit.equals("pound")){
 
 
 
                updateUnitTypesUsingOther(Quantity.Unit.pound);
 
 
 
            } else if(currentUnit.equals("milliliter")){
 
 
 
                updateUnitTypesUsingOther(Quantity.Unit.ml);
 
 
 
            } else if(currentUnit.equals("liter")){
 
 
 
                updateUnitTypesUsingOther(Quantity.Unit.liter);
 
 
 
            } else if(currentUnit.equals("milligram")){
 
 
 
                updateUnitTypesUsingOther(Quantity.Unit.mg);
 
 
 
            } else {
 
 
 
                updateUnitTypesUsingOther(Quantity.Unit.kg);
 
 
 
            }
 
 
 
        }
 
 
 
    }
 
 
 
    public void updateUnitTypesUsingTsp(Quantity.Unit currentUnit){
 
 
 
        // Convert the value in the EditText box to a double
 
        double doubleToConvert = Double.parseDouble(amountTextView.getText().toString());
 
 
 
        // Combine value to unit
 
        String teaspoonValueAndUnit = doubleToConvert + " tsp";
 
 
 
        // Change the value for the teaspoon TextView
 
        teaspoonTextView.setText(teaspoonValueAndUnit);
 
 
 
        // Update all the Unit Text Fields
 
        updateUnitTextFieldUsingTsp(doubleToConvert, Quantity.Unit.tbs, tablespoonTextView);
 
        updateUnitTextFieldUsingTsp(doubleToConvert, Quantity.Unit.cup, cupTextView);
 
        updateUnitTextFieldUsingTsp(doubleToConvert, Quantity.Unit.oz, ounceTextView);
 
        updateUnitTextFieldUsingTsp(doubleToConvert, Quantity.Unit.pint, pintTextView);
 
        updateUnitTextFieldUsingTsp(doubleToConvert, Quantity.Unit.quart, quartTextView);
 
        updateUnitTextFieldUsingTsp(doubleToConvert, Quantity.Unit.gallon, gallonTextView);
 
        updateUnitTextFieldUsingTsp(doubleToConvert, Quantity.Unit.pound, poundTextView);
 
        updateUnitTextFieldUsingTsp(doubleToConvert, Quantity.Unit.ml, milliliterTextView);
 
        updateUnitTextFieldUsingTsp(doubleToConvert, Quantity.Unit.liter, literTextView);
 
        updateUnitTextFieldUsingTsp(doubleToConvert, Quantity.Unit.mg, milligramTextView);
 
        updateUnitTextFieldUsingTsp(doubleToConvert, Quantity.Unit.kg, kilogramTextView);
 
 
 
    }
 
 
 
    public void updateUnitTextFieldUsingTsp(double doubleToConvert, Quantity.Unit unitConvertingTo,
 
                                            TextView theTextView){
 
 
 
        Quantity unitQuantity = new Quantity(doubleToConvert, Quantity.Unit.tsp);
 
 
 
        String tempUnit = unitQuantity.to(unitConvertingTo).toString();
 
 
 
        theTextView.setText(tempUnit);
 
 
 
    }
 
 
 
    public void updateUnitTypesUsingOther(Quantity.Unit currentUnit){
 
 
 
        // Convert the value in the EditText box to a double
 
        double doubleToConvert = Double.parseDouble(amountTextView.getText().toString());
 
 
 
        // Create a Quantity using the teaspoon unit
 
        Quantity currentQuantitySelected = new Quantity(doubleToConvert, currentUnit);
 
 
 
        // Create the String for the teaspoon TextView
 
        String valueInTeaspoons = currentQuantitySelected.to(Quantity.Unit.tsp).toString();
 
 
 
        // Set the text for the teaspoon TextView
 
        teaspoonTextView.setText(valueInTeaspoons);
 
 
 
        updateUnitTextFieldUsingTsp(doubleToConvert, currentUnit,
 
                Quantity.Unit.tbs, tablespoonTextView);
 
 
 
        updateUnitTextFieldUsingTsp(doubleToConvert, currentUnit,
 
                Quantity.Unit.cup, cupTextView);
 
 
 
        updateUnitTextFieldUsingTsp(doubleToConvert, currentUnit,
 
                Quantity.Unit.oz, ounceTextView);
 
 
 
        updateUnitTextFieldUsingTsp(doubleToConvert, currentUnit,
 
                Quantity.Unit.pint, pintTextView);
 
 
 
        updateUnitTextFieldUsingTsp(doubleToConvert, currentUnit,
 
                Quantity.Unit.quart, quartTextView);
 
 
 
        updateUnitTextFieldUsingTsp(doubleToConvert, currentUnit,
 
                Quantity.Unit.gallon, gallonTextView);
 
 
 
        updateUnitTextFieldUsingTsp(doubleToConvert, currentUnit,
 
                Quantity.Unit.pound, poundTextView);
 
 
 
        updateUnitTextFieldUsingTsp(doubleToConvert, currentUnit,
 
                Quantity.Unit.ml, milliliterTextView);
 
 
 
        updateUnitTextFieldUsingTsp(doubleToConvert, currentUnit,
 
                Quantity.Unit.liter, literTextView);
 
 
 
        updateUnitTextFieldUsingTsp(doubleToConvert, currentUnit,
 
                Quantity.Unit.mg, milligramTextView);
 
 
 
        updateUnitTextFieldUsingTsp(doubleToConvert, currentUnit,
 
                Quantity.Unit.kg, kilogramTextView);
 
 
 
 
 
        // Set the currently selected unit to the number in the EditText
 
        if(currentUnit.name().equals(currentQuantitySelected.unit.name())){
 
 
 
            // Create the TextView text by taking the value in EditText and adding
 
            // on the currently selected unit in the spinner
 
            String currentUnitTextViewText = doubleToConvert + " " +
 
                    currentQuantitySelected.unit.name();
 
 
 
            // Create the TextView name to change by getting the currently
 
            // selected quantities unit name and tacking on _text_view
 
            String currentTextViewName = currentQuantitySelected.unit.name() +
 
                    "_text_view";
 
 
 
            // Get the resource id needed for the textView to use in findViewById
 
            int currentId = getResources().getIdentifier(currentTextViewName, "id",
 
                    MainActivity.this.getPackageName());
 
 
 
            // Create an instance of the TextView we want to change
 
            TextView currentTextView = (TextView) findViewById(currentId);
 
 
 
            // Put the right data in the TextView
 
            currentTextView.setText(currentUnitTextViewText);
 
 
 
        }
 
 
 
    }
 
 
 
    public void updateUnitTextFieldUsingTsp(double doubleToConvert, Quantity.Unit currentUnit,
 
                                            Quantity.Unit preferredUnit, TextView targetTextView){
 
 
 
        Quantity currentQuantitySelected = new Quantity(doubleToConvert, currentUnit);
 
 
 
        // Algorithm used quantityInTbs.to(Unit.tsp).to(Unit.ounce)
 
 
 
        String tempTextViewText = currentQuantitySelected.to(Quantity.Unit.tsp).
 
                to(preferredUnit).toString();
 
 
 
        targetTextView.setText(tempTextViewText);
 
 
 
 
 
    }
 
 
 
}
 
  
 
Android Manifest.xml
 
Android Manifest.xml
  
<?xml version="1.0" encoding="utf-8"?>
+
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.newthinktank.derekbanas.conversion" >
+
    package="com.newthinktank.derekbanas.conversion" >
 
+
    <application
+
    <application
        android:allowBackup="true"
+
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
+
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
+
        android:label="@string/app_name"
        android:theme="@style/Theme.AppCompat" >
+
        android:theme="@style/Theme.AppCompat" >
        <activity
+
        <activity
            android:name=".MainActivity"
+
            android:name=".MainActivity"
            android:label="@string/app_name" >
+
            android:label="@string/app_name" >
            <intent-filter>
+
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
+
                <action android:name="android.intent.action.MAIN" />
 
+
                <category android:name="android.intent.category.LAUNCHER" />
+
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
+
            </intent-filter>
        </activity>
+
        </activity>
    </application>
+
    </application>
 
+
</manifest>
+
</manifest>
 
 
- See more at: http://www.newthinktank.com/2014/07/make-android-apps-8/#sthash.DsSTVAzu.dpuf
 
 
 
 
 
  
  
Line 521: Line 517:
  
 
* http://www.newthinktank.com/2014/07/make-android-apps-8/
 
* http://www.newthinktank.com/2014/07/make-android-apps-8/
 +
* http://www.newthinktank.com/2014/07/make-android-apps-8/#sthash.DsSTVAzu.dpuf

Latest revision as of 20:57, 20 April 2015

In this tutorial we take it to the next level. In the last video we designed the interface for our Android conversion app. This time we will create the whole backend and finish the app.

The goal of this tutorial is to show you how to make an entire app in one video. We’ll cover use case descriptions, activity diagrams, class diagrams, flexible ways to solve our conversion problem, dynamically changing classes and much more. If you don’t understand everything don’t worry about it. This tutorial is all about seeing it all so you’ll grasp what is coming next.

If you like videos like this it helps to tell others on Google Plus with a click here

Here is the entire package for download Android Conversion App.

Note : In the video I set up the emulator to lvl 20, change to 19 in your build.gradle file and try 19.1.0 as I show below. I was trying to do too many things and that was a mistake.

UML Diagrams

Click the image below a few times to view it full screen

Android UML Diagrams

Use Case Description

SIMPLE ACTIONS

1. The user enters a number they want converted into an EditText

2. They change the spinner to the unit of measure to convert from

3. The other conversion types all show their measurement version of that unit amount

1. Create the layout in activity_main.xml

a. Use relative layout for for label "Convert From", Edittext and Spinner

b. Use GridLayout for bottom that contains 2 columns and 6 rows

c. Make gridlayout a blue color

d. Use the units teaspoons, tablespoons, cup, ounces, pints, quarts, gallons, pounds, milliliter, liter, milligram kilograms

2. Setup MainActivity

a. Create Spinner, EditText, TextViews

b. In onCreate

I. add items to the spinner

i. Create an ArrayAdapter using String array resource (Make strings.xml)

ii. Define the layout to use with the Spinner

iii. Connect the Adapter to the Spinner

II. Add a listener to the Spinner

i. Use setOnItemSelectedListener for Spinner

ii. NOTE : Maybe check if I am going to use a base class for unit conversion

III. Get the value in the EditText

IV. Initialize the TextViews

c. End onCreate ---------------------

3. Define a Quantity Class ----------

a. Quantity class contains a value and Unit enum

b. Define an enum for each unit type

c. Get the conversion for each unit type from teaspoon which is the base unit

d. Receive the number of teaspoons for the starting unit

e. To convert to the base unit teaspoons divide by the base unit

f. To convert to another unit other then teaspoons multiply by the base unit

g. Constructor receives the value and the unit

h. Create a toString that prints out the value and unit type to 4 decimals

4. Finish MainActivity

a. Item changed in the Spinner

I. Check if I'm converting from teaspoons?

i. If I am check if I'm updating tsps or not

  • I Have Decided to Model this in an Activity Diagram *

Code From the Video

/src/build.gradle

apply plugin: 'android'

android {
    compileSdkVersion 19
    buildToolsVersion "19.1.0"

    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 19
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:19.+'
}

Quantity.java

package com.newthinktank.derekbanas.conversion;

import java.text.DecimalFormat;

public class Quantity {

    // Each object will have both a value and a unit of measure
    final double value;
    final Unit unit;

    // Enum types use a constant key to represent a value
    // They allow use to easily define how to convert all the other types
    // of measurements to convert from teaspoon to anything. Then to make
    // any conversion we convert from the starting type to teaspoon and then
    // to the final required type.

    public static enum Unit {
        tsp(1.0d), tbs(0.3333d), cup(0.0208d), oz(0.1666d),
        pint(0.0104d), quart(0.0052d), gallon(0.0013), pound(0.0125d),
        ml(4.9289d), liter(0.0049d), mg(5687.5d), kg(0.0057d);

        // We define that tsp will be the base unit of measure that we will
        // convert to and then convert from.
        final static Unit baseUnit = tsp;

        // Will hold the number of tsp the original unit converts to
        final double byBaseUnit;

        // Receives the number of tsps the starting unit equals
        private Unit(double inTsp) {
            this.byBaseUnit = inTsp;
        }

        // Converts any other unit value to the number of tsps
        public double toBaseUnit(double value) {
            return value / byBaseUnit;
        }
        // We convert to another unit by using the teaspoon conversion percent
        // defined in the enum
        public double fromBaseUnit(double value) {
            return value * byBaseUnit;
        } 

    }

    // The constructor that receives the value and unit of measure
    public Quantity(double value, Unit unit) {
        super();
        this.value = value;
        this.unit = unit;
    }

    // Converts from tsp to the desired unit type
    public Quantity to(Unit newUnit) {
        Unit oldUnit = this.unit;
        return new Quantity(newUnit.fromBaseUnit(oldUnit.toBaseUnit(value)),
                newUnit);
    }

    // Prints out to screen the unit amount and unit type
    @Override
    public String toString() {

        DecimalFormat df = new DecimalFormat("#.0000"); 

        return df.format(value) + " " + unit.name();
    } 

}

MainActivity.java

package com.newthinktank.derekbanas.conversion;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
 

public class MainActivity extends ActionBarActivity {

    private Spinner unitTypeSpinner;

    private EditText amountTextView;

    TextView teaspoonTextView, tablespoonTextView, cupTextView, ounceTextView,
            pintTextView, quartTextView, gallonTextView, poundTextView,
            milliliterTextView, literTextView, milligramTextView, kilogramTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Fills the spinner with the unit options
        addItemsToUnitTypeSpinner();

        // Add listener to the Spinner
        addListenerToUnitTypeSpinner();

        // Get a reference to the edit text view to retrieve the amount of the unit type
        amountTextView = (EditText) findViewById(R.id.amount_text_view);

        initializeTextViews();

    }
    public void initializeTextViews(){

        teaspoonTextView = (TextView) findViewById(R.id.tsp_text_view);
        tablespoonTextView = (TextView) findViewById(R.id.tbs_text_view);
        cupTextView = (TextView) findViewById(R.id.cup_text_view);
        ounceTextView = (TextView) findViewById(R.id.oz_text_view);
        pintTextView = (TextView) findViewById(R.id.pint_text_view);
        quartTextView = (TextView) findViewById(R.id.quart_text_view);
        gallonTextView = (TextView) findViewById(R.id.gallon_text_view);
        poundTextView = (TextView) findViewById(R.id.pound_text_view);
        milliliterTextView = (TextView) findViewById(R.id.ml_text_view);
        literTextView = (TextView) findViewById(R.id.liter_text_view);
        milligramTextView = (TextView) findViewById(R.id.mg_text_view);
        kilogramTextView = (TextView) findViewById(R.id.kg_text_view);

    }

    public void addItemsToUnitTypeSpinner(){ 

        // Get a reference to the spinner
        unitTypeSpinner = (Spinner) findViewById(R.id.unit_type_spinner);

        // Create an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<CharSequence> unitTypeSpinnerAdapter = ArrayAdapter.createFromResource(this,
                R.array.conversion_types, android.R.layout.simple_spinner_item);

        // Specify the layout to use when the list of choices appears
         unitTypeSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // Apply the adapter to the spinner
        unitTypeSpinner.setAdapter(unitTypeSpinnerAdapter);

    }

    public void addListenerToUnitTypeSpinner() {
        unitTypeSpinner = (Spinner) findViewById(R.id.unit_type_spinner);
        unitTypeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View arg1, int pos, long arg3)
            {
                // Get the item selected in the Spinner
                String itemSelectedInSpinner = parent.getItemAtPosition(pos).toString();

                // Verify if I'm converting from teaspoon so that I use the right
                // conversion algorithm
                checkIfConvertingFromTsp(itemSelectedInSpinner);

            }
            public void onNothingSelected(AdapterView<?> arg0)
            {
                // TODO maybe add something here later
            }
        });
    }

    public void checkIfConvertingFromTsp(String currentUnit){

        if(currentUnit.equals("teaspoon")){

            updateUnitTypesUsingTsp(Quantity.Unit.tsp);

        } else {

            if(currentUnit.equals("tablespoon")){

                updateUnitTypesUsingOther(Quantity.Unit.tbs);

            } else if(currentUnit.equals("cup")){

                updateUnitTypesUsingOther(Quantity.Unit.cup);

            } else if(currentUnit.equals("ounce")){

                updateUnitTypesUsingOther(Quantity.Unit.oz);

            } else if(currentUnit.equals("pint")){

                updateUnitTypesUsingOther(Quantity.Unit.pint);

            } else if(currentUnit.equals("quart")){

                updateUnitTypesUsingOther(Quantity.Unit.quart);

            } else if(currentUnit.equals("gallon")){

                updateUnitTypesUsingOther(Quantity.Unit.gallon);

            } else if(currentUnit.equals("pound")){

                updateUnitTypesUsingOther(Quantity.Unit.pound);

            } else if(currentUnit.equals("milliliter")){

                updateUnitTypesUsingOther(Quantity.Unit.ml);

            } else if(currentUnit.equals("liter")){

                updateUnitTypesUsingOther(Quantity.Unit.liter);

            } else if(currentUnit.equals("milligram")){

                updateUnitTypesUsingOther(Quantity.Unit.mg);

            } else {

                updateUnitTypesUsingOther(Quantity.Unit.kg);

            }

        }

    }

    public void updateUnitTypesUsingTsp(Quantity.Unit currentUnit){

        // Convert the value in the EditText box to a double
        double doubleToConvert = Double.parseDouble(amountTextView.getText().toString());

        // Combine value to unit
        String teaspoonValueAndUnit = doubleToConvert + " tsp";

        // Change the value for the teaspoon TextView
        teaspoonTextView.setText(teaspoonValueAndUnit);

        // Update all the Unit Text Fields
        updateUnitTextFieldUsingTsp(doubleToConvert, Quantity.Unit.tbs, tablespoonTextView);
        updateUnitTextFieldUsingTsp(doubleToConvert, Quantity.Unit.cup, cupTextView);
        updateUnitTextFieldUsingTsp(doubleToConvert, Quantity.Unit.oz, ounceTextView);
        updateUnitTextFieldUsingTsp(doubleToConvert, Quantity.Unit.pint, pintTextView);
        updateUnitTextFieldUsingTsp(doubleToConvert, Quantity.Unit.quart, quartTextView);
        updateUnitTextFieldUsingTsp(doubleToConvert, Quantity.Unit.gallon, gallonTextView);
        updateUnitTextFieldUsingTsp(doubleToConvert, Quantity.Unit.pound, poundTextView);
        updateUnitTextFieldUsingTsp(doubleToConvert, Quantity.Unit.ml, milliliterTextView);
        updateUnitTextFieldUsingTsp(doubleToConvert, Quantity.Unit.liter, literTextView);
        updateUnitTextFieldUsingTsp(doubleToConvert, Quantity.Unit.mg, milligramTextView);
        updateUnitTextFieldUsingTsp(doubleToConvert, Quantity.Unit.kg, kilogramTextView);

    }

    public void updateUnitTextFieldUsingTsp(double doubleToConvert, Quantity.Unit unitConvertingTo,
                                            TextView theTextView){

        Quantity unitQuantity = new Quantity(doubleToConvert, Quantity.Unit.tsp);

        String tempUnit = unitQuantity.to(unitConvertingTo).toString();

        theTextView.setText(tempUnit);

    }

    public void updateUnitTypesUsingOther(Quantity.Unit currentUnit){

        // Convert the value in the EditText box to a double
        double doubleToConvert = Double.parseDouble(amountTextView.getText().toString());

        // Create a Quantity using the teaspoon unit
        Quantity currentQuantitySelected = new Quantity(doubleToConvert, currentUnit);

        // Create the String for the teaspoon TextView
        String valueInTeaspoons = currentQuantitySelected.to(Quantity.Unit.tsp).toString();
        // Set the text for the teaspoon TextView
        teaspoonTextView.setText(valueInTeaspoons);

        updateUnitTextFieldUsingTsp(doubleToConvert, currentUnit,
                Quantity.Unit.tbs, tablespoonTextView);

        updateUnitTextFieldUsingTsp(doubleToConvert, currentUnit,
                Quantity.Unit.cup, cupTextView);

        updateUnitTextFieldUsingTsp(doubleToConvert, currentUnit,
                Quantity.Unit.oz, ounceTextView);

        updateUnitTextFieldUsingTsp(doubleToConvert, currentUnit,
                Quantity.Unit.pint, pintTextView);

        updateUnitTextFieldUsingTsp(doubleToConvert, currentUnit,
                Quantity.Unit.quart, quartTextView);
        updateUnitTextFieldUsingTsp(doubleToConvert, currentUnit,
                Quantity.Unit.gallon, gallonTextView);

        updateUnitTextFieldUsingTsp(doubleToConvert, currentUnit,
                Quantity.Unit.pound, poundTextView);

        updateUnitTextFieldUsingTsp(doubleToConvert, currentUnit,
                Quantity.Unit.ml, milliliterTextView);
        updateUnitTextFieldUsingTsp(doubleToConvert, currentUnit,
                Quantity.Unit.liter, literTextView);

        updateUnitTextFieldUsingTsp(doubleToConvert, currentUnit,
                Quantity.Unit.mg, milligramTextView);

        updateUnitTextFieldUsingTsp(doubleToConvert, currentUnit,
                Quantity.Unit.kg, kilogramTextView);


        // Set the currently selected unit to the number in the EditText
         if(currentUnit.name().equals(currentQuantitySelected.unit.name())){

            // Create the TextView text by taking the value in EditText and adding
            // on the currently selected unit in the spinner
            String currentUnitTextViewText = doubleToConvert + " " +
                    currentQuantitySelected.unit.name();

            // Create the TextView name to change by getting the currently
            // selected quantities unit name and tacking on _text_view
            String currentTextViewName = currentQuantitySelected.unit.name() +
                    "_text_view";

            // Get the resource id needed for the textView to use in findViewById
            int currentId = getResources().getIdentifier(currentTextViewName, "id",
                    MainActivity.this.getPackageName());

            // Create an instance of the TextView we want to change
            TextView currentTextView = (TextView) findViewById(currentId);

            // Put the right data in the TextView
            currentTextView.setText(currentUnitTextViewText);
        }

    }

    public void updateUnitTextFieldUsingTsp(double doubleToConvert, Quantity.Unit currentUnit,
                                            Quantity.Unit preferredUnit, TextView targetTextView){

        Quantity currentQuantitySelected = new Quantity(doubleToConvert, currentUnit);

        // Algorithm used quantityInTbs.to(Unit.tsp).to(Unit.ounce)

        String tempTextViewText = currentQuantitySelected.to(Quantity.Unit.tsp).
                to(preferredUnit).toString();

        targetTextView.setText(tempTextViewText);


    } 

}

Android Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.newthinktank.derekbanas.conversion" >

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/Theme.AppCompat" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


Referensi