Create real time currency converter app in Android Studio

In this tutorial, we will learn to create a Currency converter app in android using java. We can develop an app in android either using java or kotlin. To develop an android project we can either use Eclipse IDE or we can directly use Android Studio (any version). We will use: exchangeratesapi.io API key here.

For Eclipse IDE we need to download and install Android SDK and ADT plugin and Android version which is a very lengthy process. So instead of Eclipse IDE, the Android studio is preferred by most of the developers.

In this tutorial, we will use Android Studio 3.6.3 (latest version).

To create a new project in android studio: currency converter

  1. Click on the file option on the upper right corner of our android studio screen.
  2. After that, we can select a project template.

Android Studio Screen

Android Studio Screen

3. On clicking on the next option we will get the screen to configure the project. Here we can select the name of our project, package name, location to store our project, language, and minimum SDK.

4. Click on the finish button.

Android studio screen

Create project in android studio

Start coding

In the above figure, there are two options

  1. MainActivity.java
  2. activity_main.xml

In MainActivity.java we will write our java code and activity_main.xml we will design the view of our app.

To design the view of our app we will get two option

  1. We can directly drag and drop the required tool to our emulator.
  2. Write an XML code to design the view of our application.

Code:

package com.example.myapplication;


import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.JsonObject;

import Kamal.kamalBuild;
import Kamal.kamalInterface;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {
    Button button;
    EditText currencyToBeConverted;
    EditText currencyConverted;
    Spinner convertToDropdown;
    Spinner convertFromDropdown;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        currencyConverted = (EditText) findViewById(R.id.currency_converted);
        currencyToBeConverted = (EditText) findViewById(R.id.currency_to_be_converted);
        convertToDropdown = (Spinner) findViewById(R.id.to);
        convertFromDropdown = (Spinner) findViewById(R.id.from);
        button = (Button) findViewById(R.id.button);


        String[] dropDownList = {"USD", "INR","EUR","NZD"};
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, dropDownList);
        convertToDropdown.setAdapter(adapter);
        convertFromDropdown.setAdapter(adapter);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                kamalInterface retrofitInterface = kamalBuild.getRetrofitInstance().create(kamalInterface.class);

                Call<JsonObject> call = retrofitInterface.getExchangeCurrency(convertFromDropdown.getSelectedItem().toString());
                call.enqueue(new Callback<JsonObject>() {
                    @Override
                    public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                        JsonObject res = response.body();
                        JsonObject rates = res.getAsJsonObject("conversion_rates");
                        double currency = Double.valueOf(currencyToBeConverted.getText().toString());
                        double multiplier = Double.valueOf(rates.get(convertToDropdown.getSelectedItem().toString()).toString());
                        double result = currency * multiplier;
                        currencyConverted.setText(String.valueOf(result));
                    }

                    @Override
                    public void onFailure(Call<JsonObject> call, Throwable t) {

                    }


                });


            }
        });}}


-----------------------------------------------------------
create a package and in that package create one interface and one class.
-----------------------------------------------------------
import retrofit2.converter.gson.GsonConverterFactory;

public class kamalBuild {
    private static Retrofit retrofit;

    public static Retrofit getRetrofitInstance() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl("https://api.exchangerate-api.com/")
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

        }
        return retrofit;
    }
}

-----------------------------------------------------------
      
package Kamal;

import com.google.gson.JsonObject;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;

public interface kamalInterface {
    @GET("v6/1929988978e7cd9733e5e654/latest/{currency}")
    Call<JsonObject> getExchangeCurrency(@Path("currency") String currency);
}
-----------------------------------------------------------

MainActivity.java

The name of our package is com.example.myapplication.

We generally use Bundle to pass the data between various activities of Android. We can map the data from the string value to various data types with the help of parsing using Bundle.

The view is the rectangular piece of the area at the front end of our application.

Array Adapter converts the Array List of objects into view items that can be loaded into a listview container.

AppCompat is the set of libraries that are used to develop the app with various versions. This means when a new version of the android studio gets released the appcompat helps us to work with old libraries from the new version.

Gson is called google JSON and JSON stands for javascript object notation. It is used to convert data to JSON or XML code. This means when we pass any data to gson it takes the java object and returns a corresponding JSON.

Retrofit is the HTTP client it helps to retrieve and upload JSON via web services.

Oncreate()

In the onCreate method of our project, we created objects of  TextView, EditText, spinner, and button.

Then we created a drop-down list in which we passed the currencies of several countries.

