How to build a Currency Tracker Android App - Hive Programmers

avatar

Greetings to my favorite science community online, StemSocial.

It's @skyehi and I'm back with another exciting new episode to my series, Android App development tutorials for beginners.

Today's tutorial may be one of the longest I've put together so far because we have quite a lot of work to do.

For today's blog, we're going to build a currency tracker application. There are many different countries in the world and each country has their very own unique currency.

Polish_20231214_142435420.jpgOriginal Image Source by Markus Spiske from Pexels

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

A currency tracker App has one main task and that is it's designed to help users monitor and stay updated on currency exchange rates.

What it does is to provide real-time or historical data on the values of different currencies relative to each other. So with the currency tracker App, you'll know how well your country's currency is doing in the market.

My country's currency is a bit lower than the United States Dollar, USD but it used to be equal to the dollar some years ago. I use great currency tracker apps and even websites to stay updated on what's going on when it comes to currency value or exchange rates.

Now guys since this is still a programming tutorial for beginners, we'll build a very basic Currency Tracker App.

As we make more progress and also switch the programming language from Java to Kotlin, we'll build a more complex Currency Tracker app with which the users can track their preferred currency pairs, set notifications for rate changes, and access various tools to analyze currency trends.

I always emphasize on learning how to build very useful Apps as a programmer or developer because it can help assure your success and put you on demand for many customers who wish to build very useful Apps.

The currency tracker App is really useful for travelers, investors, and anyone interested in staying informed about currency fluctuations.

Now that I've gotten all the formalities and descriptions out of the way, let's get started with our App development tutorials guys. I hope you're excited for this one.

2dk2RRM2dZ8gKjXsrozapsD83FxL3Xbyyi5LFttAhrXxr16mCe4arfLHNDdHCBmaJroMz2VbLrf6Rxy9uPQm7Ts7EnXL4nPiXSE5vJWSfR53VcqDUrQD87CZSpt2RKZcmrYrze8KanjkfyS8XmMCcz4p33NZmfHE4S9oRo3wU2.png

Prerequisites and Setting Up the Android Studio Project

I always include this step purposefully for newcomers to my tutorial series. There are a few softwares you would need to have installed on your PC to be able to successfully go through with this tutorial.

  • Android Studio IDE: This is the platform we'll be building all our Android Apps on. However when we start making games, we might need to work on other platforms but that's for the intermediary level of our tutorial.

  • Java Development Kit, JDK: Like I've been saying throughout the series, our plan is to start with Java programming language for the basics and when we move to the Intermediary levels of this tutorial, we'll switch it up to Kotlin.

You need JDK installed on your PC if you want your computer to be able to execute the Java codes we'll be writing.


Alright guys, at this point I'll assume my readers have successfully installed the necessary softwares. Let's now start our work by creating a new Android Studio project.

So guys open Android Studio and click on "create a new Android project". Choose a suitable name for your currency tracker App and also choose the package name of the App.

Please don't forget to ensure that Java is the selected programming language for your project and not Kotlin - if you leave it as Kotlin, the project will build the template using Kotlin language and you will certainly get confused unless you are experienced in Kotlin programming

Now guys afterwards click on next button and choose Empty Activity as the template of your App. When you're satisfied with the settings of your project, click finish, sit back and wait while Android Studio prepares your new App project.

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Requesting Permissions in AndroidManifest

Alright guys the first thing to do after the project is created is to request a couple of permissions in AndroidManifest.xml file.

Since our Currency tracker App would need access to the Internet to fetch the currency data, we need to request internet permission. The App would need to fetch currency exchange rates from an external API which would require the use of the internet

Not going through with this step could lead to your App not working at all so this is really important guys.

Here's how your permission code should look like

<uses-permission android:name="android.permission.INTERNET" />

Also guys in more advanced App tutorials, we'll go into the details of network state permissions but I wanted to take this opportunity to introduce you to that.

Although it's optional, it's very important to use if you want your App to check the network state, that is whether the device is connected to the internet or not.

This would be just like how your browser sends you notifications or a sign that you're offline. It uses this permissions to check the phone's network state.

Here's how your permission code for network state should look like

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Please guys ensure that these two permissions are added outside the <application> tag but still within the <manifest> tag of your AndroidManifest.xml file.

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Design User Interface (UI)

