Fork me on GitHub
Skip to page content
 

Android Federal Data SDK

Adding the SDK to Your Project

Add SDK files to your project

Extract the zipped SDK folder or grab the Git repository.

Copy the contents of the SDK src folder to the src folder of your Android project.

Using the SDK

Reference the DOL Data API in your source file

In the source files that will make Goverment Data requests add the following imports:

import java.util.HashMap;
import govdata.api.GOVDataContext;
import govdata.api.GOVDataRequest;
import govdata.api.GOVDataRequestCallback;

Prepare your class for callbacks

The DOL Data SDK processes requests asynchronously to prevent locking up the UI while the data is requested and processed. To achieve this the SDK makes use of callback methods. To successfully retrieve data it is required to implement the two GOVDataRequestCallback methods. The methods will be invoked when the results have been processed or when an error occurs.

1. Implement the GOVDataRequestCallback interface in the class that will receive and process the API responses

Example:

public class DOLDataAPI extends ListActivity
	implements GOVDataRequestCallback

2. Add the interface methods to the class

public void  GOVDataResultsCallback(List > results) {
//Todo: Add your code to process the results
	Results are in a list of maps. Each map contains one record
}

//Government entity data set call.
		@Override
		public void GOVDataResultsCallback(String results) {
	
		    //Todo: Add your code to handle the error
		      	
		}

public void GOVDataErrorCallback(String error) {
	//Todo: Add your code to handle the error
}

Making API Calls


The GOVDataRequest class is used to make API calls. It requires a context object to be passed to its constructor in order to get the API key and URL information needed for the requests. The GOVDataContext is the context class used to hold this information.

You can pass arguments to the API call by adding them to a HashMap as key/value pairs and passing it as the second parameter of the callAPIMethod
method. Valid arguments are defined later in this document.

In order to make requests:

  1. Instantiate a GOVDataContext object
  2. Instantiate a GOVDataRequest object and pass the context and the callback object (usually this) as parameters.
  3. Create a HashMap and store all the API arguments as key/value pairs.
  4. Call the callAPIMethod method, passing the API name and the arguments (or null if there are no arguments)

Sample code to make requests for standard DOL API datasets:

//Usually stored as instance variables
 // API Key and URL constants
    public final String API_HOST = "http://data.fcc.gov";
    public final String API_KEY = "";
    public final String SHARED_SECRET = "";
    public final String API_URI = "/api/block";
    public final String API_DATA = "/find";
/////////////////////////////////////

//Instantiate Government Data context object
//This object stores the API information required to make requests
 GOVDataContext context = new GOVDataContext(API_KEY, SHARED_SECRET, API_HOST, API_URI, API_DATA);

//Instantiate new request object. Pass the callback object (this) and
//context that contains all the API key info
GOVDataRequest request = new GOVDataRequest(this, context);

//API we want to fetch data from
String method = "FORMS/Agencies";

//Build Hashtable arguments
HashMap args = new HashMap ();
args.put("top", "2");
args.put("filter", "AgencyId eq 'OSHA'");
//Make API call
request.callAPIMethod(method, args);

Sample code to make requests for DOL Service Operation (e.g Summer Jobs Plus) :

//Usually stored as instance variables
public final String API_KEY = "YOUR API KEY";
public final String SHARED_SECRET = "YOUR SHARED SECRET";
public final String API_HOST = "http://api.dol.gov/";
public final String API_URI = "/V1";//API VERSION
public final String API_DATA = "";
/////////////////////////////////////

//Instantiate GOV Data context object
//This object stores the API information required to make requests
 GOVDataContext context = new GOVDataContext(API_KEY, SHARED_SECRET, API_HOST, API_URI, API_DATA);

//Instantiate new request object. Pass the callback object (this) and
//context that contains all the API key info
GOVDataRequest request = new GOVDataRequest(this, context);

//API we want to fetch data from
string methodname = "SummerJobs/getJobsListing";
	
// HashMap to store the arguments
HashMap summerJobsArgs = new HashMap(7);
	 
// API method to call
// Populate the args into the HashMap
HashMap summerJobsArgs = new HashMap ();
	
summerJobsArgs.put("format", "'json'");
summerJobsArgs.put("query", "'Farm'");
summerJobsArgs.put("region", "");
summerJobsArgs.put("locality", "");
summerJobsArgs.put("skipCount", "8");
//Make API call
request.callAPIMethod(methodname, summerJobsArgs);

Sample code to make requests for outside Government Entity:

