Android SearchKit SDK Quick Start and User Guide

Prerequisites

  • The user must be familiar with the Android™ operating system, Android Studio development environment and Java® programming language.

  • The Android Studio (version 3.4 or above) must be installed

Note
The Android SearchKit software development kit (SDK) supports application programming interfaces (APIs) with a minimum version of 19 and above. This SDK is built, targeting the Android APIs with version 28.

About API Key

The API key is used to track API requests of the project for usage and billing. API key often acts as a unique identifier and a secret token for authentication. The API key can be requested by filling in details and submitting the form at https://locationstudio.zendesk.com/hc/en-us/requests/new?ticket_form_id=360001758513.

Quick Start Steps

This following steps will help you to start using the Android SearchKit SDK.

Getting the SDK

To obtain the Android SDK, perform the following steps:

  1. Go to https://git.location.studio/location.studio/androidSDK/tree/master.

  2. Register or sign in to your existing Comtech Location Studio® Git account.

  3. If you created a new account, access it by clicking the Confirm your account link sent to the registered email ID.

  4. On the home page under the Project tab, click on the download icon drop-down menu to save the Android SDK zip package to your local drive. As an alternative, you can clone the repository to your local system using the following command.

After you have downloaded and extracted the zip package or cloned the repository, follow the steps described in the next sections to begin using the SDK.

Getting Started

The following sections show how to perform a simple keyword search in a sample Android application.

Note
The following steps are targeted for Android Studio with version 3.4. The steps may vary for other versions of the Android Studio.

Project Setup

The following steps explain the project setup required to create a sample app using the Android SearchKit SDK.

  1. Start Android Studio.

  2. Start a new Android Studio project.

  3. Select an Empty Activity project and click Next as in the following screenshot.

Empact
Figure 1. Selecting Empty Activity
Note

Other types of available projects can also be selected during the project setup, but this tutorial uses Empty Activity project for easy understanding.

  1. In the Configure your project screen, enter your desired values for Name, Package name and all other fields as shown in the following screenshot.

Note
Make sure that the API version entered is at least 19. API versions of 19 and above are supported in the Android SearchKit SDK. The SDK supports both Java and Kotlin™ programming languages. For this sample project, we are selecting Java in the Language drop-down menu.
Configuring the Project
Figure 2. Configuring the Project

Dependency Setup

This section describes the dependency set up for Android SearchKit SDK APIs. The SearchKit SDK is part of the ltk_common.aar library. The following steps are performed to complete the dependency set up.

  1. Import the ltk_common.aar, as described in the following steps.

    • From the File menu select New, and then select New Module…​ as shown in the following screenshot.

New Module
Figure 3. Choosing New Module
  • Select Import .JAR/.AAR Package and click Next as shown in the following screenshot.

Import .JAR/.AAR
Figure 4. Import .JAR/.AAR Package
  • In the File name, browse to the androidSDK/libproj/ltk_common location, select the ltk_common.aar file and click Finish.

Selecting ltk_common.aar
Figure 5. Selecting ltk_common.aar
  1. Open the build.gradle of the app module and add the following dependencies:

implementation project(path: ':ltk_common')

Adding Permissions to AndroidManifest.xml

The following permissions must be declared inside the <manifest> tag in the AndroidManifest.xml file to make the Android SearchKit SDK work.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Note
If the application targets an API with version 26 or higher, make sure to check ACCESS_FINE_LOCATION and READ_PHONE_STATE permissions during runtime using the PermissionsManager, before initializing the SDK related classes.
Note
For this sample application, you can set the target SDK version to less than or equal to 25, in the build.gradle of app module.

Creating a Search Request

The following sections describe the process to create a simple search request. To get started, add the code snippets to the MainActivity’s onCreate() method. If you are targeting an API with version 26 or higher, you need to request for user permissions before using the SearchKit classes.

Creating the LTKContext Object

For using the Location ToolKit (LTK) services, you must create a LTKContext object, a singleton instance of services through which you can configure the API Key, language, country, and so on as shown in the following code snippet.

LTKContext.Builder ltkContextBuilder = new LTKContext.Builder(
        getApplicationContext(), "PUT_YOUR_API_KEY_HERE", "en");
ltkContextBuilder.setProductName("default");
LTKContext ltkContext = ltkContextBuilder.buildLTKContext();

In the above code, you need to put the received API key in the place of “PUT_YOUR_API_KEY_HERE.”

Creating the SingleSearchConfiguration Object

The SingleSearchConfiguration provides various search configurations and is needed to make a search request. The following code snippet shows creation of the SingleSearchConfiguration object.

