Monday, September 9, 2013

Temperature Converter

In this post, you will learn to create a simple app to convert a temperature in Celsius to Fahrenheit and vise versa. Now you need to open Eclipse program and create a new project and name it as CtoFConverter. If you don't know how to create a project in Elipse, please read this guide Helloworld app.
For the app interface, we need two radiobuttons, one textbox, and one textview. See the picture below.

temperature converter


After creating the CtoFConverter project, please open the activity_main.xml file (in res/layout directory). This file is the source that defines views to be placed on the main activity. Views in Android can be said as components or controls in Java or C#. You need to modify the activity_main.xml file to include the two RadioButtons, one EditText, and one TextView views. So the activity_main.xml file is as shown below.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
   >
<RadioGroup
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton android:id="@+id/ctof_radio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/ctof_radio"
android:onClick="onRadioButtonClicked"
android:checked="true"
/>
<RadioButton android:id="@+id/ftoc_radio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/ftoc_radio"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>

<EditText
    android:id="@+id/txt_input"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="@string/hint_ctof"
    android:inputType="numberDecimal" />

<TextView
    android:id="@+id/txt_result"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textColor="#992211"
    android:textSize="20sp"
/>
</LinearLayout>

The two RadioButtons are placed in the RadioGroup so that only one of them can be selected at a time. The first RadioButton is for Celsius to Fahrenheit conversion. In contrast, the second RadioButton is for Fahrenheit to Celsius conversion.
To define id property for each view, we use android:id property. The @ symbol tells the compiler to read text after the forward slash (/). By using the plus sign (+) before the id, you want to tell the compiler that this id is new and needs to be created. The width and height of a view can be defined by using android:layout_width and android:layout_height respectively. The wrap_content value of these properties specifies that the view wraps its content. The fill_parent value allows the view to be expanded to fit the screen. Besides, wrap_content and fill_parent, you can specify the width and height of the values in dp or sp unit.
To assign text to each RadioButton or other views that support text property, you need to use the android:text property. For the first RadioButton the value of the text property is taken from the string resource called ctof_radio. This string and other strings that are used for this interface construction are defined in strings.xml file (in res/values directory). You need to place @string before the name of the string to indicate that this string is defined in the strings.xml resource file.

This is the content of the strings.xml file used in this app:
<?xml version="1.0" encoding="utf-8"?>

<resources>

    <string name="app_name">CtoFConverter</string>
    <string name="action_settings">Settings</string>
    <string name="ctof_radio">Celsius to Fahrenheit</string>
    <string name="ftoc_radio">Fahrenheit to Celsius</string>
    <string name="hint_ctof">Enter celsius value</string>
    <string name="hint_ftoc">Enter fahrenheit value</string>

</resources>

The EditText view is a textbox that allows the user to type a number in Celsius or Fahrenheit. The inputType property specifies the input type of the textbox. The value of the input type can be one of the followings:
-number allows integer number input.
-numberDecimal allows floating-point number input.
-textPassword allows text input. The original text is kept. However, the password symbols are displayed instead of the actual characters.
-textMultiLine allows the text to expand to multiple lines.
-textCapWords displays a capital character at the beginning of each word.
-textCapSentences displays a capital character at the beginning of each sentence.
-date allows a value in date format input.
-time allows a value in time format input.
-datetime allows a combination of date and time input.

The last view that we use is TextView. The TextView view is used to display the result of the conversion. When the user types a value in the EditText view, the calculation is made to produce a result. The result is displayed in the TextView view.
The result can be a value in Celsius or Fahrenheit according to the RadioButtons selection. If the first RadioButton is selected, the user is prompted to enter a value in Celsius so that the conversion is from Celsius to Fahrenheit and the result is in Fahrenheit. Otherwise, the conversion is from Fahrenheit to Celsius so that the result is in Celsius.

All views are placed inside the LinearLayout. You can treat the LinearLayout in Andoid as a layout manager in Java. It is used to layout components in the app interface. The LinearLayout arranges the views in one orientation-vertical or horizontal. You can use its android:orientation property to specify vertical or horizontal orientation.

Receive click event from RadioButton

