How to create Android Unit Converter – Unit Converter Example Tutorial

How to create Android Unit Converter

In this tutorial, we are going to learn how to create android unit converter. Unit Converter is a popular tool that we use everyday to convert from one unit to another.

If you check Google Play Store you will see a lot of android unit converters you can download and install in your mobile phone. If you are wondering how to create a unit converter or a custom unit converter for your personal use, I think this tutorial will be good for you.

Although we are not going to cover all the units in the world but what we will achieve will give you a leverage to further develop and improve your unit converter.

The unit converter will use a simple ListView to display all the elements we have add. Feel free to redesign your UI to meet the need of what you plan to achieve.

When you click any of the ListView item it will take you to another Activity page where you can add the value and select your conversion units and the result will be display to you.

This Unit conversion application will use a separate class that take in input values from users and return the result of the conversion.

In other to get a better understanding of what we planned to achieve, I have included an image to illustrate the interface before.

Unit Converter

In other worst, if you want to test the working application, you can head over to Google Play Store and download my Complete Mathematics Android Application.

Before we start, it is important for you to understand the tools and environment I used in this application development tutorial. Feel free to use any tools you are familiar with.

Windows 7

Android Studio

Sony Xperia ZL

Min SDK 14

Target SDK 22

To create a new android application project, following the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidUnitConverter

Package: com.inducesmile.androidunitconverter

Keep other default selections

Continue to click on next button until Finish button is active, then click on Finish Button.

If you are using Android Studio as your choice IDE, the new project will create a default

MainActivity.java file and its corresponding layout file. Open the two files because we are going to make use of them.

We will start with the main layout file – activity_main.xml. We are going to add a ListView in the layout file. The ListView will hold all the various Units we plan to add. The code snippet for this file is shown below. You can copy and paste it in your own project.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <ListView
        android:id="@+id/statistics_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:dividerHeight="1.0sp"
        android:scrollbars="none"
        android:background="@android:color/transparent"
        android:cacheColorHint="@android:color/transparent"
        android:layout_marginBottom="8dp"
        android:layout_centerHorizontal="true"/>

</RelativeLayout>

As you can see from the code above, it is very simple and straight forward so nothing much to explain. If you have any question in the course of this tutorial, endeavor to use the comment box below and I will try as much as possible to answer you.

Now we will move over to the MainActivity.java file. We will get the handler for our ListView. Before then, we will create an Adapter that will be use to bind our data source to the ListView control.

Within the Adapter class, we will inflate a layout that will hold each item in the ListView control. You can redesign and modify this layout the way you want your ListView Item interface to appear.

The code in the inflate layout file of the Adapter class is shown below.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="12dp"
    android:paddingBottom="12dp">
    <com.github.ivbaranov.mli.MaterialLetterIcon
        android:id="@+id/imageView"
        android:layout_width="@dimen/letter_icon_size"
        android:layout_height="@dimen/letter_icon_size"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:contentDescription="@string/hello_world"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="16dp"
        app:mli_shape_color="@color/primary_text"
        app:mli_shape_type="circle"
        app:mli_letter_color="@color/icons"
        app:mli_letter_size="26"
        android:layout_marginTop="8dp"/>

    <TextView
        android:id="@+id/navigation_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="14sp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="12dp"
        android:textColor="@color/primary_text"
        android:layout_alignTop="@+id/imageView"
        android:layout_toRightOf="@+id/imageView"
        android:text="@string/hello_world"/>
</RelativeLayout>

You can see that I used the following View plugin – MaterialLetterIcon. This third-party plugin is used to add a random color circle image to the left of TextView control. You can read more about this custom view here. You also have the option to remove it and add your own ImageView control there.

We have created an Adapter class that inflates the layout above. You can copy and paste the code for the CalculationAdapter class and in your project.

