Browse through more Android tutorials. 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 SMS app Create Flappy Bird in Android  »

Create a currency converter application using Yahoo! API


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


2 « Prev Page

6. Create a Preferences screen

Preferences screen Android provides an easy means to implement a preferences screen. Create a settings.xml file under res/xml directory using predefined preferences for ex. ListPreference, EditTextPreference, CheckBoxPreference, etc. Here is an excerpt from the XML file.
	<?xml version="1.0" encoding="utf-8"?>
	<PreferenceScreen xmlns:android="" >
		<PreferenceCategory android:title="General Settings">
			<ListPreference android:key="base_currency"
				android:title="Base Currency"
				android:defaultValue="USD" />
			<EditTextPreference android:key="base_amt"
				android:title="Base Amount" 
				android:dialogTitle="Base Amount"
				android:defaultValue="1.0" />
		<PreferenceCategory android:title="Network Settings">
			<CheckBoxPreference android:key="use_wifi"
				android:title="Use only Wi-Fi" 
				android:defaultValue="false" />        
ListPreference shows a list of choices which is specified through the android:entries attribute. Create an arrays.xml file under res/values directory if not already present. Declare each array using <string-array> tag as shown below.
	<?xml version="1.0" encoding="utf-8"?>
		<string-array name="currency_codes">
		<string-array name="currency_names">
			<item>United States Dollar (USD)</item>
			<item>Euro (EUR)</item>                
			<item>Japanese Yen (JPY)</item>
			<item>British Pound (GBP)</item>
			<item>Australian Dollar (AUD)</item>

You can give any name to these files but they must be present under the appropriate directory (e.g. res/values or res/xml).

Next, create a new activity and make it extend PreferenceActivity. Additionally implement OnSharedPreferenceChangeListener interface so that when user changes a Preference value the summary gets updated.
	public class SettingsActivity extends PreferenceActivity 
									implements OnSharedPreferenceChangeListener {	
		private SharedPreferences sp;

		public void onCreate(Bundle savedInstanceState) {
			sp = getPreferenceScreen().getSharedPreferences();
		protected void onResume(){
			// TODO update preferences

		protected void onPause() {

		public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
We create a generic method to update the summary of a preference when its value is changed. But you can handle individual cases by matching the Preference key which is passed as an argument.
	private void updatePreference(String key){
		Preference pref = findPreference(key);

	    if (pref instanceof ListPreference) {
	        ListPreference listPref = (ListPreference) pref;
		if (pref instanceof EditTextPreference){
			EditTextPreference editPref =  (EditTextPreference) pref;

		if (pref instanceof CheckBoxPreference){
			CheckBoxPreference checkPref =  (CheckBoxPreference) pref;
	        checkPref.setSummary(checkPref.isChecked() ? "True" : "False");
We've completed most of the preparatory work which is common for all our apps. Now let's start implementing the functionality.

7. Implement the Init Task

A currency converter app needs to be initialized with data (e.q. symbols, exchange rates, etc.) before it can be used for the first time. This involves populating the Symbol table with currency information and the Quote table with past exchange rates.
We'll make use of AsyncTask to implement the init task. It executes in the background and on completion notifies the application to launch the Main screen. As you might have guessed we need a Splash screen for our app since the init task may take a while to complete.
Here is a basic outline of the InitTask class and we would implement the logic to populate the tables in subsequent sections.
	public class InitTask extends AsyncTask<Void, Void, Integer> {
		private Context context;
		private SQLiteDatabase db;

		public InitTask(Context context) {
			this.context = context;
			db = ForexWiz.db;

		protected Integer doInBackground(Void... params) {
			try {
				// TODO populate Symbol table
				// TODO populate Quote table
			} catch (SQLException e) {
				return Constants.STATUS_FAILED;
			return Constants.STATUS_SUCCESS;

		protected void onPostExecute(Integer result) {
			Intent intent = new Intent(Constants.ACTION_INIT);
			intent.putExtra(Constants.EXTRA_STATUS, status);
We broadcast the status on completion of the task and set a boolean flag to true in the SharedPreferences so the task is not executed again if completed successfully. Add the following methods to
	public static boolean isInitialized() {
		return sp.getBoolean(Constants.INITIALIZED, false);
	public static void setInitialized() {
		sp.edit().putBoolean(Constants.INITIALIZED, true).commit();

8. The Yahoo! Finance API

Before we write code for populating the tables we need some Forex data. Fortunately, Yahoo! provides an API for developers which they themselves use in their Financial modules. You may want to check these resources to get familar with the API and also with Forex terminologies.

So now you got some idea about what sort of data you can get using the API and the format in which they are returned. For our purpose the following query returns sufficient data to initialize the Quote table.
This Http Get request returns a XML response with exchange rate against USD for World currencies. You can see it for yourself by putting the url in your browser address. Save the XML file in the project assets directory.
Here is an excerpt from the XML response.
	<list version="1.0">
		<resources start="0" count="164">
			<resource classname="Quote">
				<field name="name">USD/KRW</field>
				<field name="price">1129.234985</field>
				<field name="symbol">KRW=X</field>
				<field name="ts">1365062740</field>
				<field name="type">currency</field>
				<field name="volume">0</field>
We also need information such as currency name, country etc. to populate the Symbol table. We had to create our own XML file with the required data. You can get it from here and save it into the assets directory.
We'll next write code to read and parse these XML files and populate the DB tables.
Share the love:  

Next Page » 2

App Gen
App Name:
Project Name:
List  Grid  Pager
Action Bar
Navigation Drawer
Dummy Data
Free Apps