To perform an action when the RadioButton is clicked, you need to register to the click event to the RadioButton view by using its android:onClick property. The value of this property will be a method to perform the action. In this app, the method to perform the action when the RadioButon is clicked is onRadioButtonClicked. This method is defined in the MainActivity.java file. When the first RadioButton is selected, the hint text of the EditText changes to Enter Celsius value. If the second RadioButton is selected, the the hint text of the EditText changes to Enter Fahrenheit value.

MainActivity.java file
package com.example.ctofconverter;
import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;

public class MainActivity extends Activity {

    private String strFrom="Celsius";
    private String strTo="Fahrenheit";
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
 
    public void onStart(){
    super.onStart();
    EditText et=(EditText)findViewById(R.id.txt_input); //refer tot he EditText, txt_input
    et.addTextChangedListener(new ChangeListener()); //register the view with the text change listener
    et.setHint("Enter celsius value");
    }
 
    class ChangeListener implements TextWatcher{
   
    public void beforeTextChanged(CharSequence s, int start, int before, int count){
   
   
    }
   
    public void onTextChanged(CharSequence s, int start, int before, int count){
   
    convert(strFrom,strTo);  //do conversions  
    }
   
    public void afterTextChanged(Editable ed){
   
   
    }
    }
 
    public void convert(String from, String to){
    EditText et=(EditText) findViewById(R.id.txt_input);
    TextView tv=(TextView) findViewById(R.id.txt_result);
    double cvalue=0.0;
double fvalue=0.0;
    if(et.getText().toString().length()>0){
    if(from.equals("Celsius")) //convert from Celsius to Fahrenheit
    {
    cvalue=Double.parseDouble(et.getText().toString());
    fvalue=32+(cvalue*180.0/100.0);
    tv.setText(fvalue+to);
    }
    else{ //convert from Fahrenheit to Celsus
    fvalue=Double.parseDouble(et.getText().toString());
    cvalue=(fvalue-32)*100.0/180.0;
    tv.setText(cvalue+to);
    }
   
    }
   
    }
 
    public void onRadioButtonClicked(View view) {
    boolean checked = ((RadioButton) view).isChecked();
    EditText et=(EditText)findViewById(R.id.txt_input);

    switch(view.getId()) {
    case R.id.ctof_radio:
    if (checked){ //the first RadioButton is selected
    strFrom="Celsius";
    strTo="Fahrenheit";
    et.setHint("Enter celsius value");    
   
    }
    break;
    case R.id.ftoc_radio:
    if (checked){ //the second RadioButton is selected
    strFrom="Fahrenheit";
    strTo="Celsius";
    et.setHint("Enter fahrenheit value");
   
}
    break;
    }
    }
 
}

Refer a view in code

When you place views in the activity_main.xml file, the id of each view is recorded in the R.java file (in gen directory). When writing code for the main activity or other activities, referring to the views allows you to use the views. You can refer a view by using the findViewById(R.id.id_of_the_veiw) of the Activity class. For example, to refer the EditText, txt_input can be done by this line of code:

EditText et=(EditText)findViewById(R.id.txt_input);

Receive text change event

When the user types a value in the EditText, txt_input. This value immediately is calculated to produce a result. Then the result is displayed in the TextView, txt_result. The actions that convert and display the result happen when the user is making change to the value of EditText, txt_input. To perform an action when the text of EditText view is making changed, you need to register this view with the text change listener  by using the addTextChangedListener(TextWatcher tw) method. You will need a class to implement the TextWatcher interface. Then create an object of this class and supply it to the addTextChangedListener method. In this app, this class is called ChangeListener. You must implement all methods of the TextWatcher interface. These methods are beforeTextChanged, onTextChanged, and afterTextChanged.

doing temperature conversion when text change


Do conversions

To convert a value input in the EditText, txt_input, to produce a result, the convert (String from, String to) is defined in the MainActivity.java file. This method will be placed in the onTextChanged method of ChangeListener class.
The conversion from Fahrenheit to Celsius value can be performed by using the formula below:
Celsius=(Fahrenheit-32)*100.0/180.0;
To convert from Fahrenheit to Celsius value, you can use the formula below:
Fahrenheit=32+(Celsius*180.0/100.0);

No comments:

Post a Comment