Browse through more tutorials here. If you'd like to see a tutorial on any particular topic, do leave a comment in the wishlist page. We frequently post new tutorials along with app releases. You may subscribe to our newsletter to get all updates in your inbox.
Now you can get the latest Java source bundled with each app update. Install the app from Google Play and go to Settings > Extras.

Create a currency converter application using Yahoo! API

DownloadDownload
By

Keywords: ConnectivityManager HttpGet XmlPullParser SAXParser SimpleCursorAdapter SQLiteDatabase ContentProvider SQLiteQueryBuilder BroadcastReceiver IntentService AChartEngine Search Dialog Animation TableLayout

Contents
  • ForexWiz
    • assets
      • hist
        • USDQAR.csv
        • USDMXN.csv
        • USDEUR.csv
        • USDDKK.csv
        • USDRON.csv
        • USDEEK.csv
        • USDJPY.csv
        • USDTRY.csv
        • USDCZK.csv
        • USDNOK.csv
        • USDRSD.csv
        • USDKRW.csv
        • USDEGP.csv
        • USDARS.csv
        • USDCNY.csv
        • USDLVL.csv
        • USDISK.csv
        • USDZAR.csv
        • USDAED.csv
        • USDCLP.csv
        • USDPHP.csv
        • USDHKD.csv
        • USDILS.csv
        • USDSEK.csv
        • USDIDR.csv
        • USDBRL.csv
        • USDTWD.csv
        • USDRUB.csv
        • USDSAR.csv
        • USDHRK.csv
        • USDIRR.csv
        • USDGBP.csv
        • USDAUD.csv
        • USDLKR.csv
        • USDDZD.csv
        • USDPLN.csv
        • USDPKR.csv
        • USDNZD.csv
        • USDUAH.csv
        • USDBGN.csv
        • USDCAD.csv
        • USDSGD.csv
        • USDTHB.csv
        • USDCHF.csv
        • USDHUF.csv
        • USDMYR.csv
        • USDNGN.csv
        • USDINR.csv
      • fonts
        • Font.ttf
      • result.txt
      • symbols.xml
      • quote.xml
    • src
      • com
        • appsrox
          • forexwiz
            • model
              • Rate.java
              • Quote.java
              • AbstractModel.java
              • Symbol.java
              • DbHelper.java
            • common
              • Constants.java
              • Util.java
            • data
              • RateUpdater.java
              • QuoteHandler.java
              • RateLoader.java
              • Downloader.java
              • QuoteLoader.java
              • SymbolLoader.java
              • QuoteUpdater.java
            • SplashActivity.java
            • MainActivity.java
            • SearchableActivity.java
            • InitTask.java
            • SettingsActivity.java
            • ForexWiz.java
            • SuggestionProvider.java
            • DataService.java
            • InfoActivity.java
            • Disclaimer.java
    • res
      • anim
        • progress.xml
      • drawable-mdpi
        • back_pattern.png
        • ic_dialog_menu_generic.png
        • ic_menu_refresh.png
      • drawable
        • curved.xml
        • bg_repeat.xml
        • separator.xml
        • curved2.xml
      • menu
        • options.xml
        • context.xml
      • drawable-ldpi
        • values-sw600dp
          • dimens.xml
        • drawable-xxhdpi
          • brunei.png
          • russia.png
          • peru.png
          • uruguay.png
          • jamaica.png
          • liberia.png
          • hongkong.png
          • croatia.png
          • venezuela.png
          • unitedkingdom.png
          • kazakhstan.png
          • euro.png
          • vietnam.png
          • honduras.png
          • southafrica.png
          • uzbekistan.png
          • sweden.png
          • hungary.png
          • iran.png
          • taiwan.png
          • belarus.png
          • cuba.png
          • australia.png
          • mexico.png
          • trinidadandtobago.png
          • oman.png
          • bosnia_and_herzegovina.png
          • switzerland.png
          • somalia.png
          • poland.png
          • srilanka.png
          • philippines.png
          • jersey.png
          • serbia.png
          • ukraine.png
          • indonesia.png
          • china.png
          • unitedstates.png
          • mozambique.png
          • brazil.png
          • norway.png
          • lithuania.png
          • solomonislands.png
          • elsalvador.png
          • azerbaijan.png
          • guernsey.png
          • barbados.png
          • kyrgyzstan.png
          • zimbabwe.png
          • qatar.png
          • southkorea.png
          • paraguay.png
          • lebanon.png
          • ghana.png
          • egypt.png
          • mongolia.png
          • netherlands.png
          • singapore.png
          • saudiarabia.png
          • thailand.png
          • seychelles.png
          • cayman_islands.png
          • sainthelena.png
          • chile.png
          • fiji.png
          • costarica.png
          • pakistan.png
          • macedonia.png
          • denmark.png
          • latvia.png
          • mauritius.png
          • guyana.png
          • nicaragua.png
          • colombia.png
          • albania.png
          • panama.png
          • namibia.png
          • dominicanrepublic.png
          • cambodia.png
          • israel.png
          • argentina.png
          • estonia.png
          • laos.png
          • botswana.png
          • bolivia.png
          • yemen.png
          • belize.png
          • canada.png
          • guatemala.png
          • suriname.png
          • bahamas.png
          • bermuda.png
          • malaysia.png
          • gibraltar.png
          • iceland.png
          • aruba.png
          • newzealand.png
          • japan.png
          • czechrepublic.png
          • turkey.png
          • bulgaria.png
          • nepal.png
          • tuvalu.png
          • afghanistan.png
          • syria.png
          • falklandislands.png
          • northkorea.png
          • isleofman.png
          • romania.png
          • nigeria.png
          • india.png
        • xml
          • searchable.xml
          • settings.xml
          • settings2.xml
        • layout
          • row.xml
          • splash.xml
          • main.xml
          • info.xml
        • values-sw720dp-land
          • dimens.xml
        • drawable-xhdpi
          • delete.png
          • ic_launcher.png
        • drawable-hdpi
          • system.png
          • throbber.png
          • plus.png
          • throbber2.png
          • ic_btn_round_more.png
        • values
          • strings.xml
          • dimens.xml
          • colors.xml
          • arrays.xml
          • styles.xml
      • libs
        • achartengine-1.0.0.jar
        • android-support-v4.jar
      • AndroidManifest.xml
     

    1. Overview

    In this tutorial we show how to create a currency converter app in Android. If you travel to foreign countries or do forex trading then you already know the utility of such an application. Even if you do neither of these you'd still find it interesting to check the exchange rates of world currencies and how they vary over time.
    Developing a currency converter app is a good way of learning Android development as it involves a lot of concepts such as making REST calls, parsing the data, storing into a database, as well as updating the data in background. Apart from these we also allow user to check historical exchange rates which involves plotting charts using third party libraries like AChartEngine.
    Here is the design of the app.

    Screenshot Screenshot

    The main screen is implemented using a ListView with custom layout for the rows. And the details screen uses AChartEngine library to render the chart. There is a search mechanism available in the main screen which allows user to search a currency and add it to the list.
    There is also a settings screen which we cover in the tutorial. So let's start coding!

    2. Create a new Eclipse Android project

    In Eclipse, go to File > New > Project and in the New Project dialog, expand Android folder to select Android Project.
    In New Android Project dialog enter the project details as follows.
    Project name: ForexWiz
    Build Target: Android 2.1
    Application name: Forex Wiz
    Package name: com.appsrox.forexwiz
    Create Activity: MainActivity
    Click Finish. The project gets created in your workspace.

    3. Define the Data model

    The data model of the application comprises of two tables. The Symbol table holds basic information about each currency such as its name, country, ISO code, and whether the user is tracking the currency. The Quote table holds the exchange rates between currencies and other useful information which would be updated regularly. Class Diagram Create a package com.appsrox.forexwiz.model to hold the data model classes.
    The data model classes are simple Java beans with attributes and getters/setters corresponding to the table columns. Additionally, we implement CRUD (create, read, update, delete) functionality in the model class itself. Here is some code to give you an idea.
    	public class Symbol extends AbstractModel {
    		
    		public static final String TABLE_NAME = "symbol";
    		public static final String SQL_CREATE = 
    			"CREATE TABLE symbol (_id INTEGER PRIMARY KEY AUTOINCREMENT, country TEXT, name TEXT, code TEXT, isTracked INTEGER)";
    		
    		private String country;
    		private String name;
    		private String code;
    		private boolean isTracked;
    		
    		// constructors
    		// getters and setters	
    
    		public long save(SQLiteDatabase db) {
    			ContentValues cv = new ContentValues();
    			cv.put("country", country);
    			cv.put("name", name);
    			cv.put("code", code);
    			cv.put("isTracked", 0);
    			return db.insert(TABLE_NAME, null, cv);
    		}
    
    		public boolean update(SQLiteDatabase db) {
    			ContentValues cv = new ContentValues();
    			cv.put("isTracked", isTracked ? 1 : 0);		
    			return db.update(TABLE_NAME, cv, "_id = ?", new String[]{String.valueOf(id)}) 
    					== 1 ? true : false;
    		}
    		
    		public boolean load(SQLiteDatabase db) {
    			Cursor cursor = db.query(TABLE_NAME, null, "code = ?", new String[]{code}, null, null, null);
    			try {
    				if (cursor.moveToFirst()) {
    					id = cursor.getLong(cursor.getColumnIndex("_id"));
    					country = cursor.getString(cursor.getColumnIndex("country"));
    					name = cursor.getString(cursor.getColumnIndex("name"));
    					code = cursor.getString(cursor.getColumnIndex("code"));
    					isTracked = cursor.getInt(cursor.getColumnIndex("isTracked")) == 1 ? true : false;
    					return true;
    				}
    				return false;
    			} finally {
    				cursor.close();
    			}
    		}
    		
    		// Override equals and hashCode	
    	}
    					

    Declare the column names as constants as done for table name.

    Additionally, create DbHelper class by extending SQLiteOpenHelper for accessing and managing the database.
    	public class DbHelper extends SQLiteOpenHelper {
    
    		public static final String DB_NAME = "forexwiz";
    		public static final int DB_VERSION = 1;
    
    		public DbHelper(Context context) {
    			super(context, DB_NAME, null, DB_VERSION);
    		}
    
    		@Override
    		public void onCreate(SQLiteDatabase db) {
    			db.execSQL(Symbol.SQL_CREATE);
    			db.execSQL(Quote.SQL_CREATE);
    		}
    
    		@Override
    		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    		}
    	}
    					
    The database gets created along with tables when we access it the first time. We will cover this later in the section for Application class.

    4. The Android Manifest file

    The AndroidManifest.xml file describes the Android application. We need to edit this file to declare various components, features, permissions, etc. used by the application.
    To start with, we show you just the important elements but we will modify this file as we develop components for the application.
    	<?xml version="1.0" encoding="utf-8"?>
    	<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    		package="com.appsrox.forexwiz"
    		android:versionCode="1"
    		android:versionName="1.0" >
    
    		<uses-sdk android:minSdkVersion="7" android:targetSdkVersion="8" />
    		
    		<uses-permission android:name="android.permission.INTERNET" />
    		<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    
    		<application
    			android:name=".ForexWiz"
    			android:allowBackup="true"
    			android:icon="@drawable/ic_launcher"
    			android:label="@string/app_name"
    			android:theme="@style/AppTheme" >
    		</application>
    	</manifest>
    					
    Notice that we specified a name attribute for the <application> element which declares that we have implemented a Application class for the application.

    5. The Application class

    The Application class is a good place to declare all globals in an application although it's not mandatory. To use it we create a class which extends Application and override onCreate() method where the variables are instantiated.
    	public class ForexWiz extends Application {
    		
    		public static DbHelper dbHelper;
    		public static SQLiteDatabase db;
    		public static SharedPreferences sp;
    		
    		public static final String BASE_CURRENCY = "base_currency";
    		public static final String DEFAULT_CURRENCY = "USD";
    
    		@Override
    		public void onCreate() {
    			super.onCreate();
    			
    			PreferenceManager.setDefaultValues(this, R.xml.settings, false);
    			sp = PreferenceManager.getDefaultSharedPreferences(this);
    			
    			dbHelper = new DbHelper(this);
    			db = dbHelper.getWritableDatabase();
    		}
    		
    		public static String getBaseCurrency() {
    			return sp.getString(BASE_CURRENCY, DEFAULT_CURRENCY);
    		}
    		public static void setBaseCurrency(String currencyCode) {
    			sp.edit().putString(BASE_CURRENCY, currencyCode).commit();
    		}
    	}
    					
    We instantiate DbHelper and invoke getWritableDatabase() to get an instance of the database. When the app is launched the very first time then this is the instant when the database is created and the code in onCreate(SQLiteDatabase db) of DbHelper is executed.

    If you execute a lot of SQL inside onCreate(SQLiteDatabase db) method either to create tables or populate data then its better to invoke getWritableDatabase() in a separate (non UI) thread.

    In the next section we'll develop a Preference screen and create a settings.xml file which we have already used in the Application class to load default preference values.

    Next Page » 1

    Subscribe to our newsletter and get all updates in your inbox.
    Recent Posts
    App Gen
    App Name:
    Project Name:
    Package:
    Screens:
    Splash
    Login
    Help
    Main
    List  Grid  Pager
    Detail
    Settings
    Options:
    Action Bar
    Navigation Drawer
    Dummy Data
    Generate
    Free Apps