It's time for us to work on the frontend of our Currency Tracker App. This is going to be a really simple and basic user interface and we'll need two very important elements for it to work. We would need a Spinner and RecyclerView.

The spinner's job will be to allow the user of our App to scroll through a list of different currencies to check its value relative to other currencies.

So for example, when the user runs the App, he or she should be able to see the local country currency and its price or value in other currencies like from Euro to dollar.

We'll be designing this interface inside the activity_main.xml file.

Here's how your user interface code should look like guys

<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:padding="16dp"
    tools:context=".MainActivity">

    <Spinner
        android:id="@+id/baseCurrencySpinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:prompt="@string/select_base_currency" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/currencyRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        android:background="@android:color/white" />

</LinearLayout>

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Fetching Currency Exchange Rates

Now guys remember I said earlier that we would need Internet permissions because our App would probably use a third party API to get the data on Currency Exchange rates?

Well it's time to implement that third party API in our App. We'll be using an API called "Retrofit". This means we need to add its dependency to our App project.

The Retrofit dependencies will be added inside the app/build.gradle file where all other dependencies are usually added.

I have shown my code example of how the dependency should look like. You can simply copy it and paste it in your app/build.gradle file and when you're done, click on the "Sync" button for Android Studio to download the dependency and add it to your project.

Here's how your dependency code should look like

// app/build.gradle
dependencies {
    // ...
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
}

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Creating Open Exchange Rates Service Interface

Now guys one thing we'll need for our currency tracker App to function is a service interface for Open Exchange Rates. This means we have to create a java file for that. So go ahead and create a Java file and name it CurrencyService.java.

You would need to add your App ID to the code we're going to write. You can easily search online and get a lot of short tutorials on how to know your app ID. However if you're having troubles locating it, please let me know in the comments guys.

Here's how your service interface code should look like

// CurrencyService.java
public interface CurrencyService {
    @GET("latest.json")
    Call<ExchangeRateResponse> getLatestRates(@Query("app_id") String appId);
}

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Handling API Response

Another thing we would need to work on is how our App would handle the API responses. This is the part where we use the Retrofit code to handle API responses.

So guys I hope you added the Retrofit dependency successfully otherwise the code will read as an error.

To handle the API responses we need to create a RetrofitClient.java class.

Here's how your code should look like.

// RetrofitClient.java
public class RetrofitClient {
    private static Retrofit retrofit = null;

    public static Retrofit getClient(String baseUrl) {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

We're making great progress here and I believe we're now halfway through our tutorial. It's quite a lengthy one so brace yourselves guys. We have completed the first part of the guide.

The next part would include working on our RecyclerView Adapter, updating the UI and also handling user interactions.

2dk2RRM2dZ8gKjXsrozapsD83FxL3Xbyyi5LFttAhrXxr16mCe4arfLHNDdHCBmaJroMz2VbLrf6Rxy9uPQm7Ts7EnXL4nPiXSE5vJWSfR53VcqDUrQD87CZSpt2RKZcmrYrze8KanjkfyS8XmMCcz4p33NZmfHE4S9oRo3wU2.png

Create RecyclerView Adapter

Now since we need our App to display exchange rates of different currencies, we would need to implement a RecyclerView Adapter.

Remember earlier on we created a RecyclerView inside the activity_main.xml file? Well it's time to create an adapter for that.

To do this we need to create a separate Java class and name it CurrencyAdapter.java.

Here's how the adapter code should look like guys

// CurrencyAdapter.java
public class CurrencyAdapter extends RecyclerView.Adapter<CurrencyAdapter.ViewHolder> {

    private List<ExchangeRate> exchangeRates;

    public CurrencyAdapter(List<ExchangeRate> exchangeRates) {
        this.exchangeRates = exchangeRates;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.currency_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        ExchangeRate rate = exchangeRates.get(position);
        // Bind data to UI elements in the ViewHolder
        holder.currencyNameTextView.setText(rate.getCurrencyName());
        holder.exchangeRateTextView.setText(String.valueOf(rate.getRate()));
    }

    @Override
    public int getItemCount() {
        return exchangeRates.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public TextView currencyNameTextView;
        public TextView exchangeRateTextView;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            currencyNameTextView = itemView.findViewById(R.id.currencyNameTextView);
            exchangeRateTextView = itemView.findViewById(R.id.exchangeRateTextView);
        }
    }
}

In the code we just wrote, we added the exchange rates of the currency and the currency name. It's now time to work on updating or changing the UI when there's a new exchange rate.

Update UI with Exchange Rates

Based on the fetched exchange rates, we would need to Update the UI inside our MainActivity.java file.

This part is very important because assuming that USD is 10 times more than let's say currency X and it changes to being 11 times more, the new exchange rate difference needs to show inside our App for both USD and currency X.

Without this step, the user may never be able to see the updated or new exchange rates.

Here's the code to update UI based on Exchange Rate changes

// MainActivity.java
public class MainActivity extends AppCompatActivity {