import android.content.Context;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.github.ivbaranov.mli.MaterialLetterIcon;
import java.util.List;
import java.util.Random;
import elearning.chidi.com.elearning.R;
public class CalculationAdapter extends BaseAdapter {
    private LayoutInflater lInflater;
    private List<String> listStorage;
    private final TypedValue mTypedValue = new TypedValue();
    private int mBackground;
    private List<String> mValues;
    private int[] mMaterialColors;
    private int mType;
    private Context context;
    private static final Random RANDOM = new Random();
    public CalculationAdapter(Context context, List<String> customizedListView) {
        lInflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.context = context;
        listStorage = customizedListView;
    }
    @Override
    public int getCount() {
        return listStorage.size();
    }
    @Override
    public Object getItem(int position) {
        return listStorage.get(position);
    }
    @Override
    public long getItemId(int position) {
        return position;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder listViewHolder;
        if(convertView == null){
            listViewHolder = new ViewHolder();
            convertView = lInflater.inflate(R.layout.calculation_list, parent, false);
            listViewHolder.calculationText = (TextView)convertView.findViewById(R.id.navigation_name);
            listViewHolder.letterIcon = (MaterialLetterIcon)convertView.findViewById(R.id.imageView);
            convertView.setTag(listViewHolder);
        }else{
            listViewHolder = (ViewHolder) convertView.getTag();
        }
        mMaterialColors = context.getResources().getIntArray(R.array.colors);
        mBackground = mTypedValue.resourceId;
        mValues = this.listStorage;
        listViewHolder.calculationText.setText(listStorage.get(position));
        listViewHolder.letterIcon.setShapeColor(mMaterialColors[RANDOM.nextInt(mMaterialColors.length)]);
        listViewHolder.letterIcon.setLetter(mValues.get(position));
        return convertView;
    }
    static class ViewHolder{
        TextView calculationText;
        MaterialLetterIcon letterIcon;
    }
}

What we did in the CalculationAdapter class is to extend a BaseAdapter and override the getView(int position, View convertView, ViewGroup parent)  method of the BaseAdapter class. The ViewHolder pattern was use to holder the View controls in the layout file. The data source was passed as a parameter in CalculationAdapter class and it is used to bind its data to the ListView item’s layout file.

With the Adapter file out of the way, we will go on to create our MainActivity.java file. Remember that this class will get the instance of the ListView object and call it setAdapter() method which will take an instance of our Adapter as one of its parameter. You can copy and paste the code for this class in your project.

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import elearning.chidi.com.elearning.adapter.CalculationAdapter;
public class UnitConverterFragment extends Fragment {
    public UnitConverterFragment() {
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_unit_converter, container, false);
        List<String> calculationSolver = calculationList();
        ListView calculation = (ListView) view.findViewById(R.id.statistics_list);
        CalculationAdapter tutorialAdapter = new CalculationAdapter(getActivity().getApplicationContext(), calculationSolver);
        calculation.setAdapter(tutorialAdapter);
        calculation.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position){
                    case 0:
                        Intent unitIntent = new Intent(getActivity(), UnitConverterActivity.class);
                        startActivity(unitIntent);
                        break;
                    case 1:
                        Intent lengthIntent = new Intent(getActivity(), LengthConverterActivity.class);
                        startActivity(lengthIntent);
                        break;
                    case 2:
                        Intent massIntent = new Intent(getActivity(), MassConverterActivity.class);
                        startActivity(massIntent);
                        break;
                    case 3:
                        Intent pressureIntent = new Intent(getActivity(), PressureConverterActivity.class);
                        startActivity(pressureIntent);
                        break;
                    case 4:
                        Intent volumeIntent = new Intent(getActivity(), VolumeConverterActivity.class);
                        startActivity(volumeIntent);
                        break;
                    case 5:
                        Intent speedIntent = new Intent(getActivity(), SpeedConverterActivity.class);
                        startActivity(speedIntent);
                        break;
                    case 6:
                        Intent temperatureIntent = new Intent(getActivity(), TemperatureConverterActivity.class);
                        startActivity(temperatureIntent);
                        break;
                    case 7:
                        Intent timeIntent = new Intent(getActivity(), TimeConverterActivity.class);
                        startActivity(timeIntent);
                        break;
                    case 8:
                        Intent energyIntent = new Intent(getActivity(), EnergyConverterActivity.class);
                        startActivity(energyIntent);
                        break;
                    case 9:
                        Intent powerIntent = new Intent(getActivity(), PowerConverterActivity.class);
                        startActivity(powerIntent);
                        break;
                    case 10:
                        Intent velocityIntent = new Intent(getActivity(), VelocityConverterActivity.class);
                        startActivity(velocityIntent);
                        break;
                }
            }
        });
        return view;
    }
    private List<String> calculationList() {
        List<String> calculations = new ArrayList<String>();
        calculations.add("Area");
        calculations.add("Length");
        calculations.add("Mass");
        calculations.add("Pressure");
        calculations.add("Volume");
        calculations.add("Speed");
        calculations.add("Temperature");
        calculations.add("Time");
        calculations.add("Energy");
        calculations.add("Power");
        calculations.add("Velocity");
        return calculations;
    }
}