//Usually stored as instance variables
public final String API_KEY = "YOUR API KEY";
public final String SHARED_SECRET = "YOUR SHARED SECRET";
public final String API_HOST = "http://api.sba.gov/loans_grants/federal.xml";
public final String API_URI = "/V1";//API VERSION
public final String API_DATA = "";
/////////////////////////////////////

//Instantiate GOV Data context object
//This object stores the API information required to make requests
 GOVDataContext context = new GOVDataContext(API_KEY, SHARED_SECRET, API_HOST, API_URI, API_DATA);

//Instantiate new request object. Pass the callback object (this) and
//context that contains all the API key info
GOVDataRequest request = new GOVDataRequest(this, context);

//API we want to fetch data from you can leave this information blank and it will return a raw data set call of xml or json.
string methodname = "YourString/DataSet";
	
// HashMap to store the arguments
HashMap yourDataArgs = new HashMap(7);
	 
// API method to call
// Populate the args into the HashMap
HashMap yourDataArgs = new HashMap ();
//Add your code to hasp map your data results.	

//Make API call
request.callAPIMethod(methodname, yourDataArgs);

The callAPIMethod triggers the SDK to process the request, add authorization headers and callback with the results or with an error message. Once the process has completed one of the two callback methods from the GOVDataRequestCallback interface will be called. If successful, the GOVDataResultsCallback method will be called and the results parameter will contain the data you requested. The results parameter contains a Vector of Hashtables. Each Hashtable is mapped to one record of the dataset. If the request failed for any reason, the GOVLDataErrorCallback will be called and the error parameter will contain a description of the error.

Sample code to make requests for standard DOL API datasets:

public void GOVDataResultsCallback(List > results) {
	//Todo: Add your code to process the results
	Map record = results.get(0);
	if(null != record.get("AgencyName") && record.get("AgencyName")!= "")
	{
		String name = record.get("AgencyName");
	}
}

Sample code to make requests for outside Government Entity API datasets This simply returns raw data. Please make the hashmap adjustment to format the data you are returning.:

//Government entity data set call.
		@Override
		public void GOVDataResultsCallback(String results) {
			List dataresults = new ArrayList();
		    dataresults.add(results);
			// Set list adapter. 
	    	setListAdapter(new ArrayAdapter(this,R.layout.list_item,dataresults));
	    	// Enable text filtering
	    	ListView lv = getListView();
	    	lv.setTextFilterEnabled(true);
		      
		
		}
}
public void GOVLDataErrorCallback(String error) {
	//TODO:  Add your code here
}

Sample code to make requests for DOL service operation: The the
GOVDataResultsCallback method will provide access to the results in the form of
List of Map objects.Developer has to clean the json response text to get the clean json object from service response. SomeTime search result may have special charcter which cause to thrown
an error during JSON serialization.

public void GOVDataResultsCallback(List > results) {
	
	//Todo: Add your code to process the results
	// Create List of strings to populate the listview items
	
	List display = new ArrayList();
	
	//Create  JSON Object and JSONArray to store the data from DOlservice operation.
	JSONObject jsonObject = null;
	JSONArray subArray =null;
	
	// Iterate thru List of results. Add each field to the display List		
	for (Map m : results) {
		try {
			//Look for value of getJobsListing property.
			if(null != m.get("getJobsListing"))
				{
					String jobs = m.get("getJobsListing");
					//convert jString to the jObject
					jobs = jobs.replaceAll("\\\\n", "");
					jobs = jobs.replaceAll("\\\\\"", "\"");
					jobs = jobs.replaceAll("\"\\{", "\\{");
					jobs = jobs.replaceAll("\\}\"", "\\}");
					// start extracting the content from jObject
					jsonObject = new JSONObject(jobs);
				
					if(null!=jsonObject)
					{
						//Look for an array of "item".
						subArray = jsonObject.getJSONArray("items");
						if(null!= subArray)
						{
							//Lets loop through each jobs.
							for(int i=0; i<subArray.length(); i++)  
							{  
								//Get the job title. 
								
								display.add(
										subArray.
										getJSONObject(i).
										getString("title"));
							}  
						}
					}
			}
				
		} catch (JSONException e) {
			e.printStackTrace();
		}  
	}
} 

Sample code to make requests for outside Government Entity API datasets This simply returns raw data. Please make the hashmap adjustment to format the data you are returning.:

//Government entity data set call.
		@Override
		public void GOVDataResultsCallback(String results) {
			List dataresults = new ArrayList();
		    dataresults.add(results);
			// Set list adapter. 
	    	setListAdapter(new ArrayAdapter(this,R.layout.list_item,dataresults));
	    	// Enable text filtering
	    	ListView lv = getListView();
	    	lv.setTextFilterEnabled(true);
		      
		
		}