// Create the search configuration
SingleSearchConfiguration config = new SingleSearchConfiguration();

Defining the Search Region

To make a search request, you need to provide the search center or the search bounding box. The following code snippet shows how to define a search region.

// Define the search region
SearchRegion[] regions = new SearchRegion[1];
regions[0] = new SearchRegion(40.661, -73.944); // New York City

The Search Handler

The SingleSearchListener returns the search result. The following code snippet shows MySearchHandler, a sample SingleSearchListener implementation, which prints the names of the places of the search result.

// Class handle the search result
class MySearchHandler implements SingleSearchListener {

    @Override
    public void onSingleSearch(SingleSearchInformation singleSearchInformation, SingleSearchRequest singleSearchRequest) {
        // Print the search result
        if (singleSearchInformation != null) {
            for (int i = 0; i < singleSearchInformation.getResultCount(); i++) {
                Log.d("SearchResult", singleSearchInformation.getPOI(i).getPlace().getName());
            }
        }
    }
@Override
public void onRequestCancelled(LTKRequest ltkRequest) {...}

@Override
    public void onRequestError(LTKException e, LTKRequest ltkRequest) {...}

@Override
    public void onRequestProgress(int i, LTKRequest ltkRequest) {...}

@Override
public void onRequestStart(LTKRequest ltkRequest) {...}

@Override
public void onRequestTimeOut(LTKRequest ltkRequest) {...}

@Override
public void onRequestComplete(LTKRequest ltkRequest) {...}
}

Creating a Sample Search Request

The following code snippets show creation of a sample search request using ltkContext, config, regions, and MySearchHandler created in the preceding step, to perform a keyword search for “hotel".

SingleSearchRequest singleSearchRequest = new SingleSearchRequest(
        ltkContext,
                "hotel",
                regions,
                null, null, null, null,
                new MySearchHandler(),
                config,
                "en-US");
singleSearchRequest.startRequest();

Building and Running the Sample App

Using the preceding code snippets, you can test the initialization and creation of the simple search request in the sample app. On building and running the sample app, you can see the printed search result in the LogCat window as shown in the following screenshot.

Search Result in LogCat
Figure 6. Search Result on LogCat

The following are the major features and configurations available in the Android SearchKit SDK.

SearchRegion

To make any SearchKit request, a search region must be provided. The search region can be the search center or a bounding box. This can be defined as follows.

Search Center

SearchRegion[] regions = new SearchRegion[1];
regions[0] = new SearchRegion(40.661, -73.944);

Search Bounding Box

SearchRegion[] regions = new SearchRegion[2];
regions[0] = new SearchRegion(40.4774, -74.2589);
regions[1] = new SearchRegion(40.9176, -73.7004);

SingleSearchConfiguration

This class defines various configurations for a search request. The following code snippet shows these configurations.

SingleSearchConfiguration config = new SingleSearchConfiguration();
config.setExtendedConfiguration(SearchRequest.POI_ENHANCED);
config.setWantSearchResultId(true);
config.setWantStructuredHoursOfOperation(true);
config.setWantResultDescription(true);

Single Search

This feature facilitates the single search.

SingleSearchRequest

This class is the entry point for the single search request. To make a single search request, we need to provide search region, search listener, search configuration and language along with the search keyword, as shown in the following code snippet.

SingleSearchRequest singleSearchRequest = new SingleSearchRequest(
        ltkContext,
        "hotel",
         regions,
         null, null, null, null,
         new SingleSearchListener(){...},
         config,
         "en-US");
singleSearchRequest.startRequest();

SingleSearchListener

SingleSearchListener provides notifications for a search request. This must be set to a SingleSearchRequest, to receive the search response. It contains the following method to return the search response.

void onSingleSearch(SingleSearchInformation information, SingleSearchRequest request)

The above method is a callback to provide the result of the single search request.

SingleSearchInformation

SingleSearchInformation represents the search response. It has methods to obtain the search results count, and Point Of Interest (POI) information, which includes distance, name, address, position, image, and so on.

To perform category search, the property wantRelatedSearch needs to be set to true for the SingleSearchConfiguration object through the method setWantRelatedSearch, as shown in the following code snippet.

SingleSearchConfiguration config = new SingleSearchConfiguration();
config.setWantRelatedSearch(true);

To know the details of search category codes, go to Appendix: Search Category Codes.

Suggestion Search

This feature facilitates suggestion search.

SuggestionSearchRequest

This class is the entry point for the suggestion search request. To create a suggestion search request, we need to provide search region, suggestion search listener, suggestion search configuration, and language along with the search keyword as shown in the following code snippet.