Then in the onClick method of our project, we are converting the values from the currency of one country to the currency of any other country depending on the choice of the user. We are using the package that we created to implement the libraries and function of google JSON and Retrofit to convert our currency. We just passing the values and with the help of functionalities of retrofit and GSON that we created in the package, we are converting the currency.

The res.getAsJsonObject(“conversion_rates”) method helps us to get the rates to which we need to multiply the currency to get the required currency.

Further SetText is used to display the result obtained by multiplying the currency entered and the rate generated on the front end of the app.

KamalInterface

Retrofit makes downloading XML or JSON data from web API easier.

In the package kamal, we are creating an instance of retrofit in retrofitInterface.

We are using Exchange Rates-API

In the retrofit interface, 1929988978e7cd9733e5e654 is the key to our API used.V6 is the version of the API.

Link to get the API::http://exchangeratesapi.io/

Just enter your email id to get the API key.

Method getExchangeCurrency(@Path(“currency”) String currency)  is used to get the rate of exchange of the currency.

In the above method, the “currency”  is used because we are selecting the currency from the drop-down menu. Instead of currency, we can also write “USD”, “EUR”, etc.

KamalBuild

In kamalBuild, we are creating the instance of Retrofit in which we are passing the base address of our API and addConvertFactory method.

 

dependencies
{
implementation fileTree(dir: 'libs', include: ['*.jar'])
   implementation 'androidx.appcompat:appcompat:1.0.2'
   implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
   implementation 'com.squareup.retrofit2:retrofit:2.7.1'
   implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
   implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
   implementation 'com.google.code.gson:gson:2.6.2'
   testImplementation 'junit:junit:4.12'
   androidTestImplementation 'androidx.test.ext:junit:1.1.0'
   androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'}

To run our application we need to add these dependencies in the Gradle file of our project.

These dependencies are for version 29.

 

XML Code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Currency Converter"
        android:textSize="36dp"
        android:layout_gravity="center"
        android:layout_margin="20dp"
        />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_gravity="center"
        >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="****ENTER AMOUNT****"
            android:textSize="15dp"
            android:layout_margin="20dp"
            />
        <EditText
            android:id="@+id/currency_to_be_converted"
            android:layout_width="250dp"
            android:layout_height="40dp"
            android:layout_gravity="center"
            android:layout_marginBottom="20dp"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="From Currency:"
            android:textSize="15dp"
            android:layout_margin="20dp"
            />
        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            android:layout_marginBottom="20dp"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            >
            <Spinner
                android:layout_width="250dp"
                android:layout_height="40dp"
                android:id="@+id/from"
                android:layout_gravity="center"

                />
        </RelativeLayout>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="To Currency:"
            android:textSize="15dp"
            android:layout_margin="20dp"
            />
        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            android:layout_marginBottom="20dp"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            >
            <Spinner
                android:layout_width="250dp"
                android:layout_height="40dp"
                android:id="@+id/to"
                android:layout_gravity="center"

                />
        </RelativeLayout>

    </LinearLayout>
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="162dp"
        android:layout_marginLeft="162dp"
        android:layout_marginTop="30dp"
        android:layout_marginEnd="162dp"
        android:layout_marginRight="162dp"
        android:layout_marginBottom="30dp"
        android:textColor="@color/colorPrimaryDark"

        android:text="Convert"
        />

    <EditText
        android:id="@+id/currency_converted"
        android:layout_width="250dp"
        android:layout_height="40dp"
        android:layout_gravity="center"
        android:layout_marginBottom="20dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:hint="Result"
        />

</LinearLayout>
    
  

We can modify the front end of our app according to our needs. We can add images, background colors, etc.

To add an image we need to download an image and save it in the drawable folder. From there we can add it to our ImageView from the src option.

We can even add audio to our app. For adding any audio file we need to create a raw folder in our app and then we can add the audio file to our app.

In the above XML code, first of all, we set Layout to LinearLayout.

ImageView helps us to display images.

EdiText helps us to take input from the user.

The button helps us to perform any operation with the help of any method mentioned in the onClick function.

Spinner helps us to display a drop-down menu.

Spinner is used for creating a drop-down menu. We can modify our spinner, Button, EditText TextView, etc in our XML code.

Modifying spinner, Button, EditText, TextView, etc means adding curves, changing color, and much more to give an impressive and attractive look to the app.

In the above XML code, we are just creating id of our image views, button, spinner, text view, and edit view. And adjusting them according to the view we want.

 

View of Emulator:

Create real time currency converter app in Android Studio

 

Output:

Create real time currency converter app in Android Studio

Leave a Reply

Your email address will not be published. Required fields are marked *