Saturday, August 14, 2010

Simple Temperature Converter

4.1. Create Project

. Select File -> New -> Other -> Android -> Android Project and create the Android project "de.vogella.android.tempconvertor" Maintain the following.



Tip

I think this wizard should have the option to add the project to an existing working set. Please stare at Android New Project Wizard should have the option to add to Working set to get this functionality.

Press "Finish". This should create the following directory structure.


"R.java" is a generated class which contains the text and the UI elements. Please do not try to modify this class manually.

4.2. Two faces of things

The Android SDK allows to maintain certain artifacts, e.g. strings and UI's, in two ways, via a rich editor and directly via XML. The following description tries to use the rich UI but for validation lists also the XML. You can switch between the two things the the tab on the lower part of the screen. For example:

4.3. Create attributes

Android allows to create attributes for resources, e.g. for strings and / or colors. These attributes can be used in your UI definition via XML or in your Java source code.
Select the file "res/values/string.xml" and press "Add". Select "Color" and maintain "myColor" as the name and "#3399CC" as the value.




Add also the following "String" attributes. String attributes allow to translate the application at a later point.

Table 1. String Attributes
NameValue
buttonHandlermyClickHandler
celsiusto Celsius
fahrenheitto Fahrenheit




Switch to the XML representation and validate that you maintained the values correctly.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, Convert!</string>
    <string name="app_name">Celsius to Fahrenheit Converter</string>
 <color name="myColor">#3399CC</color>
<string name="buttonHandler">myClickHandler</string>
<string name="celsius">to Celsius</string>
<string name="fahrenheit">to Fahrenheit</string>
<string name="calc">Calculate</string>
</resources>

   

4.4. Add UI Elements

Select "res/layout/main.xml" and open the Android editor via double-click. This editor allows to maintain the UI via drag and drop or directly via the XML source code. You can switch between both representations via the tabs at the bottom of the editor.
Switch to "main.xml" and verify that your XML looks like the following. Especially the grouping of RadioButtons into a group is difficult to get right with the editor.
Delete the "Hello World, Hello!" via a right mouse click. From the "Views" bar, drag in an "EditText". Add from the layout a "RadioGroup" and then two RadioButtons, add one "Button". The result should look like the following and the corresponding XML is listed below. Especially putting the RadionButtons into the RadioGroup is hard via the rich UI editor.



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical" android:layout_width="fill_parent"
 android:layout_height="fill_parent">

<EditText android:text="@+id/EditText01" android:id="@+id/EditText01" android:layout_width="wrap_content" android:layout_height="wrap_content"></EditText>
 <RadioGroup android:id="@+id/RadioGroup01"
  android:layout_width="wrap_content" android:layout_height="wrap_content">
  <RadioButton android:text="@+id/RadioButton01" android:id="@+id/RadioButton01"
   android:layout_width="wrap_content" android:layout_height="wrap_content"></RadioButton>
  <RadioButton android:text="@+id/RadioButton02" android:id="@+id/RadioButton02"
   android:layout_width="wrap_content" android:layout_height="wrap_content"></RadioButton>
 </RadioGroup>
 <Button android:text="@+id/Button01" android:id="@+id/Button01"
  android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>

   

4.5. Maintain UI properties

If you select a UI element you can change its properties via the properties view. Select EditText and change the property "Layout Width" to "fill_parent".


Assign the "celsius" string attribute to your "text" property of the first radio button and "fahrenheit" to the second. Set the property "Checked" to true for the first RadioButton. Assign "calc" to the text property of your button and assign "buttonHandler" to the "onClick" property. Delete the text property in the EditText (this means no text will be initially shown) and set the "Input type" property to "numberSigned" and "number decimal".
Select the complete widget and use the Properties view to set the property "background" to the color attribute "myColor".


Switch to the "main.xml" tab and verify that the XML is correctly maintained.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@color/myColor">

<EditText android:id="@+id/EditText01" android:layout_height="wrap_content" android:layout_width="fill_parent" android:inputType="numberSigned|numberDecimal"></EditText>
 <RadioGroup android:id="@+id/RadioGroup01"
  android:layout_width="wrap_content" android:layout_height="wrap_content">
  <RadioButton android:id="@+id/RadioButton01"
   android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/celsius" android:checked="true"></RadioButton>
  <RadioButton android:id="@+id/RadioButton02"
   android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/fahrenheit"></RadioButton>
 </RadioGroup>
 <Button android:id="@+id/Button01"
  android:layout_height="wrap_content" android:onClick="@string/buttonHandler" android:layout_width="wrap_content" android:text="@string/calc"></Button>
</LinearLayout>

   

4.6. Code your applicatioin

Change your code in "Convert.java" to the following. Note that the "myClickHandler" will be called basedon the "On Click" property of your button.

package de.vogella.android.tempconvertor;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

public class Convert extends Activity {
 private EditText text;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  text = (EditText) findViewById(R.id.EditText01);

 }

 // This method is called at button click because we assigned the name to the
 // "On Click property" of the button
 public void myClickHandler(View view) {
  switch (view.getId()) {
  case R.id.Button01:
   RadioButton celsiusButton = (RadioButton) findViewById(R.id.RadioButton01);
   RadioButton fahrenheitButton = (RadioButton) findViewById(R.id.RadioButton02);
   if (text.getText().length() == 0) {
    Toast.makeText(
      this,
      "Please enter a valid number", Toast.LENGTH_LONG).show();
    return;
   }
   
   float inputValue = Float.parseFloat(text.getText().toString());
   if (celsiusButton.isChecked()) {
    text.setText(String
      .valueOf(convertFahrenheitToCelcius(inputValue)));
   } else {
    text.setText(String
      .valueOf(convertCelciusToFahrenheit(inputValue)));
   }
   // Switch to the other button
   if (fahrenheitButton.isChecked()) {
    fahrenheitButton.setChecked(false);
    celsiusButton.setChecked(true);
   } else {
    fahrenheitButton.setChecked(true);
    celsiusButton.setChecked(false);
   }
   break;
  }
 }

 // Converts to celcius
 private float convertFahrenheitToCelcius(float fahrenheit) {
  return ((fahrenheit - 32) * 5 / 9);
 }

 // Converts to fahrenheit
 private float convertCelciusToFahrenheit(float celsius) {
  return ((celsius * 9) / 5) + 32;
 }
}
   

4.7. Start Project

To start the Android Application, select your project, right click on it, Run-As-> Android Application Be patient, the emulator starts up very slow. You should get the following result.


Type in a number, select your conversion and press the button. The result should be displayed and the other option should get selected.

4.8. Using the home menue

If you press the Home button you can also select your application.