Now you can run your application and see that we have successfully created our first list of all possible Unit Converter will planned to use in our application.

When you click on any single ListView item it will take you to a new Activity. I intentional separate each new Activity class for every Unit Converter class. So for length conversion, I will create a LengthConverterActivity class that will handle length unit conversion.

We are going to demonstrate this with a single class. You can follow the same proceed to create as much classes as you might need in your application.

Our example will be with the LengthConverterActivity class. The layout file for this activity will contain two Spinner that will hold the two units we will convert from and to.

We will also have an EditText View control which will accept user input for the value a user wants to converter. Finally, we will add about four TextViews – three of the TextView will contain label information while one TextView control will be use for result display. The Button View control will be used to initiate and display the result of the conversion.

The layout file code snippet is displayed below. You can copy and paste it in your own project.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <android.support.v7.widget.Toolbar xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="64dp"
        android:background="@color/color_primary"
        android:minHeight="?attr/actionBarSize"
        app:titleTextAppearance="@style/AppTheme.Toolbar.Title" />
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/icons">
        <ScrollView
            android:id="@+id/scroll_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_above="@+id/relativeAd"
            android:layout_marginBottom="8dp"
            android:background="#ffffff"
            android:padding="16dp"
            android:scrollbars="none">
            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">
                <TextView
                    android:id="@+id/binary_title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:layout_alignParentTop="true"
                    android:layout_marginTop="8dp"
                    android:layout_marginLeft="16dp"
                    android:layout_marginRight="16dp"
                    android:text="@string/title_activity_length_converter"
                    android:textColor="@color/primary_text"
                    android:textSize="18dp"
                    android:textStyle="bold" />
                <TextView
                    android:id="@+id/first_binary"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignLeft="@+id/binary_title"
                    android:layout_below="@+id/binary_title"
                    android:layout_marginTop="24dp"
                    android:text="@string/from_unit"
                    android:textStyle="bold"
                    android:textColor="@color/primary_text" />
                <Spinner
                    android:id="@+id/from_spinner"
                    android:layout_width="match_parent"
                    android:layout_alignLeft="@+id/first_binary"
                    android:layout_below="@+id/first_binary"
                    android:background="@drawable/bottom_border"
                    android:layout_marginTop="4dp"
                    android:layout_height="wrap_content">
                </Spinner>
                <TextView
                    android:id="@+id/enter_a_number"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignLeft="@+id/unit_value"
                    android:layout_below="@+id/from_spinner"
                    android:layout_marginTop="24dp"
                    android:text="@string/enter_value"
                    android:textStyle="bold"
                    android:textColor="@color/primary_text" />
                <EditText
                    android:id="@+id/unit_value"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/enter_a_number"
                    android:layout_marginLeft="16dp"
                    android:layout_marginTop="4dp"
                    android:background="@drawable/bottom_border"
                    android:inputType="numberDecimal"
                    android:padding="8dp" />
                <TextView
                    android:id="@+id/to_unit"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignLeft="@+id/unit_value"
                    android:layout_below="@+id/unit_value"
                    android:layout_marginTop="24dp"
                    android:text="@string/to_unit"
                    android:textStyle="bold"
                    android:textColor="@color/primary_text" />
                <Spinner
                    android:id="@+id/to_spinner"
                    android:layout_width="match_parent"
                    android:layout_alignLeft="@+id/first_binary"
                    android:layout_below="@+id/to_unit"
                    android:background="@drawable/bottom_border"
                    android:layout_marginTop="4dp"
                    android:layout_height="wrap_content">
                </Spinner>
                <Button
                    android:id="@+id/calculation_button"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:background="@drawable/button_all"
                    android:text="@string/calculation_text"
                    android:textAllCaps="false"
                    android:layout_marginTop="32dp"
                    android:padding="8dp"
                    android:layout_below="@+id/to_spinner"
                    android:layout_centerHorizontal="true"
                    android:textColor="@color/primary_text"/>
                <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_below="@+id/calculation_button"
                    android:layout_marginTop="40dp"
                    android:layout_centerHorizontal="true"
                    android:stretchColumns="1">
                    <TableRow>
                        <TextView
                            android:layout_width="0dp"
                            android:layout_height="match_parent"
                            android:layout_weight="1"
                            android:text="@string/unit_result"
                            android:textSize="16sp"
                            android:padding="16dp"
                            android:textColor="@color/primary_text"
                            android:textStyle="bold"/>
                        <TextView
                            android:id="@+id/convert_result"
                            android:layout_height="match_parent"
                            android:layout_width="0dp"
                            android:textColor="@color/primary_text"
                            android:text="@string/no_text"
                            android:padding="16dp"
                            android:layout_weight="1"
                            android:background="@drawable/bottom_border"/>
                    </TableRow>
                </TableLayout>
            </RelativeLayout>
        </ScrollView>        
    </RelativeLayout>
