Postcode Plus

Introduction

The AFD Postcode Plus for Android API is easy to use and quick to implement in any Android application, while balancing that with providing full flexibility. A JAR file (afdpcp.jar) alongside our native library (libafdpcp.so) provides access to Postcode Plus functionality once added to your project.

Getting Started

For rapid development and for a quick start, take a look at our sample program here to see how Postcode Plus is integrated. When you run that on Android you will need to copy your licence file to your chosen data folder on the device (unless using evaluation data). The data files (pcplus.afd, pcplusi.afd, etc.) will also need to be present either along with your application or on external storage. If file transfer is more difficult, you can simplify this by transfering the licence file using the SaveLicense method and obtain the latest data files automatically using the update functionality.

To integrate Postcode Plus into your own Project simply add the afdpcp.jar file to your project libs folder and the libafdpcp.so to libs\armeabi. Then create an instance of the afd.pcp.Engine class to access AFD Postcode Plus functionality.

On creating an instance of the afd.pcp.Engine class you should pass the path to access the product data files from, for example for application private storage:

				
					Engine pcpEngine = new afd.pcp.Engine(getFilesDir());
				
			

Or for an example of an external path:

				
					Engine pcpEngine = new afd.pcp.Engine(“/mnt/sdcard/pcpdata/”);
				
			

For non-evaluation purposes we recommend using the automatic update functionality to obtain the latest data files and using the saveLicense method to save the licence from a Base64 encoded string.

Using the Sample Application

A sample application demonstrating AFD Postcode Plus functionality is provided with the SDK.

To use this load the project in Eclipse and then click Run and follow any prompts to start the application on your device.

The path to the data folder is set in the top of the common.java and is displayed on the FastFind screen of the sample application. You may need to change this to point to an appropriate location for your target device.

For Evaluation data, copy that data to a folder on the device, or include it in your apk and ensure you have set the data path correctly as above.

For Full data, either transfer the nn.lic licence file to the device or use the saveLicense method to generate the file from a Base64 string that AFD will have supplied. Then use the checkForUpdates function to obtain the latest data.

How To…

Lookup or Search for Address Records

The addressGetFirst and addressGetNext methods enable address records to quickly be located.

This is typically done as follows:

  • Call the clear method to clear any previous search criteria
  • Set the appropriate search properties with the criteria to use. (e.g. setSearchLookup to specify a fast-find string to look for, e.g. a postcode)
  • Call addressGetFirst to retrieve the first matching record, specifying any required flags (see the function reference).
  • If addressGetFirst < 0 report an error, otherwise call addressGetNext repeatedly until AFD_END_OF_SEARCH is returned to return all matching records.
  • If the return value is AFD_SUCCESS, read the required properties from the record returned to obtain the required data. If the return value is AFD_RECORD_BREAK no new record data will be returned so continue to call AddressGetNext

See the appropriate function and property references for full details of these methods and properties.

An example lookup is as follows:

				
					// Create an instance of the afd.pcp.Engine class
Engine pcp Engine = new afd. pcp.Engine();
// Set the search criteria
pcpEngine.clear();
pcpEngine.setSearchLookup("B6 4AA");
// Do the lookup
int retVal = pcpEngine.addressGetFirst(0);
// Deal with any error
if (retVal < 0) {
 AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
 dlgAlert.setTitle("Error");
 dlgAlert.setMessage(pcpEngine.errorText(retVal));
 dlgAlert.create().show();
 return;
}
// Retrieve the results
while (retVal >= 0) {
 if (retVal != pcpEngine.AFD_RECORD_BREAK) {
String listItem = pcpEngine.getAddressList();
// do something with this data
 }
 retVal = pcpEngine.addressGetNext();
}
				
			

Retrieve Records

The jumpToRecord method enables records to be quickly retrieved again, (from a list displayed to the user, for example) using its record key.

This is typically done as follows:

  • Store the result of the getRecordKey function along with the item at the time of original retrieval.
  • Call jumpToRecord with key of the record to be retrieved
  • If jumpToRecord < 0 report an error
  • If the return value is AFD_SUCCESS, read the required properties from the record returned to obtain the required data.

See the appropriate function and property references for full details of this method and properties.

An example retrieve is as follows, where recordKey is the result of calling getRecordKey for the record originally retrieved:

				
					// Create an instance of the afd.pcp.Engine class
Engine pcp Engine = new afd.pcp.Engine();
// Do the lookup
int retVal = pcp Engine.jumpToRecord(recordKey);
// Deal with any error
if (retVal < 0) {
 AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
 dlgAlert.setTitle("Error");
 dlgAlert.setMessage(pcpEngine.errorText(retVal));
 dlgAlert.create().show();
 return;
}
// Retrieve the result
String organisation = pcpEngine.getOrganisation();
String property = pcpEngine.getProperty();
String street = pcpEngine.getStreet();
String locality = pcpEngine.getLocality();
String town = pcpEngine.getTown();
String postcode = pcpEngine.getPostcode();
// do something with this data
				
			

Saving the License File (Non-Evaluation Only)

To use full data with AFD Postcode Plus, a License will need to be purchased from AFD. This is provided in two forms, a file nn.lic and a Base64 encoded version to make entry or transfer easier.

Either save the pcplus.lic file in your data folder, or use the saveLicense method to pass the supplied base64 encoded text string to apply the license.

The process to do this is typically as follows:

  • Obtain the licence data, e.g. by user entry, a file you supply etc. (Do not hard-code this unless you can update your application each year with the new license details).
  • Call saveLicense supplying the licence string as a parameter, if this does not return 1 then the string was invalid.
  • Test Postcode Plus functionality to ensure the licence is valid.

An example of doing this is as follows:

				
					int applied = pcpEngine.saveLicense(licenseString);
if (applied == 1) {
// success
}
else {
// license string not valid
}
				
			

Updating Data Files (Non-Evaluation Only)

To update Postcode Plus data, the data files (pcplus.afd, pcplusi.afd, etc.) need to be replaced in your data folder with the latest versions available from our server.

This can be done automatically using instance functions of the afd.pcp.Engine class provided for updating.

The process to do this is typically as follows:

  • Call checkForUpdate, if this does not return 1 then no update is available so abort
  • When convenient call downloadUpdate to commence downloading the file. This function returns a response immediately so that you can continue using the software whilst the download progresses. If it returns 0 then no update is available, -1 indicates it couldn’t connect to the update server.
  • Check periodically by calling isDownloadComplete to determine if the download has completed, when it returns 1 the download has completed, <0 indicates an error downloading
  • Once downloaded call applyUpdate at an appropriate time to apply and load the new dataset.

An example of doing this is as follows:

				
					int needUpdate = afd.pcp.Engine.checkForUpdate();