    private Spinner baseCurrencySpinner;
    private RecyclerView currencyRecyclerView;
    private CurrencyAdapter currencyAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        baseCurrencySpinner = findViewById(R.id.baseCurrencySpinner);
        currencyRecyclerView = findViewById(R.id.currencyRecyclerView);

        // Set up RecyclerView
        currencyRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        
        // Dummy data for testing
        List<ExchangeRate> dummyData = new ArrayList<>();
        dummyData.add(new ExchangeRate("USD", "US Dollar", 1.0));
        dummyData.add(new ExchangeRate("EUR", "Euro", 0.85));
        
        // Initialize adapter with the dummy data
        currencyAdapter = new CurrencyAdapter(dummyData);
        currencyRecyclerView.setAdapter(currencyAdapter);
    }
}

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Handle User Interactions

It's time to work on the logic to handle user interactions. Let's say the user of our App wants to select USD as the base currency to check its value relative to all other currencies in our App's spinner list, we need to build the logic for that

This is a model of how the code should look like. You're totally free to customize it or improve on it guys.

// MainActivity.java
baseCurrencySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
        String selectedCurrency = baseCurrencySpinner.getSelectedItem().toString();
        // Fetch and update rates based on the selected base currency
        // Call the API or update the RecyclerView with new rates
    }

    @Override
    public void onNothingSelected(AdapterView<?> parentView) {
        // Do nothing
    }
});

Now guys we would need to create a layout file for RecyclerView item. We'll create the file and name it currency_item.xml.

Each currency in the list would have a name and an exchange rate value.

The layout will define how each currency item appears in the RecyclerView.

Here's how your design code should look like

(html comment removed:  res/layout/currency_item.xml )
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="16dp">

    <TextView
        android:id="@+id/currencyNameTextView"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:textColor="@android:color/black"
        android:text="Currency Name" />

    <TextView
        android:id="@+id/exchangeRateTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:textColor="@android:color/black"
        android:text="Exchange Rate" />
</LinearLayout>

Please make sure that this layout file is inside the res/layout directory of your Android Studio project. The RecyclerView Adapter we created and named as CurrencyAdapter.java earlier on will refer to this layout for inflating each item in the list.

You can totally improve on the design and logic of the app however you see fit guys.

2dk2RRM2dZ8gKjXsrozapsD83FxL3Xbyyi5LFttAhrXxr16mCe4arfLHNDdHCBmaJroMz2VbLrf6Rxy9uPQm7Ts7EnXL4nPiXSE5vJWSfR53VcqDUrQD87CZSpt2RKZcmrYrze8KanjkfyS8XmMCcz4p33NZmfHE4S9oRo3wU2.png

Wow, this has been a really long tutorial I guess. I wouldn't want to put way too much stress on you since this is still a beginner's tutorial series.

There's clearly a lot of work to be done to have this App look as advanced as the most modern Currency Trackers out there. As we make more progress we'll make it more complex and functional.

Thank you so much for taking the time to read today's blog. I'm happy you have made it this far in the series guys. It brings me so much joy that this series will help a lot of people improve on their programming skills and become better Android App developer.

As always if you're having troubles installing Android Studio and Java or troubles writing the codes, adding dependencies or running the App, please let me know in the comments.

Have a lovely day and catch you next time on StemSocial. Goodbye 👨‍💻


You Can Follow Me @skyehi For More Like This And Others



0
0
0.000
1 comments
avatar

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

Thanks for including @stemsocial as a beneficiary, which gives you stronger support. 
 

0
0
0.000