</LinearLayout>

You will see from the Spinner View Controls that we made use of a string array to populate the unit content we are working on. In other to achieve this, you should copy and paste the following string array code in your strings.xml file located in the values folder of your project.

<string-array name="length_units">
    <item id="l_inches">Inches</item>
    <item>Feet</item>
    <item>Yards</item>
    <item>Miles</item>
    <item>Millimeters</item>
    <item>Centimeters</item>
    <item>Meters</item>
    <item>Kilometers</item>
</string-array>

Let’s look into the LengthConverterActivity.java file. We will get all our view handlers by calling the findViewById() method of the Activity class.

We will use an in-built android ArrayAdapter to populate the string array to our Spinner View object.

When the convert button object is click it will check if a user has added an input value to the EditText field, if so, it will sanitize the input value and pass it to LengthUnit class method convert() which will return the result of the convertion.

The code for the LengthUnit class is shown below

package elearning.chidi.com.elearning.ultility;
public class LengthUnit implements UnitInterface {
    private MetricConverter metricConverter;
    @Override
    public double convert(String originalUnit, String newUnit, double input) {
        metricConverter = new MetricConverter();
        double num1 = input;
        double num2 = 0.0d;
        
        String original = originalUnit.toLowerCase();
        String newU = newUnit.toLowerCase();
        
        switch(original)
        {
            case "inches":
            { 
                switch(newU)
                {
                    case "inches":
                        num2 = num1;
                        break;
                    case "feet":
                        
                        num2 = num1 / 12.0d;
                        break;
                    case "yards":
                        
                        num2 = num1 / 36.0d;
                        break;
                    case "miles":
                        
                        num2 = num1 / 63360.0d;
                        break;
                    case "millimeters":
                        
                        num2 = num1 * 25.4d;
                        break;
                    case "centimeters":
                        
                        num2 = num1 * 2.54d;
                        break;
                    case "meters":
                        
                        num2 = num1 * 0.0254d;
                        break;
                    case "kilometers":
                        
                        num2 = num1 * 0.0000254d;
                        break;
                }
                break;
            } 
            case "feet":
            { 
                switch(newU)
                {
                    case "inches":
                        
                        num2 = num1*12.0d;
                        break;
                    case "feet":
                        num2 = num1;
                        break;
                    case "yards":
                        
                        num2 = num1/3.0d;
                        break;
                    case "miles":
                        
                        num2 = num1/5280.0d;
                        break;
                    case "millimeters":
                        
                        num2 = num1*304.8d;
                        break;
                    case "centimeters":
                       
                        num2 = num1*30.48d;
                        break;
                    case "meters":
                        
                        num2 = num1*0.3048d;
                        break;
                    case "kilometers":
                        
                        num2 = num1*0.0003048d;
                        break;
                }
                break;
            } 
            case "yards":
            { 
                switch(newU) {
                    case "inches":
                        
                        num2 = num1 * 36.0d;
                        break;
                    case "feet":
                        
                        num2 = num1 * 3.0d;
                        break;
                    case "yards":
                        num2 = num1;
                        break;
                    case "miles":
                        
                        num2 = num1 / 1760.0d;
                        break;
                    case "millimeters":
                        
                        num2 = num1 * 914.4d;
                        break;
                    case "centimeters":
                        
                        num2 = num1*91.44d;
                        break;
                    case "meters":
                        num2 = num1*0.9144d;
                        break;
                    case "kilometers":
                        
                        num2 = num1/1093.61d;
                        break;
                }
                break;
            } 
            case "miles":
            { 
                switch(newU)
                {
                    case "inches":
                        
                        num2 = num1*6330.0d;
                        break;
                    case "feet":
                        
                        num2 = num1*5280.0d;
                        break;
                    case "yards":
                        
                        num2 = num1*1760.0d;
                        break;
                    case "miles":
                        num2 = num1;
                        break;
                    case "millimeters":
                        
                        num2 = num1*1609340.0d;
                        break;
                    case "centimeters":
                        
                        num2 = num1*160934.0d;
                        break;
                    case "meters":
                        
                        num2 = num1*1609.34d;
                        break;
                    case "kilometers":
                        
                        num2 = num1*1.60934d;
                        break;
                }
                break;
            } 
            case "millimeters":
            { 
                switch(newU)
                {
                    case "inches":
                        num2 = num1*25.4d;
                        break;
                    case "feet":
                        num2 = num1/304.8d;
                        break;
                    case "yards":
                        num2 = num1/914.4d;
                        break;
                    case "miles":
                        num2 = num1/1609000.0d;
                        break;
                    case "millimeters":
                        num2 = num1;
                        break;
                    case "centimeters":
                        num2 = metricConverter.metricConvert(num1, "milli", "centi");
                        break;
                    case "meters":
                        num2 = metricConverter.metricConvert(num1, "milli", "unit");
                        break;
                    case "kilometers":
                        num2 = metricConverter.metricConvert(num1, "milli", "kilo");
                        break;
                }
                break;
            } 
            
            case "centimeters":
            { 
                switch(newU)
                {
                    case "inches":
                        num2 = num1 / 2.54d;
                        break;
                    case "feet":
                        num2 = num1 / 30.48d;
                        break;
                    case "yards":
                        num2 = num1 / 91.44d;
                        break;
                    case "miles":
                        num2 = num1/160934.0d;
                        break;
                    case "millimeters":
                        num2 = metricConverter.metricConvert(num1, "centi", "milli");
                        break;
                    case "centimeters":
                        num2 = num1;
                        break;
                    case "meters":
                        num2 = metricConverter.metricConvert(num1, "centi", "unit");
                        break;
                    case "kilometers":
                        num2 = metricConverter.metricConvert(num1, "centi", "kilo");
                        break;
                }
                break;
            }
            case "meters":
            { 
                switch(newU) {
                    case "inches":
                        num2 = num1 * 39.3701d;
                        break;
                    case "feet":
                        num2 = num1 * 3.28084d;
                        break;
                    case "yards":
                        num2 = num1*1.09361d;
                        break;
                    case "miles":
                        num2 = num1/1609.34d;
                        break;
                    case "millimeters":
                        num2 = metricConverter.metricConvert(num1, "unit", "milli");
                        break;
                    case "centimeters":
                        num2 = metricConverter.metricConvert(num1, "unit", "centi");
                        break;
                    case "meters":
                        num2 = num1;
                        break;
                    case "kilometers":
                        num2 = metricConverter.metricConvert(num1, "unit", "kilo");
                        break;
                }
                break;
            } 
            case "kilometers":
            { 
                switch(newU)
                {
                    case "inches":
                        num2 = num1*39370.1d;
                        break;
                    case "feet":
                        num2 = num1*3280.84d;
                        break;
                    case "yards":
                        num2 = num1*1093.61d;
                        break;
                    case "miles":
                        num2 = num1/1.60934d;
                        break;
                    case "millimeters":
                        num2 = metricConverter.metricConvert(num1, "kilo", "milli");
                        break;
                    case "centimeters":
                        num2 = metricConverter.metricConvert(num1, "kilo", "centi");
                        break;
                    case "meters":
                        num2 = metricConverter.metricConvert(num1, "kilo", "unit");
                        break;
                    case "kilometers":
                        num2 = num1;
                        break;
                }
                break;
            } 
        }
        
        return num2;
    }
}

