Isuru Edirisinghe
4 min readJun 10, 2019

Create a Simple Currency Converter using a Web Service on Android

Sample of Final Application

You would often come across the need to use a Web Service within your Applications, it is rather easier to implement a Web Service or use an existing Web Service to get certain tasks done in an Application.

Here I outline the steps I followed in creating an Android application for currency conversion developed using the WebService provided at https://api.exchangeratesapi.io/latest for exchange rates from EUR (Euro) to a set of other currencies. This WebService provides with a JSON array when a GET request is made to it, which we can use in our Application!

The Steps to Follow :

  1. Create a new Android Project
  2. Prepare the layouts for your Activities, here I will be using 2, one which shows the list of available conversion rates (I will perform this in activity_main.xml along with row_item.xml for displaying the conversion items as a list) and another for the user to calculate based on selected conversion rate (activity_main.xml)!

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="10dp"
>

<ListView
android:id="@+id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</RelativeLayout>

row_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_columnWeight="1"
android:layout_marginLeft="10dp"
android:textSize="30dp"
android:textColor="#1E90FF"
android:id="@+id/textViewId"
android:layout_row="0"
android:layout_column="1"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_columnWeight="1"
android:layout_marginLeft="10dp"
android:textSize="20dp"
android:textColor="#4B0082"
android:id="@+id/textViewCountry"
android:layout_row="1"
android:layout_column="1"
/>
</GridLayout>

activity_calc.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CalcActivity"
>

<LinearLayout
android:layout_width="344dp"
android:layout_height="495dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:gravity="center_horizontal"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"
>

<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberDecimal"
/>

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="Calculate"
/>

<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="75dp"
android:gravity="bottom|center_horizontal"
android:text="TextView"
/>
</LinearLayout>
</android.support.constraint.ConstraintLayout>

3. Now prepare a Class for storing Conversion data as Objects, which we will later use in the MainActivity.java to display the WebService response as a list!

Then create a class to manage the Currency list , I named it CustomCurrencyList.java

And finally the MainActivity.java where we will do the magic!

Currency.java :

package isuru117.conversionwebservice;
public class Currency{
String id;
String value;

public Currency(String i, String CurrencyName) {
super();
this.id = i;
this.value = CurrencyName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}

CustomCurrencyList.java :

package isuru117.conversionwebservice;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;

public class CustomCurrencyList extends BaseAdapter {


private Activity context;
ArrayList<Currency> countries;


public CustomCurrencyList(Activity context, ArrayList<Currency> countries) {
// super(context, R.layout.row_item, countries);
this.context = context;
this.countries=countries;

}

public static class ViewHolder
{
TextView textViewId;
TextView textViewCurrency;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row=convertView;

LayoutInflater inflater = context.getLayoutInflater();
ViewHolder vh;
if(convertView==null) {
vh=new ViewHolder();
row = inflater.inflate(R.layout.row_item, null, true);
vh.textViewId = (TextView) row.findViewById(R.id.textViewId);
vh.textViewCurrency = (TextView) row.findViewById(R.id.textViewCurrency);
// store the holder with the view.
row.setTag(vh);
}
else {
vh = (ViewHolder) convertView.getTag();
}

vh.textViewCurrency.setText(countries.get(position).getValue());
vh.textViewId.setText(""+countries.get(position).getId());

return row;
}

public long getItemId(int position) {
return position;
}

public Object getItem(int position) {
return position;
}

public int getCount() {

if(countries.size()<=0)
return 1;
return countries.size();
}
}

MainActivity.java:

package isuru117.conversionwebservice;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;

import javax.net.ssl.HttpsURLConnection;

import static android.content.ContentValues.TAG;

public class MainActivity extends AppCompatActivity {

private Button btnSubmit;
String responseText;
StringBuffer response;
URL url;
Activity activity;
ArrayList<Currency> countries=new ArrayList<Currency>();
private ProgressDialog progressDialog;
ListView listView;

private String path = "https://api.exchangeratesapi.io/latest";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity = this;
//btnSubmit = (Button) findViewById(R.id.btnSubmit);
listView = (ListView) findViewById(android.R.id.list);
new GetServerData().execute();

}

class GetServerData extends AsyncTask
{

@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Fetching Exchange Rates..");
progressDialog.setCancelable(false);
progressDialog.show();

}

@Override
protected Object doInBackground(Object[] objects) {
return getWebServiceResponseData();
}

@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);

// Dismiss the progress dialog
if (progressDialog.isShowing())
progressDialog.dismiss();
// For populating list data
CustomCurrencyList customCurrencyList = new CustomCurrencyList(activity, countries);
listView.setAdapter(customCurrencyList);

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Toast.makeText(getApplicationContext(),"You Selected "+countries.get(position).getValue()+ " as Currency", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), CalcActivity.class);
intent.putExtra("CUR",countries.get(position).getId());
intent.putExtra("RATE",countries.get(position).getValue());
startActivity(intent);
}

});


}
}
protected Void getWebServiceResponseData() {

try {

url = new URL(path);
Log.d(TAG, "ServerData: " + path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");

int responseCode = conn.getResponseCode();

Log.d(TAG, "Response code: " + responseCode);
if (responseCode == HttpsURLConnection.HTTP_OK) {
// Reading response from input Stream
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String output;
response = new StringBuffer();

while ((output = in.readLine()) != null) {
response.append(output);
}
in.close();
}}
catch(Exception e){
e.printStackTrace();
}

responseText = response.toString();
//Call ServerData() method to call webservice and store result in response
// response = service.ServerData(path, postDataParams);
Log.d(TAG, "data:" + responseText);
try {
JSONObject jsonarray = new JSONObject(responseText);
JSONObject rates = jsonarray.getJSONObject("rates");

Iterator<?> keys = rates.keys();

while(keys.hasNext() ) {
String key = (String)keys.next();
String value = rates.getString(key);
Log.d(TAG, "id:" + key);
Log.d(TAG, "Currency:" + value);
Currency CurrencyObj=new Currency(key,value);
countries.add(CurrencyObj);
Log.d(TAG,countries.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}

4. We’re not quite done here, we need to handle the Calculation Activity , which we stored in activity_calc.xml!

CalcActivity.java:

package isuru117.conversionwebservice;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class CalcActivity extends AppCompatActivity {

double rate;
String cur;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calc);
final TextView btn=(TextView) findViewById(R.id.textView);

Intent intent = getIntent();

cur = intent.getStringExtra("CUR");
rate = Double.parseDouble(intent.getStringExtra("RATE"));

final TextView txtResult = (TextView) findViewById(R.id.textView);
txtResult.setText("0.00 EUR to " +cur+" is : 0.00");

}


public void onClick(final View v) {

final EditText txtAmount = (EditText) findViewById(R.id.editText);
final TextView txtResult = (TextView) findViewById(R.id.textView);

double amount = Double.parseDouble(txtAmount.getText().toString());

double result = rate * amount;

txtResult.setText(amount + " EUR to " +cur+" is : " + result);

}
}

Now we’re done developing the project!

Download the Project Source Here !

Download the APK Here !

Isuru Edirisinghe

I’m currently a Software Engineering intern at 99x Technologies. Loves to get dirty with any form of code written in any modern language!