SuggestionSearchRequest suggestionSearchRequest = new SuggestionSearchRequest(
         ltkContext,
         SuggestionSearchRequest.SEARCH_TYPE_INTEREST,
          "hotel",
          regions,
          new SuggestionSearchListener(){...},
          config,
          "en-US");
suggestionSearchRequest.startRequest();

SuggestionSearchListener

SuggestionSearchListener provides notifications for a suggestion search request. This must be set to a SuggestionSearchRequest, to receive the suggestion search response. It contains the following method which returns the response.

void onSuggestionSearch(SuggestionSearchInformation information, SuggestionSearchRequest request)

The above method is a callback to provide the result of the suggestion search request.

SuggestionSearchInformation

This represents a suggestion search result. You can get the result count as well as matched locations along with their suggestion type, name, address and so on from this.

Geocoding

Geocoding is the process of converting addresses, like a street address, to geographic coordinates (latitude and longitude). These coordinates can be used to place markers on a map, or to position the map. In SearchKit, there is no separate interface for geocoding and this can be done using the same SingleSearchRequest, that is used for keyword search. The matching locations are obtained when the SingleSearchInformation throws the SingleSearchListener.onSingleSearch().

SingleSearchConfiguration config = new SingleSearchConfiguration();
SearchRegion[] regions = new SearchRegion[1]; // New York City
regions[0] = new SearchRegion(40.4774, -74.2589);
SingleSearchRequest singleSearchRequest = new SingleSearchRequest(
        ltkContext,
        "City Hall Park, New York, USA",
        regions,
        null, null, null, null,
        new SingleSearchListener(){...},
        config,
        "en-US");
singleSearchRequest.startRequest();

Reverse Geocoding

Reverse geocoding is the process of converting geographic coordinates into a human-readable address.

ReverseGeocodeRequest

The com.locationtoolkit.search.reversegeocode.ReverseGeocodeRequest class is the entry point for the reverse geocode request. To create a reverse geocode request we need to provide latitude and longitude of the location, along with a listener to get the result. The response is returned through ReverseGeocodeListener.onReverseGeocode() method as shown in the following code snippet.

ReverseGeocodeRequest reverseGeocodeRequest = new ReverseGeocodeRequest(
        ltkContext,
        40.661, -73.944, // New York City
        true,
        new ReverseGeocodeListener() {...});
reverseGeocodeRequest.startRequest();

ReverseGeocodeListener

This ReverseGeocodeListener provides notifications for a reverse geocode request. This must be set to a ReverseGeocodeRequest, to receive the reverse geocoded address. It contains the methods described in the following table to return the response.

Table 1. ReverseGeocodeListener Methods
Method Description

void onReverseGeocode (ReverseGeocodeInformation reverseGeocodeInfo, ReverseGeocodeRequest reverseGeocodeRequest)

Callback to provide the result of the reverse geocode

void onRequestCancelled(LTKRequest request)

Callback method when a request is cancelled

void onRequestComplete(LTKRequest request)

Callback method when a request gets successfully completed

void onRequestError(LTKException exception, LTKRequest request)

Callback method when some exception is thrown

void onRequestProgress(int percentage, LTKRequest request)

Callback method when a request is in progress

void onRequestStart(LTKRequest request)

Callback method when a request is going to be sent

void onRequestTimeOut(LTKRequest request)

Callback method when a request timeout occurs

ReverseGeocodeInformation

This represents the results of a reverse geocode operation. It contains a map location along with its type, name, address, and so on.

Error Codes

Different error codes are thrown from SearchKit while executing a search request via SingleSearchListener.onRequestError().

public void onRequestError(LTKException exception, LTKRequest request) {
    if (exception != null) {
        int errorCode = exception.getErrorCode();
    }
}

This table describes the major errors thrown in Android SearchKit SDK.

Table 2. SearchKit Errors
Error Code Description

LTK_NETWORK_ERROR2000

The request failed for an unknown reason

LTK_NETWORK_ERROR2001

An error response was received from the server

LTK_NETWORK_ERROR2002

No response was received from the server within the allotted time

LTK_NETWORK_ERROR2003

An unknown low-level error was generated by the client application

LTK_NETWORK_ERROR2004

An error occurred trying to connect to the server

LTK_NETWORK_WRITE_ERROR

Failed to write to a network socket

LTK_NETWORK_READ_ERROR

Failed to read from a network socket

LTK_NETWORK_NO_ REVERSE_GEOCODE

Unable to reverse geocode the specified location

LTK_SERVER_ERROR_QUERY _LIMIT_REACHED

The maximum daily queries limit for this API Key has been reached