public void GOVLDataErrorCallback(String error) {
	//TODO:  Add your code here
}

API Method Arguments

Standard DOL API datasets

top

The top argument is used to specify the number of records to be returned.

Example:

//Return top 2 records
HashMap< String, String > args = new HashMap < String, String >();
args.put("top", "2");

skip

The skip argument specifies that you want the service to skip a specified number of results. This argument in combination with top, serve as the basis to implement pagination.

Example:

//Return records 21-30
HashMap< String, String > args = new HashMap< String, String >();
args.put("top", "10");
args.put("skip", "20");

select

The select argument allows you to specify the exact columns that you want the API to return. Separate them with commas if there is more than one.

In order to save bandwidth, it is always a good idea to add a select clause to most requests and retrieve the columns needed for a specific function. Some datasets can contain dozens of columns and the performance of your app can be impacted if you always return all of the columns. This is even more important in mobile applications because of device memory limitations, possible slow network speeds, and data usage caps imposed by carriers.

Example:

//Select the AgencyId and AgencyFormNumber columns
HashMap< String, String > args = new HashMap < String, String >();
args.put("select", "AgencyId,AgencyFormNumber");

orderby

Use the orderby argument to sort the data by one or more columns. Separate them with commas if there is more than one.

//Order by the AgencyFormNumber column
HashMap< String, String > args = new HashMap < String, String >();
args.put("orderby", "AgencyFormNumber");

filter

The filter argument is used to add filters to the API query. For example, you can filter results where a specific column is equal to a string provided.

The API recognizes the following comparison keywords:

  • eq – Equal to
  • ne – Not Equal to
  • gt – Greater than
  • lt – Less than
  • ge – Greater than or equal to
  • le – Less than or equal to

For string comparisons enclose any multiple word string in single quotes. For example: 'Legal Identity Report'

More than one filter can be specified by joining them with the and/or keywords. Separate filters with parenthesis.

For example: (AgencyId eq 'MSHA') and (Title eq 'Legal Identity Report') retrieves the records where the value in the AgencyId column is equal to 'MSHA' and the value for the Title column is equal to 'Legal Identity Report'.

Example:

//Filter columns
HashMap < String, String > args = new HashMap< String, String >();
args.put("filter", "(AgencyId eq  'MSHA') and (Title eq 'Legal Identity Report')");

DOL Service Operation for Summer Jobs Plus

To use the Service Operations API the Operation name and parameters need to be supplied using the data services format. Each String typed parameter must be surrounded in quotes in order to work correctly. These quotes are then Url encoded and passed to the Service Operation.

format

The format argument allows you to specify the format that the results string will be returned. If format argument is not passed with request then result will be returned in json format by default. Following are the supported format of results string.

Format Codes:
  • json ( Default )
  • xml
  • atom

Example:

// HashMap to store the arguments
HashMap summerJobsArgs = new HashMap(7);
summerJobsArgs.put("format", "'json'");
,>,>

query

The query argument will be used to find matching job listings. This is required if region or locality are not provided.

Example:

// HashMap to store the arguments
HashMap summerJobsArgs = new HashMap(7);
summerJobsArgs.put("query", "'Farm'");
,>,>

region

The region argument will be used to filter jobs listings by the state name or abbreviation. This is required if query or locality are not provided.

Example:

// HashMap to store the arguments
HashMap summerJobsArgs = new HashMap(7);
summerJobsArgs.put("region", "");
,>,>

locality

The region argument will be used to filter jobs listings by The city name. This is required if query or region are not provided.

Example:

// HashMap to store the arguments
HashMap summerJobsArgs = new HashMap(7);
summerJobsArgs.put("locality", "");
,>,>

skipCount

The skipCount argument will be used to specify the number of records to skip ahead from the first recor.Valid range of 1-99 and it required.

Example:

// HashMap to store the arguments
HashMap summerJobsArgs = new HashMap(7);
summerJobsArgs.put("skipCount", "1");
,>,>

Licenses

The DOLData classes (whose file names start with DOLData) are released to the Public Domain.

This SDK makes use of other libraries that are licensed differently. Please read them carefully.

org.json.me, org.json.me.util

Copyright (c) 2002 JSON.org

Permission is hereby granted, free of charge, to any person obtaining a cop of this software and associated documentation files (the "Software"), to dea in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

The Software shall be used for Good, not Evil.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.