if (needUpdate == 1) {
int startedDownload = afd. pcp.Engine.downloadUpdate();
if (startedDownload == 1) {
 while (afd. pcp.Engine.isDownloadComplete() == 0) {
 // wait for download to complete – can carry on with other
tasks
 }
 int updateApplied = afd.pcp.Engine.applyUpdate();
}
				
			

Function Reference

clear

Clears the search properties ready to start a new search

				
					public void clear();
				
			

This function takes no parameters and returns no value.

addressGetFirst

Starts a lookup or search and returns the first record

Prior to calling this function, call Clear and set the appropriate search parameters to specify the fields you wish to search for (e.g. setSearchLookup).

				
					public int addressGetFirst(int flags)
				
			

flags is an integer and specifies options for the search. These are as follows:

  • AFD_ALL_RECORDS – Return all records
  • AFD_POSTCODE_ONLY – Lookup Postcode Only
  • AFD_PROPERTY_ONLY – Lookup Postcode and Property

The function returns one of the following values:

  • AFD_SUCCESS – Successful lookup (result returned)
  • AFD_RECORD_BREAK – Search in progress call AddressGetNext to get the next result
  • AFD_INVALID_POSTCODE – Format of postcode supplied is invalid
  • AFD_NOT_FOUND – No matching records found
  • AFD_ERROR_OPENING_FILES – Error opening Postcode Plus data files
  • AFD_FILE_READ_ERROR – Error reading Postcode Plus data files
  • AFD_DATA_LICENSE_ERROR – Data Licence Error

If AFD_SUCCESS is returned you can then call any of the properties to obtain the fields for the returned record, e.g. getAddressList.

If AFD_SUCCESS or AFD_RECORD_BREAK is returned you should call addressGetNext to retrieve each subsequent record until AFD_END_OF_SEARCH is returned.

addressGetNext

Continues a lookup or search, returning the next matching record

				
					public int addressGetNext()
				
			

This function takes no parameters.

The function returns one of the following values:

  • AFD_SUCCESS – Successful lookup (result returned)
  • AFD_RECORD_BREAK – Search in progress call AddressGetNext to get the next result
  • AFD_END_OF_SEARCH – End of Search (no more records to return)
  • AFD_ERROR_OPENING_FILES – Error opening Postcode Plus data files
  • AFD_FILE_READ_ERROR – Error reading Postcode Plus data files
  • AFD_DATA_LICENSE_ERROR – Data Licence Error

If AFD_SUCCESS is returned you can then call any of the properties to obtain the fields for the returned record, e.g. getAddressList.

If AFD_SUCCESS or AFD_RECORD_BREAK is returned you should continue to call AddressGetNext to retrieve each subsequent record until AFD_END_OF_SEARCH is returned.

jumpToRecord

Returns data for the record key supplied

				
					public int jumpToRecord(String recordKey)
				
			

The recordKey parameter is the key of the record to be retrieved. This would have been returned by using the getRecordKey method following a previous call to AddressGetFirst or AddressGetNext. Note this key should not be stored as it is not maintained across data updates; it is designed for reretrieving a record following a list being provided to the user.

The function returns one of the following values:

  • AFD_SUCCESS – Successful lookup (result returned)
  • AFD_INVALID_RECORD – Key supplied was invalid
  • AFD_ERROR_OPENING_FILES – Error opening Postcode Plus data files
  • AFD_FILE_READ_ERROR – Error reading Postcode Plus data files
  • AFD_DATA_LICENSE_ERROR – Data Licence Error

If AFD_SUCCESS is returned, any of the properties can then be called to obtain the fields for the returned record, e.g. getStreet.

errorText

Used to retrieve text to display a friendly error message to go with an error code returned from the search or validation functions (return value less than zero).

				
					public String errorText(int errorCode)
				
			

errorCode is an int and should be set to the return value from a previous function call.

On return a description for the error is returned which can be stored or displayed for the user.

saveLicense

Used to save a license file on the device from a Base64 encoded string representation.

				
					public int saveLicense(string base64License)
				
			

Base64License is the string containing the base64 encoded license data.

Returns:

  • 0 Successfully applied license
  • -7 Data License Error (string is invalid)

checkForUpdate

Used to check if an update to the Postcode Plus data files is available.

				
					public int checkForUpdate()
				
			

Returns:

  • 1 Update Available
  • 0 No Update Available (already on latest data)
  • -1 Error getting data (normally Internet connection issue)
  • -7 Data License Error or Evaluation data present

downloadUpdate

Used to start downloading a data update.

				
					public int downloadUpdate()
				
			

Returns:

  • 1 Update started downloading
  • 0 No Update Available (already on latest data)
  • -1 Error getting data (normally connection issue)
  • -7 Data License Error or Evaluation data present

When the function returns data continues to download in the background so your application can continue running. Poll with IsDownloadComplete periodically to determine when the download has finished.

isDownloadComplete

Used to indicate when a data download has completed downloading

				
					public int isDownloadComplete()
				
			

Returns:

  • 1 Download Complete
  • 0 Download still in progress
  • -1 No download started
  • -2 Download failed (call DownloadUpdate to retry)

applyUpdate

Used to update data files following a successful download and loads the new dataset.

				
					public int applyUpdate()
				
			

Returns:

  • 1 Update Successful
  • 0 Download in progress or failed
  • -1 No update present to apply
  • -7 Data License Error or Evaluation data present

Note that you mustn’t call the Postcode Plus functions while this call is completing as old data will be unloaded, the new data unpacked and then loaded during this call. Hence this call does block the thread it is called on which is assumed to be the one you carry out Postcode Plus calls on.

Properties Reference

Getter methods are provided to set properties for searches and setter methods to get the resulting record details following a match. These are as follows:

Field NameDescription
Search Fields (Any of these can be set prior to a call to AddressGetFirst) 
setSearchLookupSpecify fast-find string to look for, e.g. a postcode or street, town. No other search fields should be set when this is used.
setSearchPostcodeFromSet Postcode to search from (range)
setSearchPostcodeToSet Postcode to search to (range)
setSearchOrganisationSet Organisation Name to search for
setSearchPropertySet Property or Building Name to search for
setSearchStreetSet Street Name to search for
setSearchLocalitySet Locality name to search for
setSearchTownSet Post Town to search for
setSearchCountySet County Name to search for (searches all county types)
setSearchSTDCodeSet Dialling Code to search for
setSearchGridESet Grid Easting to search around (for radial searches)
setSearchGridNSet Grid Northing to search around (for radial searches)
setSearchMilesSet distance in miles to search around (for radial searches)
setSearchKmSet distance in kilometres to search around
setSearchJustBuiltSet Just Built date to search for (in format YYYYMMDD)
setSearchUDPRNSet UDPRN to search for. No other search fields should be set when this is used.
Formatted Address Fields 
getRecordKeyReturns a record key to use for subsequent retrieval of the record with AddressRetrieve. Note this should not be stored as it does not persist across data updates.
getPostcodeReturns the Postcode
getPostcodeFromReturns the original postcode if the postcode searched for has been changed (re-coded).
getOrganisationReturns the Organisation Name
getPropertyReturns the Building Name
getStreetReturns the House Number and Street Name
getLocalityReturns the Locality Name
getTownReturns the Post Town for this address
getAddressListReturns a formatted line for list insertion containing elements of the Address record. Useful when displaying a list of results for the user to choose from.
Raw Address Fields (unformatted with house number in a separate field) 
getPAFDepartmentThe department name
getPAFOrganisationThe organisation name
getPAFSubBuildingThe sub building name
getPAFBuildingThe building name
getPAFNumberProperty number
getPAFPOBoxPO Box number
getPAFDepStreetThe dependent street name
getPAFStreetThe street name
getPAFDblDepLocThe double dependent locality name
getPAFDepLocThe dependent locality name
County Fields 
getCountyPostalPostal County (held by Royal Mail)
getCountyOptionalPostal Counties including optional ones (no longer held by Royal Mail)
getCountyAbbreivatedPostalPostal County, abbreviated were an official abbreviation exists
getCountyAbbreviatedOptionalOptional County, abbreviated were an official abbreviation exists
getCountyTraditionalTraditional County Name
getCountyAdministrativeAdministrative County Name
Additional Postal Fields 
getDPSThe Delivery Point Suffix which along with the postcode uniquely identifies the letterbox for this address.
getPostcodeFromReturns the original postcode if the postcode searched for has been changed (re-coded).
getPostcodeTypeL for Large User Postcode, S for Small User.
getMailsortCodeUsed for obtaining bulk mail discounts.
getUDPRNRoyal Mail Unique Delivery Point Reference Number assigned to this letter box.
getJustBuiltAFDJustBuilt – Contains the date of inclusion on PAF for properties thought to be recently built. The date is stored numerically in descending format in the form YYYYMMDD. YYYY is the year, MM is the month and DD is the day. For example 20080304 is 04/03/2008.
getHouseholdsNumber of households behind the delivery point
Geographical Fields 
getGridEGrid Easting as a 6 digit reference
getGridNGrid Northing as a 6/7 digit reference
getLatitudeLatitude representation of Grid Reference in Decimal Format (WGS84)
getLongitudeLongitude representation of Grid Reference in Decimal
Format (WGS84)getUrbanRuralCode Provides a code which indicates if an area is mainly urban or rural and how sparsely populated those area’s are. [3]
getUrbanRuralNameProvides a description which goes along with the UrbanRuralCode. [3]
getSOALowerLower level Super Output Area (Data Zone in Scotland, Super Output Area in Northern Ireland)
getSOAMiddleMiddle level Super Output Area (Intermediate Geography in Scotland, not applicable for Northern Ireland).
getSubCountryNameIndicates if the postcode falls within the boundary of England, Wales, Scotland, Northern Ireland, Isle of Man, Jersey or Guernsey
Phone Related 
getSTDCodeReturns an indication of the most likely Standard Dialing Code for this postcode
Administrative Fields 
getWardCodeCode identifying the electoral ward for this postcode
getWardNameName identifying the electoral ward for this postcode
getAuthorityCodeLocal/Unitary Authority for this Postcode (same as the start of the ward code).
getAuthorityNameLocal / Unitary Authority for this postcode
getConstituencyCodeCode for the Parliamentary Constituency for this postcode
getConstituencyNameName of the Parliamentary Constituency for this postcode
getDevolvedConstituencyCodeCode for the Scottish Parliamentary Constituency for this postcode (if applicable)
getDevolvedConstituencyNameName of the Scottish Parliamentary Constituency for this postcode (if applicable)
getEERCodeCode identifying the European Electoral Region for this postcode
getEERNameName identifying the European Electoral Region for this postcode
getLEACodeCode identifying the Local Education Authority for this postcode
getLEANameName identifying the Local Education Authority for this postcode
getTVRegionISBA TV Region (not TV Company)
Postcode Level Property Indicator Fields 
getOccupancyIndication of the type of occupants of properties found on the selected postcode [1]
getAddressTypeIndication of the type of property level data to capture to have the full address for a property on the selected postcode. [2]
NHS Fields 
getCCGCodeClinical Commissioning Group Code (Local Health Board Code in Wales, Community Health Partnership in Scotland, and Health and Social Services Boards in Northern Ireland)
getCCGNameName matching the CCG Code field
getSHACodeStrategic Health Authority Code
getSHANameStrategic Health Authority Name
getNHSRegionCodeNational Health Service Region Code
getNHSRegionNameNational Health Service Region Name
Censation Fields 
getCensationCodeCensation Code assigned to this Postcode
getCensationLabelLabel for this Censation group for ease of identification and reference.
getAffluenceAffluence description
getLifeStageLifeStage description
getAdditionalCensusInfoAdditional information derived from the Census.

Notes:

[1] Possible Occupancy values and descriptions are as follows (information in brackets not part of the description):

  • Large User Organisation (Single Organisation on this postcode)
  • Small User Organisation (All the properties on this postcode are likely to be businesses)
  • Mostly Organisations (Most of the properties on this postcode are organisations)
  • Mixed (This postcode contains a mixture of business and residential addresses)
  • Mostly Residential (Most of the properties on this postcode are residential)
  • Residential (All the properties on this postcode are likely to be residential)

[2] Possible Address Type values and descriptions are as follows (information in brackets not part of the description):

  • Numbered (Only a property number needs to be captured)
  • Numbered and Named (This postcode contains a mixture of properties needing a property number and those needing a property name including properties such as 16b)
  • Numbered and Named, Likelihood of Multiple Occupancy (This postcode contains a mixture of properties needing a property number and those needing a property name. Some of the properties on this postcode are likely to contain multiple occupants, e.g. flats).
  • Named (This postcode only contains properties needing a property name).
  • Non-Standard Address Format (This refers to addresses which do not have a street field at all, or have multiple street names on the same postcode. This also includes addresses with numbered localities (no street but a house number which goes in with the locality field). It is in-effect a warning to be careful in capturing the property information as it is not in one of the most common address formats).
  • PO Box (This postcode has a PO Box number)
  • No Property Information (Addresses on this postcode have no property information – i.e. capture an Organisation or Resident name only)

[3] The Urban Rural Code differs from England and Wales, Scotland and Northern Ireland. The possible codes and there meanings are as follows:

England & Wales

  • Urban (Sparse): Falls within Urban settlements with a population of 10,000 or more and the wider surrounding area is sparsely populated
  • Town and Fringe (Sparse): Falls within the Small Town and Fringe areas category and the wider surrounding area is sparsely populated.
  • Village (Sparse): Falls within the Village category and the wider surrounding area is sparsely populated.
  • Hamlet and Isolated Dwelling (Sparse): Falls within the Hamlet and Isolated Dwelling category and thee wider surrounding area is sparsely populated.
  • Urban (Less Sparse): Falls within urban settlements with a population of 10,000 or more and the wider surrounding area is less sparsely populated.
  • Town and Fringe (Less Sparse): Falls within the Small Town and Fringe areas category and the wider surrounding area is less sparsely populated.
  • Village (Less Sparse): Falls within the village category and the wider surrounding area is less sparsely populated.
  • Hamlet and Isolated Dwelling (Less Sparse): Falls within the Hamlet & Isolated Dwelling category and the wider surrounding area is less sparsely populated

Scotland

  • S1. Large Urban Area: Settlement of over 125,000 people.
  • S2. Other Urban Area: Settlement of 10,000 to 125,000 people.
  • S3. Accessible Small Town: Settlement of 3,000 to 10,000 people, within 30 minutes drive of a settlement of 10,000 or more.
  • S4. Remote Small Town: Settlement of 3,000 to 10,000 people, with a drive time of 30 to 60 minutes to a settlement of 10,000 or more.
  • S5. Very Remote Small Town: Settlement of 3,000 to 10,000 people, with a drive time of over 60 minutes to a settlement of 10,000 or more.
  • S6. Accessible Rural: Settlement of less than 3,000 people, within 30 minutes’ drive of a settlement of 10,000 or more.
  • S7. Remote Rural: Settlement of less than 3,000 people, with a drive time of 30 to 60 minutes to a settlement of 10,000 or more.
  • S8. Very Remote Rural: Settlement of less than 3,000 people, with a drive time of over 60 minutes to a settlement of 10,000 or more.

Northern Ireland

A – E (Urban):

  • A. Belfast Metropolitan Urban Area
  • B. Derry Urban Area
  • C. Large Town: 18,000 and under 75,000 people
  • D. Medium Town: 10,000 and under 18,000 people
  • E. Small Town: 4,500 and under 10,000 people

F – H (Rural):

  • F. Intermediate Settlement: 2,250 and under 4,500 people
  • G. Village: 1,000 and under 2,250 people
  • H. Small Village, Hamlet or Open Countryside: Less than 1,000

Names and Numbers

Introduction

The AFD Names & Numbers for Android API is easy to use and quick to implement in any Android application, while balancing that with providing full flexibility. A JAR file (afdnn.jar) alongside our native library (libafdnn.so) provides access to Names & Numbers functionality once added to your project.

Getting Started

For rapid development and for a quick start, take a look at our sample program here to see how Names & Numbers is integrated. When you run that on Android you will need to copy your licence file to your chosen data folder on the device (unless using evaluation data). The data files (names.afd, namesi.afd, etc.) will also need to be present either along with your application or on external storage. If file transfer is more difficult, you can simplify this by transfering the licence file using the SaveLicense method and obtain the latest data files automatically using the update functionality.

To integrate Names & Numbers into your own Project, simply add the afdnn.jar file to your project libs folder and the libafdnn.so to libs\armeabi. Then create an instance of the afd.nn.Engine class to access AFD Names & Numbers functionality.

On creating an instance of the afd.nn.Engine class you should pass the path to access the product data files from, for example for application private storage:

				
					Engine nnEngine = new afd.nn.Engine(getFilesDir());
				
			

Or for an example of an external path:

				
					Engine nnEngine = new afd.nn.Engine(“/mnt/sdcard/nndata/”);
				
			

For non-evaluation purposes we recommend using the automatic update functionality to obtain the latest data files and using the saveLicense method to save the licence from a Base64 encoded string.

Using the Sample Application

A sample application demonstrating AFD Names & Numbers functionality is provided with the SDK.

To use this load the project in Eclipse and then click Run and follow any prompts to start the application on your device.

The path to the data folder is set in the top of the common.java and is displayed on the FastFind screen of the sample application. You may need to change this to point to an appropriate location for your target device.

For Evaluation data, copy that data to a folder on the device, or include it in your apk and ensure you have set the data path correctly as above.

For Full data, either transfer the nn.lic licence file to the device or use the saveLicense method to generate the file from a Base64 string that AFD will have supplied. Then use the checkForUpdates function to obtain the latest data.

‘How To’ Guide

Lookup or Search for Address Records

The addressGetFirst and addressGetNext methods enable address records to quickly be located.

This is typically done as follows:

  • Call the clear method to clear any previous search criteria
  • Set the appropriate search properties with the criteria to use. (e.g. setSearchLookup to specify a fast-find string to look for, e.g. a postcode)
  • Call addressGetFirst to retrieve the first matching record, specifying any required flags (see the function reference).
  • If addressGetFirst < 0 report an error, otherwise call addressGetNext repeatedly until AFD_END_OF_SEARCH is returned to return all matching records.
  • If the return value is AFD_SUCCESS, read the required properties from the record returned to obtain the required data. If the return value is AFD_RECORD_BREAK no new record data will be returned so continue to call AddressGetNext

See the appropriate function and property references for full details of these methods and properties.

An example lookup is as follows:

				
					// Create an instance of the afd.nn.Engine class
Engine nnEngine = new afd.nn.Engine();
// Set the search criteria
nnEngine.clear();
nnEngine.setSearchLookup("B6 4AA");
// Do the lookup
int retVal = nnEngine.addressGetFirst(0);
// Deal with any error
if (retVal < 0) {
 AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
 dlgAlert.setTitle("Error");
 dlgAlert.setMessage(nnEngine.errorText(retVal));
 dlgAlert.create().show();
 return;
}
// Retrieve the results
while (retVal >= 0) {
 if (retVal != nnEngine.AFD_RECORD_BREAK) {
String listItem = nnEngine.getAddressList();
// do something with this data
 }
 retVal = nnEngine.addressGetNext();
				
			

Retrieve Record

The jumpToRecord method enables records to be quickly retrieved again, (from a list displayed to the user, for example) using its record key.

This is typically done as follows:

  • Store the result of the getRecordKey function along with the item at the time of original retrieval.
  • Call jumpToRecord with key of the record to be retrieved
  • If jumpToRecord < 0 report an error
  • If the return value is AFD_SUCCESS, read the required properties from the record returned to obtain the required data.

See the appropriate function and property references for full details of this method and properties.

An example retrieve is as follows, were recordKey is the result of calling getRecordKey for the record originally retrieved:

				
					// Create an instance of the afd.nn.Engine class
Engine nnEngine = new afd.nn.Engine();
// Do the lookup
int retVal = nnEngine.jumpToRecord(recordKey);
// Deal with any error
if (retVal < 0) {
 AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
 dlgAlert.setTitle("Error");
 dlgAlert.setMessage(nnEngine.errorText(retVal));
 dlgAlert.create().show();
 return;
}
// Retrieve the result
String organisation = nnEngine.getOrganisation();
String property = nnEngine.getProperty();
String street = nnEngine.getStreet();
String locality = nnEngine.getLocality();
String town = nnEngine.getTown();
String postcode = nnEngine.getPostcode();
// do something with this data
				
			

Saving the License File (Non-Evaluation Only)

To use full data with AFD Names & Numbers, a License will need to be purchased from AFD. This is provided in two forms, a file nn.lic and a Base64 encoded version to make entry or transfer easier.

Either save the nn.lic file in your data folder, or use the saveLicense method to pass the supplied base64 encoded text string to apply the license.

The process to do this is typically as follows:

  • Obtain the licence data, e.g. by user entry, a file you supply etc. (Do not hard-code this unless you can update your application each year with the new license details).
  • Call saveLicense supplying the licence string as a parameter, if this does not return 1 then the string was invalid.
  • Test Names & Numbers functionality to ensure the licence is valid.

An example of doing this is as follows:

				
					int applied = nnEngine.saveLicense(licenseString);
if (applied == 1) {
// success
}
else {
// license string not valid
}
				
			

Updating Data Files (Non-Evaluation Only)

To update Names & Numbers data, the data files (names.afd, namesi.afd, etc.) need to be replaced in your data folder with the latest versions available from our server.

This can be done automatically using instance functions of the afd.nn.Engine class provided for updating.

The process to do this is typically as follows:

  • Call checkForUpdate, if this does not return 1 then no update is available so abort
  • When convenient call downloadUpdate to commence downloading thefile. This function returns a response immediately so that you can continue using the software whilst the download progresses. If it returns 0 then no update is available, -1 indicates it couldn’t connect to the update server.
  • Check periodically by calling isDownloadComplete to determine if the download has completed, when it returns 1 the download has completed, <0 indicates an error downloading
  • Once downloaded call applyUpdate at an appropriate time to apply and load the new dataset.

An example of doing this is as follows:

				
					int needUpdate = afd.nn.Engine.checkForUpdate();
if (needUpdate == 1) {
int startedDownload = afd.nn.Engine.downloadUpdate();
if (startedDownload == 1) {
 while (afd.nn.Engine.isDownloadComplete() == 0) {
 // wait for download to complete – can carry on with other
tasks
 }
 int updateApplied = afd.nn.Engine.applyUpdate();
}
				
			

Function Reference

clear

Clears the search properties ready to start a new search public void clear();

This function takes no parameters and returns no value.

addressGetFirst

Starts a lookup or search and returns the first record

Prior to calling this function, call Clear and set the appropriate search parameters to specify the fields you wish to search for (e.g. setSearchLookup).

public int addressGetFirst(int flags)

flags is an integer and specifies options for the search. These are as follows:

  • AFD_ALL_RECORDS – Return all records
  • AFD_POSTCODE_ONLY – Lookup Postcode Only
  • AFD_PROPERTY_ONLY – Lookup Postcode and Property

The function returns one of the following values:

  • AFD_SUCCESS – Successful lookup (result returned)
  • AFD_RECORD_BREAK – Search in progress call AddressGetNext to get the next result
  • AFD_INVALID_POSTCODE – Format of postcode supplied is invalid
  • AFD_NOT_FOUND – No matching records found
  • AFD_ERROR_OPENING_FILES – Error opening Postcode Plus data files
  • AFD_FILE_READ_ERROR – Error reading Postcode Plus data files
  • AFD_DATA_LICENSE_ERROR – Data Licence Error

If AFD_SUCCESS is returned you can then call any of the properties to obtain the fields for the returned record, e.g. getAddressList. If AFD_SUCCESS or AFD_RECORD_BREAK is returned you should call addressGetNext to retrieve each subsequent record until AFD_END_OF_SEARCH is returned.

addressGetNext

Continues a lookup or search, returning the next matching record

				
					public int addressGetNext()
				
			

This function takes no parameters.

The function returns one of the following values:

  • AFD_SUCCESS – Successful lookup (result returned)
  • AFD_RECORD_BREAK – Search in progress call AddressGetNext to get the next result
  • AFD_END_OF_SEARCH – End of Search (no more records to return)
  • AFD_ERROR_OPENING_FILES – Error opening Postcode Plus data files
  • AFD_FILE_READ_ERROR – Error reading Postcode Plus data files
  • AFD_DATA_LICENSE_ERROR – Data Licence Error

If AFD_SUCCESS is returned you can then call any of the properties to obtain the fields for the returned record, e.g. getAddressList.

If AFD_SUCCESS or AFD_RECORD_BREAK is returned you should continue to call AddressGetNext to retrieve each subsequent record until AFD_END_OF_SEARCH is returned.

jumpToRecord

Returns data for the record key supplied

				
					public int jumpToRecord(String recordKey)
				
			

The recordKey parameter is the key of the record to be retrieved. This would have been returned by using the getRecordKey method following a previous call to AddressGetFirst or AddressGetNext. Note this key should not be stored as it is not maintained across data updates; it is designed for reretrievinga record following a list being provided to the user.

The function returns one of the following values:

  • AFD_SUCCESS – Successful lookup (result returned)
  • AFD_INVALID_RECORD – Key supplied was invalid
  • AFD_ERROR_OPENING_FILES – Error opening Postcode Plus data files
  • AFD_FILE_READ_ERROR – Error reading Postcode Plus data files
  • AFD_DATA_LICENSE_ERROR – Data Licence Error

If AFD_SUCCESS is returned, any of the properties can then be called to obtain the fields for the returned record, e.g. getStreet.

errorText

Used to retrieve text to display a friendly error message to go with an error code returned from the search or validation functions (return value less than zero).

				
					public String errorText(int errorCode)
				
			

errorCode is an int and should be set to the return value from a previous function call.

On return a description for the error is returned which can be stored or displayed for the user.

saveLicense

Used to save a license file on the device from a Base64 encoded string representation.

				
					public int saveLicense(string base64License)
				
			

Base64License is the string containing the base64 encoded license data.

Returns:

  • 0 Successfully applied license
  • -7 Data License Error (string is invalid)

checkForUpdate

Used to check if an update to the Names & Numbers data files is available.

				
					public int checkForUpdate()
				
			

Returns:

  • 1 Update Available
  • 0 No Update Available (already on latest data)
  • -1 Error getting data (normally Internet connection issue)
  • -7 Data License Error or Evaluation data present

downloadUpdate

Used to start downloading a data update.

public int downloadUpdate()

Returns:

  • 1 Update started downloading
  • 0 No Update Available (already on latest data)
  • -1 Error getting data (normally connection issue)
  • -7 Data License Error or Evaluation data present

When the function returns data continues to download in the background so your application can continue running. Poll with IsDownloadComplete periodically to determine when the download has finished.

isDownloadComplete

Used to indicate when a data download has completed downloading public int isDownloadComplete()

Returns:

  • 1 Download Complete
  • 0 Download still in progress
  • -1 No download started
  • -2 Download failed (call DownloadUpdate to retry)

applyUpdate

Used to update data files following a successful download and loads the new dataset.

				
					public int applyUpdate()
				
			

Returns:

  • 1 Update Successful
  • 0 Download in progress or failed
  • -1 No update present to apply
  • -7 Data License Error or Evaluation data present

Note that you mustn’t call the Names & Numbers functions while this call is completing as old data will be unloaded, the new data unpacked and then loaded during this call. Hence this call does block the thread it is called on which is assumed to be the one you carry out Names & Numbers calls on.

Properties Reference

Getter and setter methods are provided for the Names & Numbers fields.

These are as follows:

Field NameDescription
Searchable Only Fields (no get method) 
SearchLookupSpecify fast-find string to look for, e.g. a postcode or street, town. No other search fields should be set when this is used.
MilesSet distance in miles to search around (for radial searches)
KmSet distance in kilometres to search around
Result Only Fields (no set method) 
AddressListReturns a formatted line for list insertion containing elements of the Address record. Useful when displaying a list of results for the user to choose from.
RecordKeyReturns a record key to use for subsequent retrieval of the record with AddressRetrieve. Note this should not be stored as it does not persist across data updates.
NameReturns a formatted Name with title, e.g. “Mr John J Smith”
Formatted Address Fields 
PostcodeReturns the Postcode
PostcodeFromReturns the original postcode if the postcode searched for has been changed (re-coded).
OrganisationReturns the Organisation Name
PropertyReturns the Building Name
StreetReturns the House Number and Street Name
LocalityReturns the Locality Name
TownReturns the Post Town for this address
Raw Address Fields (unformatted with house number in a separate field) 
PAFSubBuildingThe sub building name
PAFBuildingThe building name
PAFNumberProperty number
PAFStreetThe street name
PAFLocalityThe locality name
County Fields 
CountyPostalPostal County (held, or formally held by Royal Mail)
CountyTraditionalTraditional County Name
CountyAdministrativeAdministrative County Name
Additional Postal Fields 
DPSPostal County (held by Royal Mail)
PostcodeTypeL for Large User Postcode, S for Small User.
MailsortCodeUsed for obtaining bulk mail discounts.
UDPRNRoyal Mail Unique Delivery Point Reference Number assigned to this letter box.
JustBuiltAFDJustBuilt – Contains the date of inclusion on PAF for properties thought to be recently built. The date is stored numerically in descending format in the form YYYYMMDD. YYYY is the year, MM is the month and DD is the day. For example 20080304 is 04/03/2008.
Name Fields 
GenderThe gender (M or F) of the resident if known.
ForenameThe first name of the resident
MiddleInitialThe middle initiate of the resident.
SurnameThe surname/last name of the resident.
OnEditedRollIndicates if the resident is on the edited electoral roll (i.e. they have not opted out). Set to Y if the are on the Edited Roll, N if not, blank for Organisation and other records). To search set to #Y to return only records on the electoral roll, #N only for those not on the electoral roll or !N for all records including Organisations but excluding those not on the Edited Roll.
DateOfBirthThe residents date of birth if known (electoral roll attainers in the last 10 years only).
ResidencyGives time in years that the occupant has lived at this address.
HouseholdCompositionDescribes the household composition of the selected address[4]
**Additional OrganisationInformation Fields**
BusinessProvides a description of the type of business
SICCodeStandard Industry Classification Code for an organisation record.
SizeGives an indication of the number of employees of an organisation. [5]
Phone Number Related Fields 
PhonePhone Number
Geographical Fields 
GridEGrid Easting as a 6 digit reference
GridNGrid Northing as a 6/7 digit reference
LatitudeLatitude representation of Grid Reference in Decimal Format (WGS84)
LongitudeLongitude representation of Grid Reference in Decimal Format (WGS84)
UrbanRuralCodeProvides a code which indicates if an area is mainly urban or rural and how sparsely populated those area’s are. [3]
UrbanRuralNameProvides a description which goes along with the UrbanRuralCode. [3]
Administrative Fields 
WardCodeCode identifying the electoral ward for this postcode
WardNameName identifying the electoral ward for this postcode
AuthorityCodeLocal/Unitary Authority for this Postcode (same as the start of the ward code).
AuthorityNameLocal / Unitary Authority for this postcode
ConstituencyCodeCode for the Parliamentary Constituency for this postcode
ConstituencyNameName of the Parliamentary Constituency for this postcode
EERCodeCode identifying the European Electoral Region for this postcode
EERNameName identifying the European Electoral Region for this postcode
LEACodeCode identifying the Local Education Authority for this postcode
LEANameName identifying the Local Education Authority for this postcode
TVRegionISBA TV Region (not TV Company)
Postcode Level Property Indicator Fields 
OccupancyIndication of the type of occupants of properties found on the selected postcode [1]
AddressTypeIndication of the type of property level data to capture to have the full address for a property on the selected postcode. [2]
NHS FieldsNHSCode National Health Service Area Code
NHSNameNational Health Service Area Name
NHSRegionCodeNational Health Service Region Code
NHSRegionNameNational Health Service Region Name
PCTCodeNational Health Service Primary Care Trust Code for England (Local Health Board Code in Wales, Community Health Partnership in Scotland)
PCTNameName matching the PCT Code field
Censation Fields 
CensationCodeCensation Code assigned to this Postcode
AffluenceAffluence description
LifeStageLifeStage description
AdditionalCensusInfoAdditional information derived from the Census.

Notes

[1] Possible Occupancy values and descriptions are as follows (information in brackets not part of the description):

  • Large User Organisation (Single Organisation on this postcode)
  • Small User Organisation (All the properties on this postcode are likely to be businesses)
  • Mostly Organisations (Most of the properties on this postcode are organisations)
  • Mixed (This postcode contains a mixture of business and residential addresses)
  • Mostly Residential (Most of the properties on this postcode are residential)
  • Residential (All the properties on this postcode are likely to be residential)

[2] Possible Address Type values and descriptions are as follows (information in brackets not part of the description):

  • Numbered (Only a property number needs to be captured)
  • Numbered and Named (This postcode contains a mixture of properties needing a property number and those needing a property name including properties such as 16b)
  • Numbered and Named, Likelihood of Multiple Occupancy (This postcode contains a mixture of properties needing a property number and those needing a property name. Some of the properties on this postcode are likely to contain multiple occupants, e.g. flats).
  • Named (This postcode only contains properties needing a property name).
  • Non-Standard Address Format (This refers to addresses which do not have a street field at all, or have multiple street names on the same postcode. This also includes addresses with numbered localities (no street but a house number which goes in with the locality field). It is in-effect a warning to be careful in capturing the property information as it is not in one of the most common address formats).
  • PO Box (This postcode has a PO Box number)
  • No Property Information (Addresses on this postcode have no property information – i.e. capture an Organisation or Resident name only)

[3] The Urban Rural Code differs from England and Wales, Scotland and Northern Ireland. The possible codes and there meanings are as follows:

England & Wales

  • Urban (Sparse): Falls within Urban settlements with a population of 10,000 or more and the wider surrounding area is sparsely populated
  • Town and Fringe (Sparse): Falls within the Small Town and Fringe areas category and the wider surrounding area is sparsely populated.
  • Village (Sparse): Falls within the Village category and the wider surrounding area is sparsely populated.
  • Hamlet and Isolated Dwelling (Sparse): Falls within the Hamlet and Isolated Dwelling category and thee wider surrounding area is sparsely populated.
  • Urban (Less Sparse): Falls within urban settlements with a population of 10,000 or more and the wider surrounding area is less sparsely populated.
  • Town and Fringe (Less Sparse): Falls within the Small Town and Fringe areas category and the wider surrounding area is less sparsely populated.
  • Village (Less Sparse): Falls within the village category and the wider surrounding area is less sparsely populated.
  • Hamlet and Isolated Dwelling (Less Sparse): Falls within the Hamlet & Isolated Dwelling category and the wider surrounding area is less sparsely populated.

Scotland

  • S1. Large Urban Area: Settlement of over 125,000 people.
  • S2. Other Urban Area: Settlement of 10,000 to 125,000 people.
  • S3. Accessible Small Town: Settlement of 3,000 to 10,000 people, within 30 minutes drive of a settlement of 10,000 or more.
  • S4. Remote Small Town: Settlement of 3,000 to 10,000 people, with a drive time of 30 to 60 minutes to a settlement of 10,000 or more.
  • S5. Very Remote Small Town: Settlement of 3,000 to 10,000 people, with a drive time of over 60 minutes to a settlement of 10,000 or more.
  • S6. Accessible Rural: Settlement of less than 3,000 people, within 30 minutes’ drive of a settlement of 10,000 or more.
  • S7. Remote Rural: Settlement of less than 3,000 people, with a drive time of 30 to 60 minutes to a settlement of 10,000 or more.
  • S8. Very Remote Rural: Settlement of less than 3,000 people, with a drive time of over 60 minutes to a settlement of 10,000 or more.

Northern Ireland

  • A – E (Urban):
    • A. Belfast Metropolitan Urban Area
    • B. Derry Urban Area
    • C. Large Town: 18,000 and under 75,000 people
    • D. Medium Town: 10,000 and under 18,000 people
    • E. Small Town: 4,500 and under 10,000 people
  • F – H (Rural):
    • F. Intermediate Settlement: 2,250 and under 4,500 people
    • G. Village: 1,000 and under 2,250 people
    • H. Small Village, Hamlet or Open Countryside: Less than 1,000

[4] The household composition field includes both a number and description and can have any of the following values.

  • 1. 1 Male and 1 Female occupant with different surnames
  • 2. 1 Male and 1 Female occupant with the same surname (married couples)
  • 3. Mixed household
  • 4. More than 2 persons with the same surname (e.g. older families).
  • 5. 1 Male Occupant Only
  • 6. 1 Female Occupant Only
  • 7. More than 7 persons (e.g. old peoples home).

[5] The Size property can have any of the following values:

  • A. 1 to 9 employees
  • B. 10 to 19 employees
  • C. 20 to 49 employees
  • D. 50 to 99 employees
  • E. 100 to 199 employees
  • F. 200 to 499 employees
  • G. 500 to 999 employees
  • H. 1000+

(If blank, then this is unknown or not applicable).

BankFinder

Introduction

The AFD BankFinder for Android API is easy to use and quick to implement in any Objective C application, while balancing that with providing full flexibility.

A JAR file (afdbank.jar) alongside our native library (libafdbank.so) provides access to BankFinder functionality once added to your project.

Getting Started

For rapid development and for a quick start, take a look at our sample program here to see how BankFinder is integrated. When you run that on Android you will need to copy your licence file to your chosen data folder on the device (unless using evaluation data). The data files (bacs.afd and bacsi.afd) will also need to be present either along with your application or on external storage. If file transfer is more difficult, you can simplify this by transfering the licence file using the SaveLicense method and obtain the latest data files automatically using the update functionality.

To integrate BankFinder into your own Project simply add the afdbank.jar file to your project libs folder and the libafdbank.so to libs\armeabi. Then create an instance of the afd.bf.Engine class to access AFD BankFinder functionality.

On creating an instance of the afd.bf.Engine class you should pass the path to access the product data files from, for example for application private storage:

				
					Engine bfEngine = new afd.bf.Engine(getFilesDir());
				
			

Or for an example of an external path:

Engine bfEngine = new afd.bf.Engine(“/mnt/sdcard/bfdata/”);

For non-evaluation purposes we recommend using the automatic update functionality to obtain the latest data files and using the saveLicense method to save the licence from a Base64 encoded string.

Using the Sample Application

A sample application demonstrating AFD BankFinder functionality is provided with the SDK.

To use this load the project in Eclipse and then click Run and follow any prompts to start the application on your device.

The path to the data folder is set in the top of the common.java and is displayed on the FastFind screen of the sample application. You may need to change this to point to an appropriate location for your target device.

For Evaluation data, copy that data to a folder on the device, or include it in your apk and ensure you have set the data path correctly as above.

For Full data, either transfer the afdbank.lic licence file to the device or use the saveLicense method to generate the file from a Base64 string that AFD will have supplied. Then use the checkForUpdates function to obtain the latest data.

How To…

Lookup or Search for Bank Records

The bankGetFirst and bankGetNext methods allow bank records to quickly be located.

This is typically done as follows:

  • Call the clear method to clear any previous search criteria
  • Set the appropriate search properties with the criteria to use. (e.g. setSearchLookup to specify a fast-find string to look for, e.g. a sort code)
  • Call bankGetFirst to retrieve the first matching record, specifying the clearing system you wish to use (e.g. AFD_ALL_RECORDS or AFD_UK_ONLY).
  • If bankGetFirst < 0 report an error, otherwise call bankGetNext repeatedly until END_OF_SEARCH is returned to return all matching records.
  • If the return value is SUCCESS, read the required properties from the record returned to obtain the required data. If the return value is RECORD_BREAK no new record data will be returned so continue to call bankGetNext

See the appropriate function and property references for full details of these methods and properties.

An example lookup is as follows:

				
					// Create an instance of the afd.bf.Engine class
Engine bfEngine = new afd.bf.Engine();
// Set the search criteria
bfEngine.clear();
bfEngine.setSearchLookup("560035");
// Do the lookup
int retVal = bfEngine.bankGetFirst(bfEngine.AFD_ALL_RECORDS);
// Deal with any error
if (retVal < 0) {
 AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
 dlgAlert.setTitle("Error");
 dlgAlert.setMessage(bfEngine.errorText(retVal));
 dlgAlert.create().show();
 return;
}
// Retrieve the results
while (retVal >= 0) {
 if (retVal != bfEngine.AFD_RECORD_BREAK) {
String listItem = bfEngine.getListItem();
// do something with this data
 }

retVal = bfEngine.addressGetNext(); 
}
				
			

Retrieve Record

The jumpToRecord method enables records to be quickly retrieved again (from a list displayed to the user, for example) using its record key. This is typically done as follows:

  • Store the result of the getRecordKey function along with the item at the time of original retrieval.
  • Call jumpToRecord with key of the record you wish to retrieve
  • If JumpToRecord < 0 report an error
  • If the return value is AFD_SUCCESS, read the required properties from the record returned to obtain the required data.

See the appropriate function and property references for full details of this method and properties.

An example retrieve is as follows, where recordKey is the result of calling getRecordKey for the record you originally retrieved:

				
					// Create an instance of the afd.nn.Engine class
Engine bfEngine = new afd.bf.Engine();
// Do the lookup
int retVal = bfEngine.jumpToRecord(recordKey);
// Deal with any error
if (retVal < 0) {
 AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
 dlgAlert.setTitle("Error");
 dlgAlert.setMessage(bfEngine.errorText(retVal));
 dlgAlert.create().show();
 return;
}
// Retrieve the result
String bankName = bfEngine.getBankOwnerBankFullName();
String branchTitle = bfEngine.getBankFullBranchTitle();
String sortCode = bfEngine.getBankSortCode();
// do something with this data
				
			

Validate Account Details

The ValidateAccount method enables bank account details to be validated.

This is typically done as follows:

  • Call the ValidateAccount with the account number and sort code to be validated.
  • If ValidateAccount returns < 0 report an error, otherwise report success

See the ValidateAccount reference for full details of this method.

An example account validation is as follows:

				
					// Create an instance of the afd.bf.Engine class
Engine bfEngine = new afd.bf.Engine();
// define variables to pass to the validateAccount function
int flags = 0;
String sortCode= "774814";
String accountNo = "24782346";
String typeOfAccountCode = "";
String rollNumber = "";
String needRollNumber = "";
String iban = "";
String countryName = "";
// Do the validation
int retVal = bfEngine.validateAccount(flags, sortCode, accountNo,
typeOfAccountCode, rollNumber, needRollNumber, iban, countryName);
/* Display the result – note that the sortcode and account number may
have been updated if account translation was necessary (e.g. a nonstandard
length account number was supplied) */
if (retVal >= 0) {
 AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
 dlgAlert.setTitle("Account Details Validated");
 dlgAlert.setMessage("Account Number Valid");
 dlgAlert.create().show();
}
else {
 AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
 dlgAlert.setTitle("Error");
 dlgAlert.setMessage(bfEngine.errorText(retVal));
 dlgAlert.create().show();
 return;
}
				
			

Validate Card Number

The validateCard method enables card numbers to be validated.

This is typically done as follows:

  • Call validateCard with the card number (and optionally expiry date) to be validated.
  • If validateCard returns < 0 report an error, otherwise report the card type

See the validateCard reference for full details of this method.

An example card validation is as follows:

				
					// Create an instance of the afd.bf.Engine class
Engine bfEngine = new afd.bf.Engine();
// define variables to pass to the validateAccount function
int revisionID = 2; // for future proofing
String cardNumber="4903005748392742";
String expiryDate = "";
// Do the validation
int retVal = bfEngine.validateCard(revisionID, cardNumber,
expiryDate);
/* Display the result */
if (retVal >= 0) {
 AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
 dlgAlert.setTitle("Card Details Validated");
 dlgAlert.setMessage(bfEngine.cardType(retVal));
 dlgAlert.create().show();
}
else {
 AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
 dlgAlert.setTitle("Error");
 dlgAlert.setMessage(bfEngine.errorText(retVal));
 dlgAlert.create().show();
 return;
}
				
			

Saving the License File (Non-Evaluation Only)

To use full data with AFD BankFinder, a License will need to be purchased from AFD. This is provided in two forms, a file afdbank.lic and a Base64 encoded version to make entry or transfer easier.

Either save the afdbank.lic file in your data folder, or use the saveLicense method to pass the supplied base64 encoded text string to apply the license.

The process to do this is typically as follows:

  • Obtain the licence data, e.g. by user entry, a file you supply etc. (Do not hard-code this unless you can update your application each year with the new license details).
  • Call saveLicense supplying the licence string as a parameter, if this does not return 1 then the string was invalid.
  • Test BankFinder functionality to ensure the licence is valid.

An example of doing this is as follows:

				
					int applied = bfEngine.saveLicense(licenseString);
if (applied == 1) {
// success
}
else {
// license string not valid
}
				
			

Updating Data Files (Non-Evaluation Only)

To update BankFinder data, the data files (bacs.afd and bacsi.afd) need to be replaced in your data folder with the latest versions available from our server.

This can be done automatically using instance functions of the afd.bf.Engine class provided for updating.

The process to do this is typically as follows:

  • Call checkForUpdate, if this does not return 1 then no update is available so abort
  • When convenient call downloadUpdate to commence downloading the file. This function returns a response immediately so that you can continue using the software whilst the download progresses. If it returns 0 then no update is available, -1 indicates it couldn’t connect to the update server.
  • Check periodically by calling isDownloadComplete to determine if the download has completed, when it returns 1 the download has completed, <0 indicates an error downloading
  • Once downloaded call applyUpdate at an appropriate time to apply and load the new dataset.

An example of doing this is as follows:

				
					int needUpdate = afd.bf.Engine.checkForUpdate();
if (needUpdate == 1) {
int startedDownload = afd.bf.Engine.downloadUpdate();
if (startedDownload == 1) {
 while (afd.bf.Engine.isDownloadComplete() == 0) {
 // wait for download to complete – can carry on with other
tasks
 }
 int updateApplied = afd.bf.Engine.applyUpdate();
}
				
			

Function Reference

clear

Clears the search properties ready to start a new search public void clear();

This function takes no parameters and returns no value.

bankGetFirst

Starts a lookup or search and returns the first record Prior to calling this function, call Clear and set the appropriate search parameters to specify the fields you wish to search for (e.g. setSearchLookup).

				
					public int bankGetFirst(int flags)
				
			

flags is an integer and specifies which clearing systems to use. The possible options are:

  • AFD_ALL_RECORDS – Return all records (both systems)
  • AFD_UK_ONLY – Only return records on the BACS system
  • AFD_IRISH_ONLY – Only return records on the IPSO system

The function returns one of the following values:

  • AFD_SUCCESS – Successful lookup (result returned)
  • AFD_RECORD_BREAK – Search in progress call bankGetNext to get the next result
  • AFD_NOT_FOUND – No matching records found
  • AFD_ERROR_OPENING_FILES – Error opening BankFinder data files
  • AFD_DATA_LICENSE_ERROR – Data Licence Error
  • AFD_NO_SEARCH_DATA – No search parameters were set (or all set to empty strings)

If AFD_SUCCESS is returned you can then call any of the properties to obtain the fields for the returned record, e.g. getBankSortCode.

If AFD_SUCCESS or AFD_RECORD_BREAK is returned you should call bankGetNext to retrieve each subsequent record until AFD_END_OF_SEARCH is returned.

bankGetNext

Continues a lookup or search, returning the next matching record

				
					public int addressGetNext()
				
			

This function takes no parameters.

The function returns one of the following values:

  • AFD_SUCCESS – Successful lookup (result returned)
  • AFD_RECORD_BREAK – Search in progress call bankGetNext to get the next result
  • AFD_ERROR_OPENING_FILES – Error opening BankFinder data files
  • AFD_DATA_LICENSE_ERROR – Data Licence Error
  • AFD_END_OF_SEARCH – End of Search Reached

If AFD_SUCCESS is returned you can then call any of the properties to obtain the fields for the returned record, e.g. getBankSortCode.

If AFD_SUCCESS or AFD_RECORD_BREAK is returned you should continue to call bankGetNext to retrieve each subsequent record until AFD_END_OF_SEARCH is returned.

jumpToRecord

Returns data for the record key supplied

				
					public int jumpToRecord(int recordKey)
				
			

The recordNumber parameter is the key of the record to be retrieved. This would have been returned by using the getRecordKey method following a previous call to BankGetFirst or BankGetNext. Note this key should not be stored as it is not maintained across data updates; it is designed for reretrieving a record following a list being provided to the user.

The function returns one of the following values:

  • AFD_SUCCESS – Successful lookup (result returned)
  • AFD_NOT_FOUND – No matching records found (key must be incorrect)
  • AFD_ERROR_OPENING_FILES – Error opening BankFinder data files
  • AFD_DATA_LICENSE_ERROR – Data Licence Error

If AFD_SUCCESS is returned, any of the properties can be called to obtain the fields for the returned record, e.g. getBankSortCode.

validateAccount

Used to validate a sortcode and account number (or IBAN) to check it passes validation.

				
					public int validateAccount(int flags, String sortCode, String accountNo, String rollNumber, String iban);
				
			

Parameters should be initialised to a blank string as appropriate if unused.

flags is an integer and specifies which clearing systems to use. The possible options are:

  • AFD_ALL_RECORDS – Return all records (both systems)
  • AFD_UK_ONLY – Only return records on the BACS system
  • AFD_IRISH_ONLY – Only return records on the IPSO system

On return this value will be one of the following which can be useful when validating through both systems:

  • 1 – On UK Clearing System
  • 2 – On Irish Clearing System
  • 3 – On Both Clearing Systems

sortCode is a string used to specify the sort code to be validated.

accountNumber is a string used to specify the account number to be validated. It should be specified along with the sort code.

rollNumber is a string which is used to specify the Roll Number for validation. This is required along with the sortcode and account number for credits made to some building society accounts.

iban is a string which can be used in-place of passing a sortcode and accountnumber to validate an International Bank Account Number.

If the function returns a positive value (>=0) this should be taken to be valid.

Some non-standard account numbers may be transcribed to provide a standard length account number for BACS processing. It is therefore recommended that onward processing is done using the returned sortcode (getValidateSortCode) and account number (getValidateAccountNo), and type of account code returned (getValidateTypeOfAccountCode) rather than those supplied to the function.

There are also additional functions to get an IBAN from a validated sortcode and account number etc. The full list is given in section 6 of this manual.

The function returns one of the following values:

  • AFD_SUCCESS – Successful lookup (result returned)
  • AFD_VALIDATION_NOT_AVAILABLE – Successful, but validation isn’t available for this sortcode.
  • AFD_NOT_FOUND – Sortcode specified not found
  • AFD_ERROR_OPENING_FILES – Error opening BankFinder data files
  • AFD_DATA_LICENSE_ERROR – Data Licence Error
  • AFD_INVALID_SORTCODE – Sort code supplied is invalid
  • AFD_INVALID_ACCOUNT_NUMBER – Account number supplied is invalid
  • AFD_INVALID_ROLL_NUMBER – Roll number supplied is invalid
  • AFD_INVALID_IBAN – Invalid IBAN Supplied
  • AFD_UNRECOGNISED_COUNTRY – IBAN contained an unrecognised country code
  • AFD_IBAN_MISMATCH – Both a sort code, account number and IBAN were passed for validation but these did not match.

validateCard

Used to validate a card number to check it passes validation.

				
					public int validateCard(int revisionID, String cardNumber, String expiryDate);
				
			

revisionID is an integer and should be set to 2. It is provided for future proofing.

cardNumber is a string used to specify the card number you wish to validate.

expiryDate is a string used to specify the expiry date you wish to validate. This is optional but if specified a check will be made that the card is in date. This should be in the format MM/YY.

On return a positive value indicates the card is valid. The return value will indicate the type of card as follows:

  • AFD_MASTERCARD – Mastercard
  • AFD_VISA – Visa
  • AFD_AMERICAN_EXPRESS – American Express
  • AFD_VISA_DEBIT – Visa Debit
  • AFD_VISA_UK_ELECTRON – UK Electron Card
  • AFD_VISA_PURCHASING – Visa Purchasing Card
  • AFD_UK_MAESTRO – UK Issued Maestro Card
  • AFD_INTERNATIONAL_MAESTRO – Maestro Card
  • AFD_SOLO_AND_MAESTRO – Solo and Maestro (combined) Card
  • AFD_JCB – JCB Card
  • AFD_CHARITIES_AID_FOUNDATION – Charities Aid Foundation Card
  • AFD_MASTERCARD_DEBIT – Mastercard Debit Card

A negative return value indicates an error has occurred and could be any of the following:

  • AFD_ERROR_OPENING_FILES – Error opening BankFinder data files
  • AFD_DATA_LICENSE_ERROR – Data Licence Error
  • AFD_INVALID_EXPIRY – Expiry date specified is invalid (should be in format MM/YY)
  • AFD_CARD_EXPIRED – Card has expired
  • AFD_INVALID_CARD_NUMBER – Card Number supplied is invalid
  • AFD_VISA_ATM_ONLY – Visa card is valid for use in an ATM only
  • AFD BankFinder for Android API
  • AFD_UNRECOGNISED_CARD – Card type is unrecognised.

errorText

Used to retrieve text to display a friendly error message to go with an error code returned from the search or validation functions (return value less than zero).

				
					public String errorText(int errorCode)
				
			

errorCode is an integer and should be set to the return value from a previous function call.

On return a description for the error is returned which can be stored or displayed for the user.

cardText

Used to retrieve text to display or store the card type returned from the ValidateCard function.

				
					public String cardText(int cardType)
				
			

cardType is an integer and should be set to the return value from the validateCard function when that function returns a positive value.

On return a description for the card is returned, e.g. Mastercard or Visa Debit.

saveLicense

Used to save a license file on the device from a Base64 encoded string representation.

				
					public int saveLicense(string base64License)
				
			

Base64License is the string containing the base64 encoded license data.

Returns:

  • 0 Successfully applied license
  • -7 Data License Error (string is invalid)

checkForUpdate

  • Used to check if an update to the BankFinder data files is available.
  • public int checkForUpdate()

Returns:

  • 1 Update Available
  • 0 No Update Available (already on latest data)
  • -1 Error getting data (normally Internet connection issue)
  • -7 Data License Error or Evaluation data present

downloadUpdate

Used to start downloading a data update.

				
					public int downloadUpdate()
				
			

Returns:

  • 1 Update started downloading
  • 0 No Update Available (already on latest data)
  • -1 Error getting data (normally connection issue)
  • -7 Data License Error or Evaluation data present

When the function returns data continues to download in the background so your application can continue running. Poll with IsDownloadComplete periodically to determine when the download has finished.

isDownloadComplete

Used to indicate when a data download has completed downloading

				
					public int isDownloadComplete()
				
			

Returns:

  • 1 Download Complete
  • 0 Download still in progress
  • -1 No download started
  • -2 Download failed (call DownloadUpdate to retry)

applyUpdate

Used to update data files following a successful download and loads the new dataset.

				
					public int applyUpdate()
				
			

Returns:

  • 1 Update Successful
  • 0 Download in progress or failed
  • -1 No update present to apply
  • -7 Data License Error or Evaluation data present

Note that you mustn’t call the BankFinder functions while this call is completing as old data will be unloaded, the new data unpacked and then loaded during this call.

Properties Reference

Getter and setter methods are provided for the BankFinder fields. These are as follows:

Field NameDescription
Search Fields (Any of these can be set prior to a call to bankGetFirst) 
setSearchLookupSpecify sort code, postcode and fast-find lookup strings here for lookup operations. No other search fields should be set when this is used.
setSearchSortCodeBank’s Sortcode
setSearchBankBICBank’s BIC Code
setSearchBranchBICBranch BIC Code (should be used in conjunction with Bank BIC)
setSearchPostcodeRoyal Mail Postcode for correspondence for the bank
setSearchBranchNameBranch Name
setSearchBankNameOwner Bank Name
setSearchTownTown or Location of the bank
setSearchPhonePhone Number
SearchTextSpecify text to search for within any of the BankFinder fields
General Bank Fields 
getRecordKeyReturns a record key (integer) to use for subsequent retrieval of the record with JumpToRecord. Note this should not be stored as it does not persist across data updates.
getBankSortCodeBank’s Sortcode
getBankBICBank BIC Code [1]
getBranchBICBranch BIC Code [1]
getBankSubBranchSuffixAllows a branch to be uniquely identified where there is a cluster of branches sharing the same Sort Code [1]
getBankShortBranchTitleThe official title of the branch
getBankCentralBankCountryCodeThe ISO Country code for beneficiary banks in other countries
getBankSupervisoryBodyIndicates the supervisory body for an institution that is an agency in any of the clearings. [2]
getBankDeletedDateSpecifies the date the branch was closed if it is not active
getBankBranchTypeIndicatorThe branch type – Main Branch, Sub or NAB Branch, Linked Branch
getBankMainBranchSortCodeSet for linked branches in a cluster. It identifies the main branch for the cluster. For IPSO records this is set to the branch that would handle transactions for this sortcode when the branch has been amalgamated with another.
getBankMajorLocationNameWhere present helps indicate the physical location of the branch.
getBankMinorLocationNameWhere present helps indicate the physical location of the branch.
getBankBranchNameDefines the actual name or place of the branch
getBankBranchName2An alternative name or place for the branch where applicable.
getBankFullBranchTitleExtended title for the institution
getBankOwnerBankShortNameShort version of the name of the Owning Bank
getBankOwnerBankFullNameFull version of the name of the Owning Bank
getBankOwnerBankCodeThe four digit bank code of the Owning Bank [1]
getBankPropertyBank Postal Address: Property (Building)
getBankStreetBank Postal Address: Street
getBankLocalityBank Postal Address: Locality
getBankTownBank Postal Address: Town
getBankCountyBank Postal Address: County (Optional)
getBankPostcodeThe Royal Mail Postcode for this address
getBankSTDCodeSTD Code for the Bank Phone number
getBankPhonePhone number
getBankFaxSTDCodeSTD Code for the Bank Fax Number
getBankFaxFax number (where held)
getBankCountryIndicatorReturns ‘U’ if the record is on the BACS system, or ‘I’ if the record is on IPSO.
getBankSTDCode2STD Code for a secondary Bank Phone number
getBankPhone2Secondary Phone number (where held)
getBankListReturns a formatted line for list insertion containing elements of the Bank record. Useful when displaying a list of branch results for the user to choose from.
BACS Related Fields (Not applicable to IPSO Records) 
getBACSStatusIndicates the BACS Clearing Status [4]
getBACSLastChangeDate on which BACS data was last amended
getBACSClosedClearingIndicates the date the branch is closed in BACS clearing if applicable. 
getBACSRedirectedFromFlagSet to R if other branches are redirected to this sort code.
getBACSRedirectedToSortCodeThis specifies the sort code to which BACS should redirect payments addressed to this sort code if applicable.
getBACSSettlementBankCodeBACS Bank Code of the bank that will settle payments for this branch.
getBACSSettlementBankShortNameShort form name of the settlement bank
getBACSSettlementBankFullNameFull form name of the settlement bank
getBACSSettlementBankSectionNumeric data required for BACS to perform its settlement.
getBACSSettlementBankSubSectionNumeric data required for BACS to perform its settlement.
getBACSHandlingBankCodeBACS Bank Code of the member that will take BACS output from this branch.
getBACSHandlingBankShortNameShort form name of the handling bank
getBACSHandlingBankFullNameFull form name of the handling bank
getBACSHandlingBankStreamNumeric code defining the stream of output within the Handling Bank that will be used or payments to this branch.
getBACSAccountNumberedSet to 1 if bank has transferrable account numbers
getBACSDDIVoucherSet to 1 if Paper Vouchers have to be printed for Direct Debit Instructions.
getBACSDirectDebitsSet to 1 if branch accepts Direct Debits
getBACSBankGiroCreditsSet to 1 if branch accepts Bank Giro Credits
getBACSBuildingSocietyCreditsSet to 1 if branch accepts Building Society Credits.
getBACSDividendInterestPaymentsSet to 1 if branch accepts Dividend Interest Payments.
getBACSDirectDebitInstructionsSet to 1 if branch accepts Direct Debit Instructions.
getBACSUnpaidChequeClaimsSet to 1 if branch accepts Unpaid Cheque Claims.
CHAPS Related Fields (Not applicable to IPSO Records) 
getCHAPSPStatusIndicates the CHAPS Sterling clearing Status [5]
getCHAPSPStatusDescriptionProvides a description for the status [5]
getCHAPSPLastChangeDate on which CHAPS Sterling data was last amended
getCHAPSPClosedClearingIndicates the date the branch is closed in CHAPS Sterling clearing if applicable.
getCHAPSPSettlementBankCodeCHAPS ID of the bank that will settle payments for this branch,
getCHAPSPSettlementBankShortNameShort form of the name of the settlement bank
getCHAPSPSettlementBankFullNameFull form of the name of the settlement bank
C&CCC Related Fields (Not applicable to IPSO Records) 
getCCCCStatusIndicates the C&CCC clearing Status [6]
getCCCCLastChangeDate on which C&CCC data was last amended
getCCCCClosedClearingIndicates the date the branch is closed in C&CCC clearing if applicable.
getCCCCSettlementBankCodeBACS generated code of the bank that will settle payments for this branch.
getCCCCSettlementBankShortName Short form of the name of the settlement bank
getCCCCSettlementBankFullName Full form of the name of the settlement bank
getCCCCDebitAgencySortCodeWhen the Status field is set to ‘D’ this specifies where cheque clearing is handled for this branch.
getCCCCReturnIndicatorSet if this is the branch that other banks should return paper to. It will only be set for a sort code of a Member.
getCCCCGBNIIndicatorSet if this is the branch that other banks should return paper to. It will only be set for a sort code of a Member.
FPS Related Fields (Not applicable to IPSO Records) 
getFPSStatusIndicates the FPS clearing Status [7]
getFPSLastChangeDate on which FPS data was last amended
getFPSClosedClearingIndicates the date the branch is closed in FPS clearing if applicable.
getFPSRedirectedFromFlagSet to R if other branches are redirected to this sort code.
getFPSRedirectedToSortCodeThis specifies the sort code to which FPS should redirect payments addressed to this sort code if applicable.
getFPSSettlementBankConnectionTwo digit connectivity code (will be 01 FPS Member)
getFPSSettlementBankCodeBank Code of the bank that will settle payments for this branch.
getFPSSettlementBankShortNameShort form name of the settlement bank
getFPSSettlementBankFullNameFull form name of the settlement bank
getFPSHandlingBankConnectionTwo digit connectivity code
getFPSHandlingBankCodeBank Code of the bank that will handle payments for this branch.
getFPSHandlingBankShortNameShort form name of the handling bank
getFPSHandlingBankFullNameFull form name of the handling bank
getFPSAccountNumberedFlagSet to 1 if bank has transferrable account numbers
getFPSAgencyTypeIf getFPSStatus is ‘A’ this will be set to either ‘D’ for a direct agency or ‘I’ for an indirect agency.
Account Validation Fields (Only applicable following a call to ValidateAccount) 
getValidateSortCodeContains the validated sortcode, may be updated if account number translation is required, e.g. for non-standard length account numbers.
getValidateAccountNoContains the validated account number, like the sortcode may have been updated and this value is one that should be submitted to BACS.
getValidateTypeOfAccountCodeThis returns the value required for the type of account code field on BACS. This is normally zero but is required in some cases when account numbers are translated from nonstandard lengths.
getValidateNeedRollNumberIndicates if a roll number is required for the sortcode and account number specified. This will be one of the following values:
-1 – No Roll Number required, but one was supplied
0 – No Roll Number required
1 – Roll Number required, but not supplied
2 – Roll Number required and one was supplied
getValidateIBANIf a sortcode and account number is validated this field will return the corresponding IBAN were possible.
getValidateCountryReturns the country name corresponding to an IBAN passed for validation.

Notes:

[1] Does not apply to records in the IPSO (Irish Payment Services Organisation) clearing system.

[2] The supervisory body code can be any of the following:

  • A. Bank of England
  • B. Building Society Commission
  • C. Jersey, Guernsey or Isle of Man authorities
  • D. Other

[3] The clearing system property can have one of the following values

  • United Kingdom (BACS) – For branch records for the UK clearing system
  • Ireland (IPSO) – For branch records on the Irish Payment Services Organisation Clearing System
  • Both UK and Irish – Returned by Account Number Validation only when a branch is on both systems.

Note, that you should only accept account numbers validated on the Irish system if you can clear through both the Irish (IPSO) system as well as the UK (BACS) system.

[4] Possible values for the BACS Status fields are as follows:

  • M. Branch of a BACS Member
  • A. Branch of an Agency Bank
  • I. Member of the Irish Clearing Services (IPSO)
  • Does not accept BACS Payments

[5] Possible values for the CHAPS Sterling Status fields are as follows:

  • M. Direct Branch of a CHAPS £ Member that Accepts CHAPS £ Payments
  • A. Branch of an Agency Bank that Accepts CHAPS £ Payments
  • I. Indirect Branch of a Member or Agency Bank that Accepts CHAPS £ Payments
  • Does not accept CHAPS £ Payments

[6] Possible values for the C&CCC Status fields are as follows:

  • M. Branch of a C&CCC Member
  • F. Full Agency Bank Branch
  • D. Debit Agency Branch Only

Not Part of the C&CCC Clearing

[7] Possible values for the FPS Status fields are as follows:

  • M. Bank office of FPS member, accepts FPS payments
  • A. Bank office of FPS agency bank, accepts FPS payments
  • N. Bank office does not accept FPS payments.
mailLink mailLink

We are here to help

We serve thousands of organisations and a network of hundreds of partners across multiple industry sectors, enabling them to have full confidence in their contact data.