LTK_SERVER_ERROR_ INVALID_API_KEY

The specified API Key is not valid

LTK_SERVER_ERROR_MDN_ LIMIT_REACHED

The maximum number of users for this API Key has been reached

LTK_SERVER_FEATURE_ NOT_AVAILABLE

Feature not available in this country

LTK_SERVER_FEATURE_ NOT_SUPPORTED

Feature not supported

Building and Running the SearchKit Example App

SearchKit_SampleApp is an example application provided by Comtech, that demonstrates various features of the Android SearchKit SDK. The following sections describe how to build and run the SearchKit_SampleApp example application.

Importing the Project

The following steps are performed to import the SearchKit_SampleApp project.

  1. Click Open existing Android Studio project, from Studio Welcome Screen. If another project is already open in Studio, from the File menu, select Open.

  2. Browse to the path androidSDK/sample/SearchKit_SampleApp, select the option SearchKit_SampleApp from the drop-down menu and click Ok, as shown in the following screenshot.

ImportSearch
Figure 7. Importing the Project
  1. Click OK in the Gradle Sync dialog, to auto configure the Gradle wrapper for the project.

  2. After Gradle sync is completed, SearchKit_SampleApp and the libraries can be seen in the project explorer, as shown in the following screenshot.

SearchKit_SampleApp
Figure 8. SearchKit_SampleApp Libraries in Project Explorer

Building and Running the SearchKit_SampleApp

The following steps describe building and running the SearchKit_SampleApp.

  1. Before building the project, set the value for the API key. Go to com.locationtoolkit.SearchKit.sampleapp.common.Credential.

  2. Replace your_server_token highlighted in the following screenshot, with the API key assigned to you by Comtech.

SetAPISearch
Figure 9. Setting the API Key
  1. Run the SearchKit_SampleApp to explore various search features. The following screenshot shows the main screen which has the available search options.

Mainscreen_Search
Figure 10. SearchKit_SampleApp Main Screen

TroubleShooting

While building or running the SearchKit_SampleApp, if you get the following error, disable the Instant Run located under Settings of the Android Studio.

Caused by: java.lang.IllegalStateException: Unexpected constructor structure.

Go to File → Settings…​ → Build, Execution, Deployment → Instant Run, as shown in the following screenshot. By default, the highlighted option in the screenshot is enabled. To resolve the error, you need to uncheck the box and disable it.

InstantRun
Figure 11. Disabling the Instant Run

Appendix: Search Category Codes

The following table describes various search category codes available in the Android SearchKit SDK.

Table 3. Search Category Codes
Category Code Category Code

Restaurants

AE

Houseware Stores

AKU

American

AEA

Office Supplies and Stationery Stores

AKV

Burger

AEOA

Wholesale Clubs

AKX

Bars and Nightclubs

AEC

Photographers

AKAA

Brewery/Pubs

AEOB

Photography Store

AKAB

Wine Bars

AEQJ

Children’s Clothing Store

AKAC

Chinese

AED

Men’s Clothing Store

AKAD

Coffee Shops

AEE

Women’s Clothing Store

AKAE

Fast Food

AEF

Shoe Store

AKAF

Indian

AEG

Pet Store

AKAG

Italian

AEH

All Health Care

AN

Sushi

AEOC

Dentists

ANA

Japanese

AEI

Hospitals

ANB

Mexican

AEJ

Pharmacies

ANC

Pizza

AEK

Chiropractors

AND

Seafood

AEL

Physicians

ANE

Vegan

AEOD

Dermatologists

ANEA

Vegetarian

AEM

Family Practice Physicians

ANEB

Barbecue/Southern

AEYA

Internal Medicine Physicians

ANEC

Californian

AEYC

Obstetricians and Gynecologists

ANED

Filipino

AEYD

Ophthalmologists

ANEE

French

AEYE

Pediatricians

ANEF

German

AEYF

Other Health Practitioners

ANEH

Greek

AEYG

Medical Laboratories

ANF

Hawaiian/Polynesian

AEYH

Nursing Homes and Residential Care Facilities

ANG

Jewish/Kosher

AEYI

Other Outpatient Care Centers

ANH

Korean

AEYJ

Psychiatric and Substance Abuse Hospitals

ANI

Bagels

AEOE

Specialty Hospitals

ANJ

Doughnuts

AEOF

Opticians and Optical Centers

ANK

Bakeries

AEOG

Optometrists

ANO

Argentinean

AEOH

Eye Care Centers

ANL

Brazilian

AEOI

Emergency Rooms

ANM

Peruvian

AEOJ

Urgent Care Clinics

ANN