The convert class was adopted from Github and credit goes to the original owner

Finally, we will finish up with the code by shown the code snippet of our LengthConverterActivity.java file below.

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import elearning.chidi.com.elearning.ultility.LengthUnit;
public class LengthConverterActivity extends ActionBarActivity {
    private Spinner fromSpinner;
    private Spinner toSpinner;
    private EditText inputValue;
    private TextView convertResult;
    private LengthUnit lengthUnit;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_length_converter);
        Toolbar topToolBar = (Toolbar)findViewById(R.id.toolbar);
        setSupportActionBar(topToolBar);
        topToolBar.setLogo(R.drawable.logo);
        topToolBar.setLogoDescription(getResources().getString(R.string.logo_desc));
        
        fromSpinner = (Spinner)findViewById(R.id.from_spinner);
        toSpinner = (Spinner)findViewById(R.id.to_spinner);
        inputValue = (EditText)findViewById(R.id.unit_value);
        convertResult = (TextView)findViewById(R.id.convert_result);
        ArrayAdapter<CharSequence> staticAdapter = ArrayAdapter.createFromResource(this, R.array.length_units, android.R.layout.simple_spinner_item);
        staticAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        fromSpinner.setAdapter(staticAdapter);
        toSpinner.setAdapter(staticAdapter);
        toSpinner.setSelection(1);
        Button convertButton = (Button)findViewById(R.id.calculation_button);
        convertButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkIfFieldIsEmpty(inputValue);
                String convertFromUnit = fromSpinner.getSelectedItem().toString();
                String convertToUnit = toSpinner.getSelectedItem().toString();
                double userInputValue = returnErrorInputs(inputValue);
                lengthUnit = new LengthUnit();
                double returnedConvertedResult = lengthUnit.convert(convertFromUnit, convertToUnit, userInputValue);
                convertResult.setText(String.valueOf(String.format("%.2f", returnedConvertedResult)));
            }
        });
    }
    private double returnErrorInputs(EditText input){
        double returnedInput = 0.0;
        String inputValue = input.getText().toString();
        if(inputValue.equals(".")){
            returnedInput = 0.0;
        }
        else if(inputValue.contains("..")){
            returnedInput = 0.0;
        }
        else{
            returnedInput = Double.parseDouble(inputValue);
        }
        return returnedInput;
    }
    private void checkIfFieldIsEmpty(EditText checkContent){
        if(checkContent.getText().toString().equals("")){
            Toast.makeText(LengthConverterActivity.this, "All the input field must be filled", Toast.LENGTH_LONG).show();
            return;
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_length_converter, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
}

This brings us to the end of this tutorial, If you find anything confusing kindly contact me with your questions or use the comment box below.

Now, when you run your application you will see the interface that looks similar to the sample that was shown earlier on.

You can download the code for this tutorial below. If you are having hard time downloading the tutorials, kindly contact me.

Remember to subscribe with your email so that you will be among the first to receive our new post once it is published.

If you like this tutorial, you can see the Unit Converter in action in my Complete Mathematics App in Google Play Store. You are free to use and modify the source code for your own use.

One Response

Add a Comment