close
close
currency converter app android source code java

currency converter app android source code java

3 min read 07-12-2024
currency converter app android source code java

Building an Android Currency Converter App in Java: A Comprehensive Guide

This article provides a detailed walkthrough of building a currency converter Android app using Java. We'll cover the essential components, from setting up the project to integrating an API for real-time exchange rates. This guide assumes a basic understanding of Java and Android development.

I. Project Setup and Dependencies:

  1. Android Studio: Ensure you have Android Studio installed and configured. Create a new project, selecting "Empty Activity" and giving it a name like "CurrencyConverter". Choose Java as the language.

  2. Internet Permission: Your app needs internet access to fetch exchange rates. Add the following line within the <manifest> tag in your AndroidManifest.xml file:

<uses-permission android:name="android.permission.INTERNET" />
  1. Dependencies: We'll use a library to handle network requests and JSON parsing. Add the following dependencies to your build.gradle (Module: app) file:
dependencies {
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
}

Sync your project after adding these dependencies.

II. API Integration:

We need a reliable API to fetch current exchange rates. Many free APIs exist, but remember to check their terms of service and usage limits. For this example, we'll assume you're using a free API (replace with your chosen API's endpoint and parameters):

public interface CurrencyApi {
    @GET("latest") // Replace with your API's endpoint
    Call<CurrencyResponse> getExchangeRates(@Query("base") String baseCurrency);
}

CurrencyResponse is a POJO (Plain Old Java Object) that maps the JSON response from your API. You'll need to create this class based on your API's response structure. For example:

public class CurrencyResponse {
    public String base;
    public Map<String, Double> rates;
}

III. UI Design (activity_main.xml):

Design your layout using XML. You'll need:

  • Spinner(s): To select the base and target currencies. Populate these with currency codes (e.g., USD, EUR, GBP).
  • EditText: For inputting the amount to convert.
  • TextView: To display the converted amount.
  • Button: To trigger the conversion.

Example (simplified):

<EditText
    android:id="@+id/amountEditText"
    ... />

<Spinner
    android:id="@+id/baseCurrencySpinner"
    ... />

<Spinner
    android:id="@+id/targetCurrencySpinner"
    ... />

<Button
    android:id="@+id/convertButton"
    android:text="Convert"
    ... />

<TextView
    android:id="@+id/resultTextView"
    ... />

IV. Conversion Logic (MainActivity.java):

  1. Retrofit Setup: Create a Retrofit instance:
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("YOUR_API_BASE_URL") // Replace with your API base URL
        .addConverterFactory(GsonConverterFactory.create())
        .build();

CurrencyApi currencyApi = retrofit.create(CurrencyApi.class);
  1. Conversion Function: This function handles the API call and updates the UI:
private void convertCurrency() {
    String baseCurrency = baseCurrencySpinner.getSelectedItem().toString();
    String targetCurrency = targetCurrencySpinner.getSelectedItem().toString();
    double amount = Double.parseDouble(amountEditText.getText().toString());

    currencyApi.getExchangeRates(baseCurrency).enqueue(new Callback<CurrencyResponse>() {
        @Override
        public void onResponse(Call<CurrencyResponse> call, Response<CurrencyResponse> response) {
            if (response.isSuccessful()) {
                CurrencyResponse currencyResponse = response.body();
                double exchangeRate = currencyResponse.rates.get(targetCurrency);
                double convertedAmount = amount * exchangeRate;
                resultTextView.setText(String.valueOf(convertedAmount));
            } else {
                // Handle API error
            }
        }

        @Override
        public void onFailure(Call<CurrencyResponse> call, Throwable t) {
            // Handle network error
        }
    });
}
  1. Button Click Listener: Attach this function to your "Convert" button's click listener.

V. Error Handling and Enhancements:

  • Implement robust error handling for network issues and API errors. Display user-friendly messages.
  • Add input validation to prevent crashes due to incorrect input (e.g., non-numeric values).
  • Consider adding a progress indicator while fetching data.
  • Improve the UI with better styling and user experience.
  • Implement offline functionality by caching exchange rates.

This detailed guide provides a solid foundation for building your currency converter app. Remember to replace placeholder API details and adapt the code to your chosen API and UI design. Thorough testing and error handling are crucial for a robust and user-friendly application. Consult the official Android documentation and Retrofit documentation for further details and best practices.

Related Posts


Popular Posts