Latin American

AEYK

Entertainment and Recreation

AB

Middle Eastern

AEYL

Nightclubs

ABM

Moroccan

AEOK

Casinos

ABB

Sandwich/Deli

AEYM

Conventions

ABC

Spanish

AEYN

Golf Courses

ABD

Steak House

AEYO

Movie Theaters

ABE

Thai

AEYP

Museums

ABF

Vietnamese

AEYQ

Amusement Parks

ABN

Cajun

AEOL

Amusement Places

ABO

Caribbean

AEOM

Parks

ABP

Bistro

AEON

Zoos

ABQ

British

AEOO

Aquariums

ABAC

Continental

AEOP

Stadiums and Arenas

ABR

Finnish

AEOQ

Performing Arts/Live Theaters

ABS

Grill

AEOR

Bowling Alleys

ABT

International

AEOS

Fishing

ABU

Russian

AEOT

Hunting

ABV

Snacks and Beverages

AEOU

Marinas

ABW

Breakfast

AEOV

Race Tracks

ABX

Chicken

AEOW

Ice Skating

ABY

Ice Cream

AEOX

Paint Ball

ABZ

Tapas

AEOY

Wineries

ABJ

Irish

AEOZ

Gambling

ABAA

Malaysian

AEPA

Comedy Clubs

ABAB

Fusion

AEPB

Banks and ATMs

AA

Creole

AEPC

ATMs

AAA

Creperie

AEPD

Banks

AAB

Pastries

AEPE

Currency Exchange

AAC

Indonesian

AEPF

Check Cashing

AAD

Fondue

AEPG

Public Offices and Services

AF

Chilean

AEPI

Police Stations

AFI

Azerbaijani

AEPJ

Courts

AFA

Baltic

AEPK

Libraries

AFB

Belorussian

AEPL

Police Stations

AFC

Caucasian

AEPM

Post Offices

AFD

African

AEPO

Schools

AFE

Australian

AEPR

Colleges/Universities

AFF

Austrian

AEPS

Fire Stations

AFG

Balkan

AEPT

Travel and Tourism

AL

Belgian

AEPU

Airports

ALA

Bohemian

AEPV

Tourist Attractions

ALF

Canadian

AEPX

Tourist Info

ALG

Dutch

AEPY

Historical Sites

ALD

East European

AEPZ

Landmarks

ALP

Hungarian

AEQA

Bus Stations

ALB

Maltese

AEQB

Car Rental

ALC

Polish

AEQC

Parking

ALE

Portuguese

AEQD

Train Stations

ALH

Scandinavian

AEQE

Car Service

ALI

Southwestern

AEQF

Limousine Service

ALJ

Surinamese

AEQG

Taxicabs

ALK

Swiss

AEQH

Airlines

ALL

Turkish

AEQI

Travel Agents

ALM

Logging

AH

Ferry Terminal

ALN

Hotels

AHC

Rest Area

ALO

Bed and Breakfasts

AHA

Personal Services

AI

Skiing and Ski Resorts

AHD

Barbers

AIJ

Campgrounds

AHB

Beauty Salons

AIK

R V Parks

AHF

Copying and Duplicating

AIB

Resorts

AHG

Laundries and Cleaners

AIF

Vacation Rentals

AHH

Mailing and Shipping Services

AIG

Shopping

AK

Churches

AIU

Department Stores

AKC

Synagogues

AIV

Grocery Stores

AKD

Temples

AIW

Malls and Shopping Centers

AKH

Mosques

AIX

Clothing Stores

AKI

Places of Worship

AII

Pharmacies

AKE

Automotive

AC

Retail Shops

AKF

Gas Stations

ACC

Sporting Goods

AKG

Auto Parts Stores

ACE

Convenience Stores

AKB

Auto Repair Shops

ACF

Book Stores

AKA

Oil Change Shops

ACG

Food Markets

AKJ

Tire Shops

ACH

Antiques

AKK

Auto Dealers

ACB

Florists

AKL

Auto Clubs

ACI

General Merchandise

AKM

Car Washes

ACJ

Hardware and Building Materials

AKN

Truck Stops

ACK

Liquor, Wine and Beer Stores

AKO

Motorcycle Dealers

ACL

Variety Stores

AKP

Auto Body Shops

ACM

Music Stores

AKQ

Truck Rental

ACN

Newsstands

AKR

Smog Inspection Stations

ACO

Lawn and Garden Stores

AKS

Electric Charging Stations

ACP

Furniture Stores

AKT

Note

For more information on all the Android SearchKit APIs, their respective classes and methods, see SearchKit Android API Reference Guide.