Você está na página 1de 372

r

r
r

Copyright Information

kony

Copyright Information

Copyright 2012 Kony Solutions, Inc. CONFIDENTIAL

r
r

This publication is in copyright. No part of this content may be copied, reproduced, or translated
in any form or mdium without the prior written consent of Kony Solutions Inc.

To obtain permission to reproduce the information (text or graphics) contained in this course
material for any purpose, submit the specifics of your request in writing to Konyvia the e-mail
address traininq@konv.com

"

Table of Contents Day 1


Basic App Building Components
Introduction to the Kony Architecture
Kony Studio

Creating a New Application and Form

Introduction to Skins

Managing Image Resources

Quick Preview

Introduction to Layout

^E Module - ScrollBox Widget


Text Wdgets (Self Study)

kony

Your Workstation

Sixteen workstations - ws01 through ws16

8GB MacBook Pro

Wireless network

Parallels VM - runs Windows

Two Disk Partitions

Macintosh HD - OS X 10.8 (Mountain Lion)

r
r

>

BOOTCAMP - Windows 7 SP1

Kony Studio & Platform SDKs preloaded

r
Copyright20t2Kony Solutions, Inc. CONFIDENTIAL

kony

After boot

kony

Log in as 'student' with admin rights.

Start Parallels Desktop

Parallel Desktop Icn is Kept on the Dock

Click to start

kony

Kony Studio

Eclipse with KonyOne Studio installed in C:\

C:\KonyOne5.0.02 contains KonyOne Studio.

kony
KonyOne5.0
re with

Burn

New folder

ame

_KonyOne Studio_insta!laticn
Ant

IOS

KMAPJBOSS

KonyOne_Studio
KonyOne-Se rver
video widget samples

81 eclipse
jij) KonyOne Ser.'er (Stop)
^ KonyOne Sep.er(Start)
>'- KonyOne Studio
r

Memcached

^5 Uninstall

OS X Desktop
The Dock also includes Xcode

Xcode 4.5 with OS SDK 6.0

r
*

kony

Write Once

Run Everywhere

All Devices

kony

The KonyOne Mobile Architecture

kony

Mobile Application
Tablet

Mobile Browser

IBM WebSphere, Oracle WebLogic, Apache Tomcat, JBoss

r
Kony Native App

kony

Native Application Composition

r
*

The application components and the userwritten code modules are compiled and
JavaScript code (bytecode) is generated
for the following:
Ul Components
Non-UI Components
User Defined Components

Code

]</>|

JS to Native Bridge

, --%

(V
c
c

This bytecode is interpreted by the VM on the


mobile devices to run the application.

Copynght2012Koi

UJ

Native Libraries

Overview of the IDE - KonyOne Studio

kony

The KonyOne platform provides its own development environment - KonyOne Studio.
KonyOne Studio:

is provided as a self nstallable binary.

is a complete Integrated Development Environment for designing and constructing


mobile applications to be deployed on the KonyOne platform.

provides the ability for the developer to perform all of the required activities from visual
Ul designing, coding, data integration, application building, emulator testing and
deployment to servers.

>

Basic IDE Layout

kony
Open Documents

Navigator

Kony Perspectives

ST'-T""-"!"'
-

H,

!!

Object

Application
List and

components

Emulators

LJi
Form object hierarchy

Consol

Widget Palette

jl/

Kony Studio Plug-ins


There are the Kony Studio plug-ins for each
platform as well as plug-ins for various IDE
features (help, debugging, etc.).

kony
E Applications 2 fe Navigator
i

~Lq3 HeloWorki
0 forre (2)
C mobrie (2)

The plug-ins are copied in your KonyOne


install_directory\KonyOne_Studio\plugins
folder.

To change plug-ins versions:


1
2.
3.

Stop Eclipse.
Replace plug-ins.
Restart eclipse.

Pkjgn llame

5.0.0.GM

S.O.O.GM

S.O.O.GM

5,0,0.GM

Jj -Naovecodegen

S.O.O.GM

0 La Core

5.0.0.GM

ij LaBaseScts
@LuaLfl

S.O.O.GM

g| La 1*32

5.0.0.GM

S.O.O.GM

isl Lita Documenlabon

5.0.0.GH

jej LaLoggev

S.O.O.GM

|3 La Debug LaunoSer
3 La Debug Core
0 La Debug U!

S.O.O.GM

>Tetet AnoVwd

B ..-.::; Pkjg-n
| Android

Versin

:. -Kony Studio

.','-HrdPartyJars Plug-*i
V-Kony Codegerwator
i'v'-KonyHetpPbg-in

i-.Kafikberrv&jJME

- Koiiy Platform Ptugin Detaifc

5.0.0.GM
5.0.0.GM

5.0.0.GM
5.0.0.GM
S.O.O.GM
5.0.0.GM

BTHnOent

S.O.O.GM

Sspa

S.O.O.GM

t/Desktop Web

5.0.0.GM

Building Applications

kony

Applications are built by:

Creating your forms (individual screens on the device)

Populating forms with all the Ul elements ("widgets")

Writing code to do things

Creating the "looks" for all the Ul elements (we cali these "skins")

Integrating into various data sources

Building and packaging the application

We'lljust start at the beginning...

10

Creating a New Application

kony

:.i<wi.

/toa*

*WWVt

|1

aam

Kony Apphcotion

m a

ilr.TKxtntrr.^B'jvKjt. |j*.Xruf
""*""

*>*r.

~-l.~,

g UMPI

..-
Cr.-,.
i# <h1 JD XI

-4.JKW

_,

".* si

Sm

. Bl* .,

^-,-.;.'-r:

.'

"

K-

Creating Your First Form

kony

Forms within an application are categorized under "mobile tablet and desktop channels"
separately.
Cuati; a Ni Furn

GD Appkcabons Si >C- Navigator j

B (^ HdoWorid
B B forms (0)
\J taUett
rp

v deskt i

Copy

v popups (C

i V tmplate

Refresh

33 ai. modules (
S si resource*
53 *a. servtces ( ~

UtiSties
- Impon i

faExoort

Debug As
VaSdate
Team

Compare With
Restore from Local Htory

Your new
Form

r
11

Creating Your First Form (cont.)

kony

You can set the form nature to either native, Static or Dynamic

(3 HclloWorld

G3Apptcabons 3 x- Navigator

? frmHome 23

U fotms (1)

[fg HelloWorld > ff^ forms | mobile ^

K mobile0)
frmHome

\) tablet (0)

Indicates the

app start-up
form

B tjjHeJoWorld
B@ forms (1)
I B < moble (1)

9 tablet (0)

Copy

" desktop (O] XDelete


S S5 popups (0)
Retame

Ctrl+C

Delete
F2

El t tompiates (0)

| </ Native

ffl at modules (1)

{/ web_module (0 ^ Fork
* resources (10) ~

a -i services (0)

HTML5Static (Hybnd-Mixed mode only)

HTT^L5 Dynamic (Hybrid-Mixed mode only)

*-Rel"a

Creating Your First Form (cont)

-i

kony

The Form
=

tool is NOT

'

WYSIWYG -

it's a layout
that will be
used to

""sr

genrate the

...

actual Form

you'll see in
your App.

The new Form is empty and does nothing by default.


Need to add the Ul elements to start creating some functionality.
Ul elements are called "widgets".

There are 3 types of forms: Native, HTML5 Static and HTML5 Dynamic.

12

Palette - Widget Inventory

Following are
different types of
widgets:

Containers

Basic

Advanced

Mobile Web

.> Palette

* Container Widgets

< BasicWidgets

C^HBox

OButton

QTab

QTabPane
rvfT VBox

Advanced

Add a widget by
SeleCting it and
dragging onto the

.. Palette

0fl6 Basic Widgets

^-Advanced Widgets
nina* web Advanced

t>

.1-Palette

>

* Container Widgets

i* Container Widgets

(H]Form

ScrolIBox

t>

ko **
V Base Widgets

W Advanced Widgets
, i," Advertisement

'io Calendar

A Browser

v- CheckBoxGroup

23ComboBox
gg DataGrid

tai Camera
tm Hz Image Strp2

Image2

l||!] Image GaHery2

Labe)

$Kap

Line

ObjectSeIector3D

unk

ListBox

Phone

l PickerView
\\ Segmenta

Meniiltpm

<" Switch^

"- Advanced Widgets

,(, Mobte WebAdvanced

.: Palette

^ Moble WebAdvanced

bj

fe Container Widgets
oBaseWidgets
%vAdvanced Widgets

f Mobile Web Advan... col


O Vadeo

Copyright 2012 Kony Solutions, Inc. CONFIDENTIAL

Widget Properties
J

l,

'

'

'."'.

'

25

kony

....

*-

'

"

13

Widget Properties - Render

kony

QL3

i~ MetoWo...j /Soaper...

MuntlmiT

.!. "**
P (k-ffO >W.'.lvO-*lM

B Lr-General

id

segmenta 104557599518

isVisibie

true

renderer

<Pfione:tjue,Android:b-iieTT

0 >v<

WH i 1^ Pjot *ew ap*)


P Teueh

P Q (*wnc
P

retamStects faise

< va;

rov.'Template t-tone

7 a*S**-,4.0nd*t>.'

P iwnioucn

secbooHea* ftone

P B .YnttM

t; iir Data
masterDate

- I

pHM

P # ot

ftot Defined

*WI
1' ItaKitrr.

P Q Mane
P ... *n*t
P ? KaKttaMT) ft.B1

Appearance

ooentabon
mafgn

BOX_LAYOUT_VERTICAL
Edt

padding

Edit

Stepixets) (443,200)
vadth

hoght
Si (%)

200
(100,54)

utdth

100

height

54

sho'.vSaoba faise

viewType

SEGU!_VIEW_TYPE_TAB...

groupCefe

faise

O 11 AlC>wr.'

screenLeveK faise

btodcedUISb StanDefaults

seiecbonBeh- SEGU_DEFAULT_6EHAV...

S Gtt layout
layoutAfcgnmBOX_LMOJTJUGNJH...

-: fe s^n
rowSfcn

Used to identify on which devices/thin


client versions this widget will be shown.

iMOgetSkjn Shn Defadts


Sbn Defadts

rowFoojsSkii SkmDefaUts

Widget Properties - Common vs. Specific

JA
kony

"Wioet.., H -r_HefaWo... /saaper... Q


:Property: |

IHiMiBbIi
3

id

bulto 104S57599S20

eViaWe

true

renderer

Phone: true. Andrwd: true...

Lr- Appesrance

ATdvetAlnjniT VWKETJUGNjCENTK
contentAbon. CCxrrBJT_ALIGM_CBTS

Eroand (App {htitrue, vt:fabe)

ffl

S<re(piefs} (446,26)

Si

Si(H)

(100,13)

dtsplayText

true

mafffn

Edt

padding

Edt

Common properties:

Shows properties that are common across all

pressedSon 5fcinDefaUB

devices.

blodedUISt 51xi DefaUts

showProgres true

5 0l Stan
skn

StanDefauHs

fbOJsStan

Skn Defauite

Device specific properties:

-. > Event
orOck

Not Defined

El urPhone

gtovffeet faise
El i~ Moble Web (Phc
extemalURL
subrr-tURL

preOndiGys
postOnoW;

Shows properties unique to a device.

Shows properties that may be common to

more than one device allowing each device

to be configured separately.

14

Building an Application
:

'

kony

'
i-

.3

a" -"
0'

o*

"

o**<
G

O*
O* ..,

Build Options

kony

The build process creates new resources from the existing resources, updates the existing
resources, or both.

Build process generates JavaScript code for the following application components:
> Ul Components: forms, popups, and widgets.

Non-UI Components: skins, services, service definition file, Project properties,


intemationalization content.

User Defined Components: user-whtten JavaScript code modules and custom


services.

The generated JavaScript code of application components and the user written code
modules are then compiled during the build process.

For ALL Platforms:

JavaScript code is converted to executable binahes and the application is packaged.

These binahes are executed by the JS Engine on the mobile devices whenever the
application is launched.

15

Build Options (cont.)

kony

Single Page Applications (SPA) -

ASingle Page Application (SPA) represents a special type of web application in which
all of the HTML, CSS, and JavaScript files necessary for the application are retrieved
with a single page load.

The page neither re-loads automatically during user interaction with the application, or
transfers the control to another page.

The application requires server interaction only for retrieving data

KonyOne Platform serves the devices with a SPAversin of the application using the
device detection logic.

The platform falls back on the tradltional Mobile Web platform for devices that do not
have HTML5 compliant browsers.

Once the first page is downloaded, a SPA behaves the same way as that of a clientside model application.

Build Options (cont.)

kony

This platform covers a wide spectrum of devices available in the market.


These include:

Phone 4.0 and 5.0

Android 2.1 and above

BlackBerry 5.0.x and above

Pad and Android 3.0 tablets

Windows Mango 7.5 and Windows 8

16

"

Build Options (cont.)

akony^

For Hybrid Applications (Wrapper & Mixed):

Hybrid (Wrapper) A web application packaged within a native application shell.


Can be installed on the device or put in an app store just like a native application.
Contains only HTML5 (static) forms and no native forms.

All Static forms will be packaged in the binary.

Mixed -

A mix of some native forms, some static forms and some dynamic forms.

Can be installed on the device or put in an app store just like a native application.
All the native forms will be converted to JS Bytecode.

Whereas, all static forms will be a packaged in the binary and dynamic forms will
be downloaded at run time from the server.

Build Options (cont.)

kony

Both the Mixed and the Hybrid (Wrapper) will be executed in the web with SPA architecture.

Note: An application can be either a native, Hybrid (Wrapper) or Mixed. Henee selecting
one option in the IDE automatically disables the other two.

Clean and Build:

Ignores any problems in the previously built state.


Deletes all the existing resources related to build (files created in "temp" folder) and
builds the application from scratch.

Use Cases:

On updating Eclipse with new Kony Plug-ins,


Before releaslng a build to QA team or Client.

17

XA

Build Options (cont.)

kony

Build (Incremental):

Uses the previously built state and applies the modifications to the resources that have
changed since the last build.

JavaScript code would be generated and compiled for all the components modified by
Developer.

Use Cases:

On making few changes to one or two forms/pop-ups.


Adding/changing a skin, internationallzation keys.

Build (without Clean):

Builds the application for all the build-related resources without deleting the build
resources that were existing earlier.

JavaScript code will be generated and compiled for all the application components.

Use Case:

Building the application for a different platform.

Build Options (cont.)

>

kony

Valdate:

Validates the application for duplcate Form ames, Skin ames, and Widget IDs.

Reports errors if any duplicates are found.

Use Case:

After creating required forms for a module n the application


Mobile Web Optimized WarArchive (For Production):

This option creates an optimized war file by applying minifieron the generated files.

Creates the <ApplD>-local.wari\\e in following path:


<Workspace>\temp\<ApplD>\build\wap\build\
This war file can be used to test the application by placing it in respective server.

Publishing an application will still crate a war file from files present In webapps folder.
Note: You must build the application using other options for thin client before using this
option.

This build option is for creating builds for Staging and Production environments.

18

r
r

Build Options (cont.)

X-

kony

Valdate Render for Mobile Web:

This option is mandatory on importing an application targeted for thin client to Kony
Studio versin 5.0 from Kony Studio versin 2.5, 2.6 or 3.0.

Checks if there are any widgets that have been previously rendered off and if Mobile Web
has references to any of those widgets. This option is useful when you are upgrading to
KonyOne Studio from earller versions.

Checks if there are any references to widgets In the code that have been previously
rendered off for thin client.

Using this option will crate a file with references for widgets rendered off for thin client:
The file ame is: RenderedOffWAPWidgetsReferenceslndication.txt

Can be found at:

<workspace>\temp\<AppName>\output\

These references should be removed from code for thin client for the application to work
without any exceptions.

AA

Build Options - Executable Path

kony

Following table lists the path to the executables created in build process for various
platforms:
Executable

j Extensin
iPhone

KBF

Android

apk

Path to executable

<workspace>\webapps\<appd>r\kbf\

<workspace>\temp\<AppName>\build\luaandrod\dist\luavmandrod.ap
k

Windows 7
Blackberry (Storm &
Torch devices)

Blackberry (Other
Families)
Thin Client

xap
cod

cod

<workspace>\temp\<AppName>\build\luawnmobile\windows7\WP7Ma
ngo.xap

<workspace>\temp\<AppName>\buld\luaj2me\blackberry47\dist\<app
d>-bb-<JDE_Version>-storm.cod

<workspace>\temp\<AppName>\buld\luaj2me\blackberry\dst\<JDE_Ve
rson>-<Family>-<appid>-bb.cod

<workspace>\temp\<AppName>\build\wap\buld\<appd>-local.war

Note: For Phone, KBF is extracted into the Xcode project inside mac machine.

19

V*

Application Build Men

i*

kony

Select the target channels by clicking in the check boxes.


Plug-ins that are not installed will show as disabled options.
ECE

p a ~- _j o
i
O""
s Q ^p^.-

o*. *
O
D

. .*

rj

o*
D
D

O*' K r
o

>a

( t "

O*

r b-

_^J

The output is the complete installer file for installing the app on the device (except OS
where objective-C source is generated - needs to be built in Xcode).

Testing the Application


Once you've successfully built the application, you can
test it using any/all of your installed emulators.

kony
"5 HebWotidSkins 0, Emulators 23 j
H-3 Emulators;
3

=D
A

Android

B y_ Mobile
VT3

If the build was successful for a device, then you'll.see

a big '-/ next to those emulators ndicatlng that you

> Tablet

X GalaxyTab

can run the App.

y
E 1 &t

Devices

Blackberry

S ? V4.2
ffl-5 V4.S
B 5* V4.7

If you didn't select a device or an error occurred, you'l


see a big X next to those emulators.

a ?r vs.o

BB-9700
B 5 V6.0

/ BB-9800

Double-click the emulator to launch the app in that


emulator.

Windows

B Native

Sf Windows Phone Mango


X ProfessionalV6.0
X StandardV6.0

Note: For Phone/iPad testing, the process is different.

B {'/ **
;-/ Windows Phone Mango

*f Windows Phone 7

X WtfidowsPhone6.5

20

BlackBerry Simulator Notes

kony

Native apps connect to the internet. For mobile web, you'll need to run the MDS service:

Launch MDS by:

Start -> Programs -> Research in Motion -> BlackBerry Email and MDS Services ->
MDS

For most models, the app will be Installed n the device's Download folder. Navigate there
and click the app to start it.

When the simulator starts, you'll have to go through all the initialization stuff...just cancel out
of everything.
"

Each JDE package comes with several simulators.


To add a new model, rlght-cllck the BB node in the
emulator list, and then select the /4dd command.

i-

Windows

* Native
V WindowsPhone Mango

BlackBerry Simulator Notes

kony

You'll typically want to test BB on several devices.

By default, the emulators ship with all the same port so you get a conflict if trying to run
more than one emulator at once (Bold and Storm, for example).

To get around that, open the corresponding emulator's .bat file and edit the port.

Cjt

j\

Orgarwe "
-

Computer - New Volume (D:) BlackBerry JDE 5.0.0 - simulator SjOpen

Favorita
x.Downbads

- _ Recent Places

Print

Bum

1Date modified

ame -

Debug

Q 9000 - Hotepad

Mj}

Java

File Ectt

Format

Type

| Size

.1
-]n|x|

View Hdp

Desktop

B \t trenes

.43] 1Searchsl...

New folder

E J Documente

_90G0

' J' Muse

"^9550

5 h-; Pictures

_ 9S50.bug

S f Podcasts

^95S0

fledge.exe app=ivm.di 1 ,handheld=9000


, session=9000 titTe="BlackBerry 9000 5imu1at<)r'
app-param=DisableReqistration 'appparam-ivmAlxConfigpile:9000.xml pin=0x210000 )A

21

Android Emulator Notes

kony

On the emulator, you must clickthe Android Men to continu the load process when
prompted.

The App will automatically start after that.

Youcan cise the App and it will be installed on the main programs page on the device; you
can click it to restart the App.

You can configure command line options when running the emulator:

Right-cllck the emulator and select Edit.

Enter the command line options.

Reference: http://developer.android.com/quide/developinq/tools/emulator.html

Note: No need to re-launch emulator after re-build -just double-click the emulator again. It
will load the new versin into the running emulator.

Creating a New Android Emulator

kony

The Android SDK provides tools to crate new emulator types/instances.

In the Android SDK folder (C:\android-sdk-windows by default) run SDK Manager.exe)

Crate new emulator configurations using the New button.

Adds t mulato' to Mobile

In Kony Studio, right-click the Android folder and select Add.

22

Android Emulator Notes

kony

The Android SDK provides a Telnet tool that allows you to simlate various device
functions.

In a command window, enter telnet locaihost 5554 to crate a connection to the


running emulator
Note: 5554 is the default port for the emulator.

You can now send various commands to the emulator (Ex: send a text message, configure
the battery level, etc. Explore the help function to see available commands.)
EB Telnet locaihost

c^

E3

k^fl
^^^^^^H
cr

i ' i t u I-I4i

ujiBJ.i

Tml
2j^B

ffl^^^HI

|^9

Windows Phone Mango Emulator Notes

kony

Double-click the emulator.

App will auto-launch.

If you quit the app or hit the

key, the app can be found on the next page of the

emulator.

# HelloWorld
<9 /Q Internet Explorer
flk Settings

r
Note: No needto re-launch emulator after re-build -just double-click the emulator again.

23

Windows Mango

kony

You can now build applications targeted for Windows Mango platform using Kony Studio.
In addition to the existing Windows 7 features following additional Features are added to the
new Windows Mango platform.
Enhanced Camera Capabilities

Native with Crop - The native camera Interface with the additional provisin to crop
captured images.

Custom with Crop - Acustom camera interfacewith the provisin to crop captured
images.

Custom with Easy Capture - Acustom camera interface which can be tapped anywhere
to capture, and saves a thumbnail, instead of the full captured image.
Ability to use Windows Phone 3D model selectors

Small Alrliner Seat Selection - Selectlon of a single seat location in a single-aisle


aircraft.

Large Airliner Seat Selection - Selection of four seat locations in a twin-aisle aircraft.

Usage instructions (in 3D mode)

Tap on objects to select/unselect them

Press and hold down on a selected object for a walkthrough.

Windows Mango Additional Features

'i'

kony

Keyboard customizations

Select a keyboard layout from the list of keyboard layouts (Default, Chat, URL, ... etc.)
Tap on the text field at the top (where it says "Try keyboard") - this brings up the
keyboard with the selected layout.

Enhanced device information

Connectivity information

Memory status

Other information

Accelerometer capabilities

Orientthe phone at various angles and watch the acceleration components change in
real-time.

Shake the phone to switchthe light bulb on (itautomatically goes off again after a
couple of seconds).

24

AA

Windows Mango Additional Features

kony

Ability to intgrate with Windows Phone Tiles capabilities

Demos dynamic creation and removal of a secondary tile to a particular page in the
application (the Live Tiles demo page).

The application is able to detect that it is launched from a Live Tile, and can execute
custom logic as required.

Ability to intgrate with Bing search (using Kony appservice/deeplinking techniques)

Phone Emulator Notes

kony

The Phone emulator runs on the Mac so we need to move the compiled code over.

On the Mac:

Open a Terminal window and navigate to the IOS application folder.


Navigate to the gen folder and enter the following command:
perl extract.pl

http://<windows

IP>:<jetty-port>/<app ID>r/s?type=iphone

Navigate back to the application folder and enter the following:


open VMAppWithKonylib.xcodeproj

In xCode, build and run the project to see it on the emulator.

25

iPad Emulator Notes

kony

The iPad emulator also runs on the Mac


On the Mac:

Open a Terminal window and navigate to the IOS application folder.


Navigate to the gen folder and enter the following command:
perl extract.pl http://<windows IP>:<jetty-port>/<app ID>r/s?type=ipad
aaa

Navigate back to the application folder and enter the following:


open VMAppWithKonylib.xcodeproj

In xCode, build and run the project to see it on the emulator.

Testing the Thin Client / SPA

kony

In Kony Studio, the Jetty server will host up the generated mobile web site(s).
You can use the emulators OR physical devices to test the mobile web site(s).
Jetty unit testing URL is:

http://<dev_hostname_or_ip>:< jetty-port>/<app_name>/p

The Kony Jetty HTTP port number defaults to 8888, but may be modified in Ecllpse's Kony
settings. Go to:

Window -> Preferences -> Kony Dev Studio -> Embedded Server and change the
Jetty port number

You can also use Firefox or IE to browse the site. Firefox lets you change the user agent
so you can simlate the various device browsers.

26

Setting up the App to Build

kony' i

Whenever you crate a new application, if you're building for Android, then you have to set
a few things up(its optional).

>

Rlght-click the Application; and in the Applications view, select Properties.


On the Native App tab, go to Android and give it a
package ame (format of com.<whatever>)

Opw feroce Qetr*s<jr>

Alij.Ir. ni-un Piupetlie

Own

itffH** UnyfefvcrPetM. Iix* *t MK-p NXff

iWKrti.itiMl(l;; Mee* Art

PutM

I.SaiDet/*

.rji:.ir.:

) t<r>> lavyt leiecm

btUrtUuta-

( Uw ItKJMn Pre'unKf

Uilewt

tJtnBcrt

r
Rrtttvc * en ioM HtWi...

Ka

XA

Exercise - Helio World

kony

Objectives

Be able to crate and build a new Kony Studio project.

Be able to run an app on the emulators as well as test it for the mobile web.

Concepts

Applications are built by creating forms (screens) and populating them with user
interface (Ul) elements, called widgets.

Applications (apps) can be built for a number of mobile platforms (channels) from one
specificatlon.
Procedure

Crate new Kony Application.

Crate a new mobile form.

AddaLabel:

Drag a Label onto the form (from the Basic Widgets sectlon of the Palette).
Set the Text property to "Helio World"

Save your project.

Build and test on all devices and mobile web.

Copyright2012KQ

27

Exercise - Helio World (cont.)

kony

mmmnv.K'\.*r*f>m<!'!-m>m'~r*rr

*inal

<JM.

^iN

%.Wknr

CBenemceDelMan

Mi

XOWfW

-.nw

BUkl 0>> mriL,.

CveH W ir UAJ
Hin H*iW tr cok Are

1, Me^*iMn*iSon; Un)

*". (

- u>m< uji-m

.1 Mrtojwne sm O cu-sn :

fr^ttO1*'* "TTTlJ P^t"

j^

28

Exercise - Helio World (cont.)

kony
JDJXJ

na : irTnn:rz=^^^m^^mmam
Channels
i

Beta 6: Mobile web is available onty for La

>e*ctr>s r>yt trar i bto.3bef-v dt"B osnf^/ecr w>4 >e*: f tbttrS bufl ame.

Phorm MurdOuimH

Tjihi-tOwwt

r
O*1

MjWev.eb

v Photv

*? LWK!

15 0 "WC-3

I? KTH 5 '^jn ftijr ,tti (VA;

- n1*-' *?<>

C O nJ

j, Ntr. *CP

C r?Ant*ad

Q: Trh (Tnu-

- *".' 6.0

*f Njvttvrry tOflnrtieW.m

P ItanTnirh

- "-' DF e.

Jtar*hrTT

0^-' (VflrtV.

Orf

r Brj
Vl*tX

"J.-oid

..:

r *, Mwret

*?- !>*) ira;

Q:'' 00

v OertksWeb

5? |>Eju(.1>-.tjoW.iJS{U5)
P

'

*n*oe;

ueittiMa*Owe(

*f-'eri(aioo;

<> eK.De-.<.c9.

**n*tneof 9 P*Jferrnt of Mitre * Htnd V M*eU&tmt zm be Blta: w.i pon of ane ..0 <* rie-O.* *+ons u tekcted. ii^kJ **J *<*4**rte opcent we 4
'n ck ^ vw pUtVtns of mif>L^oMe Web er Mae4 <^^^

29

*.

Skins

kony

Skins are used to configure the look and feel of a widget when it Is rendered on the form in
an application.

Skins are created for each widget type allowing you to adjust things like:

The color scheme

The border scheme

The font

The image, if applicable

Custom CSS for thin clients

etc..

Skins can be forkedXo crate device/channel specific versions.

Every widget has a default look (i.e. when no skin is applied) that can't be changed.

Kony studio ships with many default skins that CAN be edited if necessary.

30

Everything can be Skinned

kony

All Ul Widgets can be skinned - Buttons, Labels, ComboBoxes, Forms etc.

Many widgets can display an image as part of the skin (e.g. Form backgrounds and
Buttons)
r

Many widgets can have more than one skin applied for the various "states" of the widget.

A Button can have a Normal and Focus skin. The Focus skin will be displayed when
the user touches the Button or puts the "cursor" on the Button.

A Segment (showing a list of data) can have a Normal, Focus AND Altrnate skin (to
apply to every OTHER row of data to help crate a visual effect of separating the rows)

It is VERY important to crate and use Focus skins. This becomes an absolute necessity
on non-touch devices.

Note: This includes the use of images. You'll need mages to represent the focus state as
well as the normal state

Kony Skin Defaults

kony

Kony Skin Defaults let you specify common skins for widgets in different states (normal and
focus), across the application.
Q Ap*-atrl5 3 i C-

ftmHor

r Krld

L^

i-rl ENew Aoplcabon


r=

Copv

8HB

i e* kc* r* ea u

Open Service Definitwn

Q-,

Ctrf+C
Deiete

*"

Refresh

ffi

Refresfi Worfcspate
i :<e*ise -et Boette u:: K>Sk

! 'je.'!3o_-o>>.*-a<ii:Noa

Chance Development Languaoe to tus'

*vcy* >ri i iiSf-iMJi

Pubtti
BukJEARSe

J <nu

rtoi:NaQ

Prooerbes

ji M0C*e.-.fiocjWW:'S*r
Jl ^rfxx BMaciU! :!>*

Jetty Web Server

* mMhIl.^MWi

App Men

,1 '.fWlf.lnWto ' ShT

0Ou** i^inttmatjooaiisbcint.lSn)...

#^ >/- c*lNm*l

U tibes

~e\Zfc
...

Integrare Thrd Party

jl 1i. .*/.--.<;
f tVut3cn : itt*tt.\n

Import

f *r%cr>; Cvui duttsn 5J- '*


Otffl jj i)
,1

ti^Ewmrt

Compare W.tti

Restore from LocalHetory...

31

XA

Kony Skin Defaults

kony

Skin Defaults providesthe ability to give a uniform look and feel for the widgets across
various platforms.

Widgets in the application will default to skin set in Skin Defaults. The skin can be
overridden on that widget's skin properties

-'..

You can edit which skin is used in the

Skin Defaults for any/all widgets.


W"IWi: f*

You can change, edit, crate, delete

In i r* fcn
/i *:ji >r | >*Son

and fork skins from the Skin Defaults


view.

?*IMo&*rri

J ro5fcri:M*x

Your skin edits will be available

| l'.* l*we
fcltm- lllliP|
n:n i v* **n*

i Si^nnjtceMaSMP'NeSan

throughout the IDE (i.e. you can pick


that new skin from the widget
property directly if you want).

l 'Sksetefu!

HsSW"

\^p/

OKHHMWm

. r,^.amn>Nivtrin't9CP

-7r h*v ivii.u>.,

, Sbi bstatynal

< tVW < *ne>

,*f tt*1: UtKH*i

The preview window gives you a

..

ilfcui

at CHM

first-order idea of the skin's

>.- {vnmwf

appearance
iuiE.r

*
J

Skins View

kony

Skins view lists existing skins grouped by Widget type.


Using skins view, we can Add, Refresh and Clone skins for any widget.

, HeoWorldSkins S3 | O. Emulators|

= n

Current Application Theme: [default

Theme: |defauit
f\ Advertisement

'' GSSSB
I9

Button

+-VAdd__

S i btnFocus
IB-SS'' btnNormal

J E ,

id ,4

Current Appkaton Theme: |default

~3

,-!HdoWorld Skins SZ \O Emulators j

/: HefloWorid Skins t I<> Emulators

1 Ll i < _

Refresh

-v

^L*J

Current Application Theme: default

~B vjjtj

Theme: default
\ Advertisement
'- Button

m -*, b.VB

B $' Calendar

* 'ti Q

5! S Calen X<***

B i Camera

iS Ci/ clone *>

IS Carne f F^

0 Chart_2D_3D

>

Chart_2D_3D

B |^j CheckBoxGroup

Ep vj ChedBoxGroup
S 'j ComboBox
B {H DataGnd

S kj ComboBox
S a DataGnd

E {^jForm

S {^j Form
0^ HBox

E^HBox
Cu HlmageStrip

B C WmageStrip2

zi

"\

Chart

Rename

:Chd ^Refresh"

' i Como -

B Hj Datat .jCopY

ff) 03 Form ~
n
._ ."S Clone Al
k HBox_

B Cu HlmageStrip

Si S HlmageStrip

B Cu Wmage5tnp2

I WmegeStrip2

32

Adding Skins

kony

Each skin needs a unique ame - unique for ALLobjects in the App.
Configure the various attributes.
Click Finish to save your work.

There always has to be a default skin defined if you're going to fork the skin.
/-. Hdk>Worid Slans 3 O Emulators

$j U t 8

Currem flptobon Theme: |defsult

Theme: |default
Ji Advertisement

iimiiiiw

jj

^'1

_-j v | X|
*_

fjy^
di

noa

i 81 Q|

Refresh

-- Chart_2D_30
ChedSoxGroup

BataGrtd

Form

AA

Adding Skins - Fonts

kony

These attributes of fonts can be changed through skins:

r
r

Color

Transparency

Size

Weight - bold or normal, for example

Style - none or italics, for example

You can select fonts for individual platforms on Rich Client, Thin Client and Tablet
separately.
-T.rr-MVM5.--V.rt.

AJd^>..

'"i

ene ['y*
(N*M j-OT

Mtn ['-"

zl

j|

IM. .M.CS

f=-

Copyright 2012 Kony E

"

33

AA

Adding Skins - Custom Fonts

kony
5

W
-- - I

_i

"3 F

kkony6

Skins Files

The skins are stored in XML files in

themes folder at the application root

All non-forked skins are in


skin.xml

All forked skins are in thelr

respective XMLfile (e.g. iPad forked


skins are in the ipadskin.xml
file).

ame

| Date modified

|Type

bgimages

8/28/2012 1:09 PM

customv.idgets

8/28/2012 10:54 AM

Re folder

diatogs

3/28/2012 10:41 AM

File folder

forms

8/23/2012 10:41 AM

Fe folder

jssrc

8/29/2012 4:33 PM

Rle folder

modules

8/28/2012 10:41 AM

Fe folder

resources

3/29/2012 4:33 PM

FSefoider

services

8/28/2012 10:41 AM

Fie folder

templa tes

8/28/2012 10:41 AM

Fe folder

8/28/2012 10:41 AM

File folder

File folder

i r^
web_modufe
__ .project

8/28/2012 4.11PM

PROJECT Fe

i bu**

8/29/2012 4:31 PM

PROPERTIES Fe

_bud

8/28/2012 10:41 AM

XMlFSe

fonrtcon

8/29/2012 3:54 PM

PROPERTIES Fe

8/29/2012 4:32PM

XMLFile

HelloWorldmapptngs
._. konyplucitns

3/29/2012 4:31 PM

XML Fe

g luajrtdge^jirtjnfij
j middeware

8/29/2012 7:49 PM

PROPERTIES File

8/29/2012 4:32 PM

PROPERTIES Fe

Lj projectprop

8/29/2012 4:17 PM

XML Re

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^b

34

r
Forking Skins
S. HeJGWoridSkre S|Q.BnutotDre|
-

J|. t $

Current AppfcabonTheme: default


Theme: default

kony
;--

-:;

^1

1i*. Adverbsement

r"

; B~

_^J _j_XJ

22(jO.Emiatars:

0 Cl Button

:::. i ,4

i * b3"t

pealen XDelete

ffl A carne Fo*


^chart

Rename

1*

^g01^ Refresh
r~*

*|

Theme: default

_^J v| x|

(j Adve tisement

S S Comb "
S S, OataC .. Copy
ES O^Fonn~

-.

CurrentAppkabonTheme: [default

_^_

0 Gl Butto
6 b

sil , Phones - Nabve AppChannel


3 .Phone

i iancuis

" Clone A

Andr-,

*:! Bladberry

*; ni HImageStrip2

Q Windows Phooe

Note: Unchecked devices will use

the default skin - you can


always choose "Fork" again to

| Phones- MoMe WebChannel

# HTML SSPA Phone


<"? HTML 5 SPA Android

: HTML5 SPA 8lad*en v

^ Server adetione

add new forked skins for other

*~9 Server sde Androd

devices.

List will show already forked skins as


disabled options.

Double-click the main or


forked skin to edit.

r
Cloning Skins

kony

Cloning Skins is a useful option when you want to replcate the forked skins for other device

type.

Cloning copies ALL the forked skins for one device type and creates one or more copies for
the selected target device types.

K^^Hi^^^^HiaTaTaTaTaHMaB

.-! HefcWorkISkmi 3 |Osfc|


Cunent Appkabon Theme: default

*|

Theme: default

riw

jjAdvertisement

5 %

Refresh

S^CalEB
$ i Camera

*"3 Chart_2D_30
6 [3j CheckBoxGroup
il' ComboBox

* 9 DataGrid

$ jsS Form

This exampie shows copying ALL the iPhone forked skins and creating forked BlackBerry
and Android skins.

"

35

Native Skins

-%

kony

Kony Studio also provides you the ability to use the nativeskins (skinsthat give the native
look to the widgets) on certain platforms.

Native skins are only available for Phone and Android.

Native skins are currently only available for


the Button and TextBox widgets.

r-

Using Images in Skins

3
a

kony

You can also use images for skins.

To do this, you must select Image n the skin editor Style drop-down on the Background tab

mrr *"^

*.-

- I l|

All the images must be present in the Resources folder of the project. The IDE supports
PNG and JPEG formats for the images.

You can use the Browse option glven in the skin editor to plck your image.

Note: the image may be stretched depending on the layout scheme being used

36

"

-i*

Using Images in Skins

kony

-.

.
1*1 s**

".

3ST
*~

e^

i
immvnmm-

Emtm
AHdacni
adamftan

__

^_
7

mtogeuR>.:|

-.

=^1

^^

i rc*i 1

"

"

37

AS

Themes

kony

Theme s a set of skins available at the application level.


Themes let you specify common skins for widgets in different states (normal, focus, and so
on).

Themes allow you to package the skins in a way that resemble a particular user interface
or branding for a particular set of users.
For example, all the Goldcustomers will see all the buttons n Golden Yellowcolor.

Themes allow you to personalize the look and feel of the application for the end users. For
example, the users can choose between a green theme or a blue theme.
You can define your own themes in Kony Studio or download themes from the network (a
specific URL) and use them in the application.
A theme, which consists of a set of skins, is represented as a file containing a JSON string.
The JSON string has the key-value pairs in which the key is skinid and the valu s JSON
string that represents the skin.
Every application should have a "default" theme (stored n the in the default theme file).

Deleting or overriding the contents of this file will lead to undesired behavior. KonyStudio
does not allow the developer to delete this theme. Allother user defined themes can be
deleted.

Themes View

kony

KonyOne Studio provides a default theme that has a set of skins defined for all the widgets
within an application.

The skins in this theme can be applied to widgets to get a different look and feel for the
widgets.
The Themes View is embedded in the Skins View. A drop-down list indicating the current

theme appears in the Skins View. you can see theme to which all the skins are associated
with.

I fea _i A
heme:

deault

~ Popup
=' RadioButtonGroup

RichTect
SooMBtt

Segment

all the skins usted here


are associated with the

default theme

*' StgnatureOpture
-vf Midei

CTab
K TbPane
';

TtrtArea

cff TortBox
K VBt
jS TrtleBV

"~

38

Themes View (Cont.)

kony

KonyOne Studio also provides you to crate themes and associate skins with them.
When you crate a theme, it is created using the default theme as the base. All the skins
available in the default theme are copied to the created theme.

The IDE allows you to add, modify, rename, copy, fork, clone, and delete skins within a
theme.

KonyOne Platform provides a set of APIs that allow you to perform different actions with
themes.

Note: Any changes you make to the skins within a theme are limited only to that theme.

Themes View (Cont.)

kony

Steps to crate a Theme


CertificatinExSkins Z O. Certificatin ExEmulators

1.

Navigate to Skins View.

2. Click Add New Theme icn ( . ). Current Application Theme: default


3.

Enter a ame for theme in


the New Theme window and
click OK. A new theme with the

specified ame is created.


All the skins in the default theme

are copied to the new theme.


4.

Select the new theme n the

Theme: default

4L

q Advertisement

CS Button
ib Calendar
>

i New Theme ^k

M3!

Enter Theme ame:

MyTheme

drop-down list to see a list of


the skins in the new theme.
OK

Cancel

Copyright 2012 Kon y Solutions, Inc. CONFIDENTIAL

"

39

Themes View (Cont.)

kony

Delete a Theme

KonyOne Studio provides you with an option to delete a theme.

>

When theme is no longer used in the application.

When you delete a theme, you must be aware that all the skins associated with that theme
are also deleted.

>

Click the Remove theme (Xjjcon to delete a theme


Current Application Theme: | MyTheme
Theme | MyTheme
^ Advertisement
::' Button

Note: We can only delete themes that we have created manually. We cannot delete the
default theme available in the IDE.

A'

Theme APIs

kony

The theme APIs provided by KonyOne Platform have the following capabilities:
1. Defining new themes.

2. Applying the theme to the application or only for the current session.
3. Switching the application from one theme to another theme dynamically.
4. Deleting and loading the skins for memory efficiency.
5.

Provisin for custom meta data.

Important Considerations

The default theme is the base-point for new theme.


If the referred skin does not exist both in the current theme and default theme, a runtime
error occurs.

When a skin is referred, the IDE searches for the skin in the order of precedence)

Current theme

Default theme.

Note: You cannot dynamically modify the skin attributes.

40

Theme APIs (Cont.)

jl/

kony

kony.theme.setCurrentTheme

This API allows you to apply a speclfied theme to the application at runtime.

kony.theme.createTheme

This API enables you to crate a theme.

kony.theme.isThemePresent

This API allows you to check the existence of specific theme in the application.

kony.theme.getAIIThemes

kony.theme.getCurrentThemeData

This API returns all the themes available In the application.

This API returns the meta data of the current theme in the application.

kony.theme.getCurrentTheme

This API returns the current theme that Is applied to the application.

kony.theme.deleteTheme

This API allows you to delete a specified theme in the application programmatically.

Import/Export Theme

kony

You can import as well as export themes used in an application to re-use them across
different applications

In the Skins view, click on the export I import theme icons and you'll see the Import Export
window.

When exporting, Select the location click Wexf and select skins to be exported. Kony Studio
will use Theme.zip as the filename. Import is the reverse.
.

HatriMISfei

41

aa

Images - Resource Folders

Each Application has resources directory to hold images.

By default the resource folder contains these subfolders:

kony

build - contains images copied in from properties in the app properties dialog

common - contains all the common resources, i.e., resources that are not platform
specific. This folder also has screen size specific folders:
Images240

images320
Images480

mobilerichclient- contains subfolders for each rich client platform.

mobilethinclient- contains subfolders for each thin client platform.

tabletrichclient & tabletthinclient - contains subfolders for each tablet platform.

desktop_kiosk - contains subfolders for kiosk platform.

In the platform specific subfolders are the images specific to that platform.

Each of the platform specific subfolders can subfolders for specific device types and/or
screen sizes and/or screen resolutions.

42

XA

Subfolders in Resources

kony

Any resource common to all platforms should be added in "resources/common/'


Any resource common to all platforms but specific to a supported lcale should be added n
"resources/common/<locale_ CountryCode>/"

Example; "resources/common/en_USf

Any resource specific to a platform should be added as below n the respective sub folder:

Thin Client: "resources/mobilethinclient/"

advandroid, advpalm, bjs, normal: Following subfolders are valid

<locale_CountryCode>

Images320

Images240

Images240/<locale_ CountryCode>
Images320/<locale_ CountryCode>
Images480

Images480/<locale_ CountryCode>

advblackberry, adviphone: Following subfolders are valid:


<locale_CountryCode>

Subfolders in Resources

kony

Any resource specific to a platform should be added as below in the respective sub folder:

Rich Client: "resources/mobilerichclient/"

blackberry: Following subfolders are valid


<locale_ CountryCode>
large
large /<locale_CountryCode>
small

small/<locale_CountryCode>
storm

storm/<locale_ CountryCode>
pearl3g
pear!3g/<locale_CountryCode>

2me, phone, winmobile, palm, symbian: Following subfolders are valid


<locale_CountryCode>

43

1
Subfolders in Resources -Android

Anyresource specificto a Android rich client should be added as below in the respective
subfolder of "resources/mobilerichclient/android':

Resource specific to a lcale should be added n "drawable-<language>-r<Region>"


sub folder. Y letter s used to differentiate Regin.
Example: "drawable-en-rUS"

Resources specific to screensize can be added in "drawable-<screensize>" subfolder.

Possible vales for screensize are "small", "normal", "large" and "xlarge".
Example: "drawable-normal"

Resources specific to orientation should be added in "drawable-<orientation>"

subfolder. Possible vales for orientation are "land' and "pon".


Example: "drawable-land"

Resources specific to Resolution/screen-pixel-density should be added in "drawable<screen-pixel-density' subfolder. Possible vales for Resolutlon are "ldp!\ "mdpf,
"hdpf, "xhdpf and "nodpi'.

Example: "drawable-hdpi"

Subfolders in Resources -Android (cont.)

kony

A resource specific to combination of these factors should be placed in a subfolder created


as per the following precedence rules while naming the subfolder:

lcale/language and Regin

screensize

orientation

'

screen pixel density

Some Examples:

"drawable-en-rUS-land' applies to US-English devices in landscape mode.


"drawable-port-hdpi"applies to a devices n portrait mode and having hdpi pixeldensity.

"drawable-en-rUS-large-land-hdpf applies to US-English large screen devices in


landscape mode.

Some Invalid Combinations:

drawable-en-rUS-hdpi-large-land

drawable-land-en-rUS

44

'

44.
"

Subfolders in Resources

kony

Any resource specific to a tablet platform should be added as below in the respective sub
folder:

Tablet; "resources/tabletrichclient/"

Pad; Following subfolders are valid:


<locale_CountryCode>

andriodtab; Subfolder structure is same as mobile Rich Client.

Managing Resources

kony

c*

When managing images, there are fwotechniques:

1. Creating copies of the exact file ame in the platform/device specific subfolders:

You'll specify that file ame in the various Kony Studio image dialogs.
The platform will search for that file in the following order:
The device specific subfolder
The platform subfolder
The common subfolder

Clean and simple approach


2.

Using all unique file ames:

In the various KonyStudio image dialogs, you'll specify the exact image to use for
each platform.

Best to have a good naming convention to keep things manageable.

45

Image Dialogs

kony

Specify the default image


JQJxJ
Add New Skin

Q Stan namecannotbe empty


Default image must be provided.

Name:

Ailil Uwm BUl

Wm

Widget Type: [~

*!*. |
Mr*^<

Background

*" ** " " a

Font Border MtateWeb CSS

Stvie: 132
*

r Image-

Mob*e Nabve App MopJe Web Tablet Chame) DesfctiWWosk Channe

i-

.11

na

"

'

Optionally specify images for each platform


i - ----.-.

Conventions for Images

3 '~ I

kony o

Only PNG and JPEG image types are supported by all platforms.

There are certain naming conventions that will ensure complete cross-platform support:

Only use lower case alphanumeric characters and underscore (and '@' for Phone)

Filenames must start with a letter.

No uppercase characters - including the extensin.

No keywords such as "continu" or "break" or other Java/Lua reserved words.

For Phone retina display, add "@2x" to the filename.


For example:

You have an image hello.png

You want to also provide a higher resolution image for the retina display.

Name your high resolution image hello@2x.png

In the image dialogs, select hello.png. The platform will build in and use the specified
im ages.

46

"

"

XA

Quick Preview

kony

To view changes to images or skins, you need to run your App.

Do you really need to compile the whole thing just to see how it looks on any given
platform? There MUST be a better way, right?

Yes! Quick Preview allows you to preview the current form n any emulator. Instantly!

You need NOT build the entire application to preview how your form would look on various
emulators.

VERY helpful when doing fine tunlng of look/feel on a specific form

No code will be executed - preview is non-functional.


-

Quick Preview displays one form at a time.

"

47

Using Quick Preview

kony

Before using the preview feature, you must do a full build (creates application build folders).
Once t's built, you'll then do a quick preview build.
rj.*y.y^s :* fe.* ,.

#^:3<5S?!:*

3ff^?^

Build in quick preview mode by:

Clicking the button


...Or...

Right-click in form window.

I..,I....H

ln^

Choose Preview.
Unob move / resrze

X Dtete
firrdWidgel

i:

KxtArc.V

W Preview...

)
Alt4oubleC6ck

EdrtProcer-bes...

Double Ock

You choose the build platforms using the normal build screen.

Using Quick Preview (cont.)

kony

After the build, you can now view the preview on the emulator(s).
Right-click the emulator (don't double click) and choose Open in preview.
This is required ONLY to launch preview mode
: Helio'.'.'oild Skins *J

Emulators

Emulators

Android

K Mbile
sa t j

- -JTablet Hj Edit
y Ga(ff^ Open inpreview^^
j " Blackberry
) V4
3 V4S
3 V4.7
)f BB-9530
X BB-9500

3 V5.0
3 V6.0
4

Windows

You Are In Preview Mode


Setect Men ->QuickPreview to get (he
form preview
Select Men >Settings to configure
preview spltmgj

Native

^ Window; Phone 7
X Windows Phone 6.5
X Windows Phone 6.0

O Web
A v Kiosk'Desktop
<tf Windows 7

Q Palm

48

A
kony1

Using Quick Preview-Android Emulator

Once the emulators are running, after making any changes to the form, you can directly go
to the emulators and see the changes.

rigH]Oa:52PM|

You Are In Preview Mode


SetKlMe

"

Original screen.

click men on emulator.

see your button changes


after clicking Quick Preview..

Quick Preview Info

JA
kony

Building in Preview Mode will add a men tem to the app called Quick Preview.

It actually creates another lighter versin of the application which will only have the form
and its referenced code (skins etc.).

Keep the emulator running during the quick preview steps.

For Thin Client preview mode:

Open the browser on an emulator or device on the same network as your Kony Studio.

Navigate to the URL below:


http://<ip address>:8888/preview/p

where <ip address> is the IP address of the host computen

49

1
iPhone - Preview

kony

Running Preview mode on the iPhone is similarto running the app. You'll have to launch
the Preview mode app and this will let you see your preview screens
To run Preview mode, on your Mac:

Open the VMAppWithKonylib.xcodeproj file.

Now build the application for simulator on Xcode


and run the same by selecting Preview iOS
Device with some PhoneliPad simulator.

Enter the IP Address (IP address of the Kony


Studio Windows host)
... and the port number in the Initial screen on the
emulator.

Click Preview.

Double click on the screen to bhng up option to refresh


(for when you've made changes and want to see them)

Exercise - Helio World Made Pretty

kony

Objectives

Be able to modify a Ul and render it on various devices without rebuilding the app

Be able to crate custom "skins" for the same Ul on different channels

Concepts

Skins are used to configure the look and feel of a widget when it is rendered on the
Form n an application.

Skins can be forked to crate channel specific looks.

Procedure

Crate a new default skin for the Label widget.


Name it whatever you want.

Make it: transparent background, blue font, make it BIG (200%) and tallo.

Fork the skin for iPhone and BlackBerry

For iPhone, make it a two color vertical gradient (light yellow to darker yellow), a
dark font (non-black), normal size (100%),and the border completely rounded.
For BlackBerry, make it a two color vertical split (use similar yellows as for
Phone),black font, sort of blq (150%), with no border.

50

"

Exercise - Helio World Made Pretty (cont.)

XA

kon-i

Applythe skin to your label, save, preview build and check your work.
-

Add a button:

Crate a skin with an image (don't forget to put an image in your resources
folder).

Fork the skin for any device and use a different image for that device.

Apply the skin to your button, save, preview build and check your work.

,1

51

Objectives

kony

By the end of this module, you will:

Understand the dynamic nature of Kony's Layout Manager

Understand how to crate a Form using the Kony Studio IDE

Understand Container Widgets and their role in composing a Form

Understand how Margin and Padding affect the appearance of a Widget

Understand the bastes of Widget skinning

Layout must "Run Everywhere"

kony

Layout in Kony Studio begins as a general speclfication.

Layout can be tuned by channel (Phone, Android Tablet, etc..) (and often more finely
grained than that).

A precise layout is computed at runtime on the device.

1
52

XA
-

Widgets

kony

Widgets are the building blocks of the Kony user interface.

i Palsite
1ft Container Widgets

Container Widgets:
QHBox

Containers are the scaffolding that control how


components are arranged.

Container,

StrollBox

widgets

_Zl Tab

Q TabPane

Form: Hlghest level container.

0!VBox

HBox: container to arrange widgets horlzontally.

V Baoc Widgets

VBox: container to arrange widgets vertically.

Button

'\'Calendar
\, CheckBoxGroup

Component Widgets

]_" ComboBox
S3] DataGrid

Components are the "leaf" elements of the Widget


hlerarchy.
In this module, we'll work with these Component
Widgets:

ImageZ
,b: Labe)

Componen
t widgets

Line

iV. Link

% ListBox

y Menultem

Button

TextBox

'

Label

RadioButtonGroup

1 RichText
- SMer

AA

Essentials of Sizing

kony

Widgets are organlzed in a hierarchyj- QiAtmr

{H} M "

[F1fcrm ImsOtifLotitn
y

Components within Containers

HOe. - hii<263STllWl
Di/tcn tjtr.JieOjrreMLeertien

iab*f - ib*G03171105

t-J HBw.- hbviAiWimOjll


! leitBu<-tri.pUiU>
Bulln - L-t-iij ji

Containers may be nested

BullL'" - LtrieirUi

i Mcnu BurUm
l.ltnu CnU:ncT

The hierarchy is depicted n the Outllne View

EveryComponent Widgetinstance has a Preferred Size (more on this soon ...)

A container instance's size is based on the Preferred Size of its children and the container's
own properties

53

Adding Widgets

a, ^"
kony
; ttrnHonie i ;

The mobile app will


display the widgets in
the order they are
placed on the Layout
Manager form

"

[ EJHdbWorkJ

forms amobl \ frmHome.Id

[ *> Prevtew... !

.> Palette

>

% Contaer Widgets

Hefo World

" Baste Widgets


TextBoxZ

1 Z Button 1
g Calendar
iv CheckBoxGroup

uyow

By default, the
horizontal size of a

L_

child in a Form is

Image2

100% of screen width,

La bel

while height depends,


on the specific widget

Line

Link

jfjstfiox
=i Menultem

When placing them on


the Form Designer, by
default, they stack
themselves snug
against the top of the

Men

Form

ai RadioButtonGroup

^ RichText
-0 Slider
tu TextArea2
V_ TextBox2

r:r Advanced Widgets

<Mobile Web Advanced

Form - Layout Rules Summary

kony

A Form stacks children vertically -

Height based on the preferred height of each child

Vertical space you might insert by resizing widgets is ignored

The Width of each child is set to the width of the device's screen.

54

r
XA

Spacing in the IDE - Spacing at Runtime

'i '

kony

You can re-arrange and/or change position of the existing widgets by drag-and-dropping
them

You can also leave vertical spaces between them...

BUT the Layout Manager will remove that space for you and by app runtime everything
is snug at the top

Run-time

Design-time

aifflS 9:43 PM

Lu

Space -

Tex:Box

No Space

HBox

kony

A Form stacks vertically; an HBox Is used to stack horizontally


Drag an HBox onto the Form...
frmHome

|Hj frmHBox U

tl HeloWorld > ^} forms l mobile ^ frmHBox.H hbox 101557599526

drag.

a"d-drop

Drop Widgets into it, monitor the hlerarchy in the Outline View.

HBox Sizing Rules:

An HBox s empty (has a (0,0) Preferred Size) until you add children.

The Preferred Height of an HBox is the Preferred Height of the largest child.

"

55

Sizing a Widget in the IDE

kony

You can resize a Widget using one ofthe eightgrips. Grips are visible when the widget Is
selected.
F=J frmPage2 :

--

-e-

-O

EijfrmPagt:;

Just click and drag to change the size.

HBox Sizing of Children

kony

When you drop in the first child widget, the layout manager sizes t to 40% of the HBox
width automatically.

You can manually resize it in the IDE.

=] frmHome

||=) frmHBox 23 j

"

(ElHeUoWorid - forms - moboe [H] frmHBox.kl EJ hboxl21225027428 L_lbuttonl21225027429

1O Preview... J

. Palette

1> I

1* Container Widgets

Button

>fTJasi<: WrdgeT^.

Button

O Button

To&lefKtaT
|v"| CheckBoxGroup

^3 ComboBox
ul DataGrid

|y rmage2
ik Labe)

Line

- Link

56

Horizontal Stacking

kony

Add a widget and resize to make room for the next.

Drop a Label into an HBox

Resize the Label

Drop a TextBox into the Hbox


and resize

r
Label

TextBcx

Button

Drop a Button Into the HBox

HBox Properties

x^
kony

The HBox's width is determined by the parent.

An HBox child in a Form parent will take on the width of the screen (as we discussed).

Each child occupies the Size(%).width setting within the HBox.

"Use Widget size %" property alters this behavior, but this is an advanced property;
always use "true" for now

...but how are children aligned?

mmmmfmm

57

XA

HBox Layout Rules

kony

Bydefault, Widgets will be sized based on the percentage specified In the properties of
each child.

Design-time
Run-time
Label

TextSca

9Hffl 11:18PM

Label
Button

Button

The HBox's height will be based on the Preferred Height of the tallest widget.

In this example, both the TextBox and Button are the same height.

Exercise - Crate a Simple Form

kony

Objectives:

Be able to crate a new Form with 3 widgets and configure t as the app startup Form

Be able to arrange 3 different widgets in a horizontal row

Concepts:

Container widgets control how component widgets are arranged in the Ul.

Precise layouts are determined at runtime and not during the layout phase in the IDE.

Procedure:

Crate a new form.

Stack three widgets in the form

A Label

A TextBox

A Button

Set this as the startup Form.

Build it for rich client Android, BlackBerry and thin client.

Use preview mode to view your app

58

Exercise - Crate a Simple Form

kony

Extend your layout exercise to include:

HBox that contains:

Label - with text

TextBox

Button - with text

UL

Inside a Widget

kony

Top Margin

Border width
,

Top Padding
O)

'5
i

>|

Right

Right Padding |

Left Padding

Margin

Margin

t*

Content

*>

Botom P

adding

1 r

Preferred Width

59

4\

Inside a Widget - Dimensions

kony

Margin -top, left, bottom, right set independently


Border- width same on all sides

Padding-top, left, bottom, right set independently


Content- Size depends on the widget type / font

Margin, Padding are widget


properties.

"Transparent"
Border width

Border width is a Skin property.

1 T0(iP0tl"5

'.

I
'

1
5
a.
"

"

Preferred Widlh

Margin & Padding

kony

Margin and Padding are controlled on a widget by widget based (including container
widgets).
BlrfHi Platluim

[j

|;w iwl

I,-

\**i,

C ^1.ll^i.Mt^
P TaXI

i*i,>m-m..i

il BHm

5 3 .wawanow

a; <

B'J

1: S i n r t . l C r M .

--

ag .,,...
a

F"3 =

..>..-:

O*.
o-'

D-r.^,
D

O*

*..

p
p

p
i
i

n.

J_

You can change individual settings...AND...apply them to some or all other devices.
Typically, you get it working for one device and then start appiying to other devices.
Use preview to check your work. http://developer.kony.com/updatesite

HH

60

r
4'

Margin & Padding

kony

Margin and Paddings can be specified in both percent as well as pixeis.


jal
owr- o-.:-tMt*jr.ii
o

lita

It |tg<|t,

lia* lam t

1-

Mmn

*my*i...
*m.ai..

am***..

,' KTM SM0F i*Qr opl (VA)

D'rf l=*Br-.i. 3*o&e.t

J
Di ..-*,-.

....

IT"- voad
Mwe:"^! on* jw "e-rienfl rtt* " ft wj-ed i iwdfl S twr oei w KM Mim

1 >ImI

Specify % to ensure a uniform look & feel with one set of margins and paddings across the
other platforms.

"

Margin & Padding

kony

There is also a global option for changing vales.

In the application context men, you can Replace or Copy margin/padding settings.

I-ilegal* Tr*tJP#tv

UvftdehiOKttvCwrOTl Wm

Cf*>

k~

i"-.'.,j '.

<

!=--

Oaw

'

=.-;

Easy way to perfect one platform and copy as starting point to the next.

61

XA

Margin & Padding (cont.)

kony

When do I apply Margin and when do I apply Padding for widgets in containers?

What if I really mess up my settings?


QH*3 10:50 pmI
hboxwlh padding:

Qgffle 11:09 PM
hbox with ridiculous padding:

Can't draw the

widgets properly
with errors
Ihboxwhere widgets have margin:
hboxwhere widgetshave imposslblemargins:

Way too much


padding above
Below, the A and C
buttons have

Easler to set padding in 1


place than margin in 3

margins of 22%
and 35% all the

way around

Extreme examples, but in very crowded layouts, it's best to be careful

The Expand Properties

kony

You can request horizontal / vertical expansin of a widget within its parent.

Think of it as stretched padding.

Setting h/v expand to true will not affect the size of any other peer widgets within the parent.

Note: Expand setting has no effect on thin clients.

iJJ"LJJlJ1JIJIJI"LJ-

62

Expansin Example

Two side-by-side Buttons in an Hbox

Left button: horizontal expand = true

Right Button: horizontal expand = faise

Widget width 50%

Widget width 50%

i:

! Button Text

Button Text

Again, think of expansin as "stretched padding".

i. *

Expansin Example (cont.)

kony

Expansin properties only affect that Widget, not peers.

Design-time

Run-time
'HJCl 4:19rM
.*bet

-.e^ax

HCquMOn

MEttpondOn

HtspjndOri

Htxpndcrri

Htoynaofl

Kony Studio

Here we have three HBoxes as part of a Form; each contains two 50% width Buttons.

Horizontal Expand settings are vahed.

For Buttons with Expand = faise, the size of the text controls the side of the content.

63

%A

Skinning

kony

ASkincan be appliedto a Widget to set border width, border color, background, ...

"Transparent" Margin

Skinning and layouts

kony

As we saw earlier, skins are managed via the Skin View.

Changing a skin MAY change the shape of an object which n turn MAYchange the layout.

Use of images or different border widths that are different for focus/non-focus state may
affect the layout.

Oh, and by the way, skins work with Containers, too, not just Components.

While working with layouts, skinning containers can help see your margin/padding effect.

64

Skinning vs. invisibility

kony

All widgets can be set to be visible or Invisible.


In layouts, an invisible widget doesn't exist!

If you want to make something LOOK invisible but don't want the layout to change (when
you make it invisible) use transparent skins.

For example:

you have 3 buttons at the bottom of the form where you can click one to "vote": Button
1 says "yes", button 2 says "N/A" and button 3 says "no".
For some questlons, "N/A" is not valid so you want to hide that button but KEEP the
other 2 where they are at.

Making Button 2 invisible will not work on all platforms - button 3 will scoot over to fill
the gap.

Solutlon: set the button's skin to a transparent skin (with no text)


All 3 shown

Button with transparent skin

Invisible button

r
V
kony

VBox
As the name mplies

A VBox is a Container that stacks children vertically.

Use a VBox, where needed, to switch from horizontal to vertical stacking.

In most cases, you can only embed a container within a container if you are changing the
stacking axis -

Correct:

HBox with a Form as the parent


VBox within an HBox parent

Incorrect:

VBox within a Form as the parent

65

XA

VBox Sizing

kony

Height rules similar to a Form -

Preferred heights of all children, stacked.

Width of all children will be the width of the parent HBox -

With specified Margin/Border/Padding added

Width of HBox (by default) is set by Size(%) property of the HBox within the HBox's
parent (usually a Form)

*.'.
kony

Where Are My Properties?

In order to see properties in the Properties Pane for a widget you have to select it.
It is usually difficult to select an HBox widget from the layout directly
!^jumPage2 1
.

The HBox s the fine red box

H)
Is easier to select your HBox from the Outline Pane
on the bottom left-hand crner of Kony Studio

i H Form - ftmPage7
a E HBox.hboxl5680706ooll057
O

Button - burtcnl568u706o61109

ifci Label - labell56807066oT1071

Once you select it, the Properties pane will show


the specific properties for HBox.

f-J TextBox - textfieldl56307066611075


*

Label - Iabell56307066611077

'{: TextBox - textfieldlS07066oT1079


O

Button - buttonl5o80706ooll081

G ' Men Button

| I Men Container

66

t 9

kony3C

Module - ScrollBox Widget

ScrollBox Widget
ScrollBox widget by nature is a container widget, to place
form components in horizontal or vertical direction, except
TabPane.

kony
.i Palette

* Container Widgets

[HJForm
HBox

Purpose:

ScrollBox

To place widgets in either horizontal or vertical


alignment, along with scrollable behavior.

DTab"
1^1 TabPane

vJVBox
Use cases:

To manage split view type of alignment of the form


components.

"S Basic Widgets


%?Advanced Widgets
(i Mobile Web Advanced

67

"

AJ^

ScrollBox Widget Properties

kony

ScrollBox can be rendered on all platforms.

Percent, specifies ifthe widgets must be laidout as per the percentage allocated size or as
per the preferred size. By default, the valu is set to be TRUE.
Name

Valu

General

Note: If the valu has been set to FALSE, then


Widget Layout's Direction can be set to

id

scrollboxlli331872023

Visible

iPhonenje,Android:trije,Blacl;berr>Ttru

renderer

left, center or right

Layout
fake

BOX.LAYOUT AL1GNFROM LEFT

l.t. ( !i-:.:u:i- mi'

_- Appearance

Orientation, specifies the way, the widgets


supposed to be stacked - horizontally or vertically.

margin

Edit

padding

Edit

Siie ipfcels)

(448,50)
448

width

Once the components have been stacked, its


orientation cannot be changed.

SO
(100,11)
width

100

height

11

BOX ^AVnUT HORTZOMTAI

Scroll Direction , as a property facilitates to scroll


the aligned components .

it'ollDirection

show5<roiibars

poition

enableScrollByPa
-,-- Scroliing Events
onReachingBegm rtg
cnReachingEnd

Container Height, Specifies that the height of the


box must be fixed as per the percentage given In
the IDE.

SCROLLBOX SCROLL HORIZONTAL


true

BOX.P05mON_AS.NORWM
fake

Nct Defined
Not Defined

onPull

Not Defined

OflPtlSti

Not Defined

Fned Height
<L ccntsintrHti-iht J>

ScrollBox Widget Properties (cont.)

kony

Position is used to align the ScrollBox onto the form at header or footer or segheader or
segfooter position of the form.
Stie (%)

showScrollbars can be used to enable

scroll bar while swiping the components


of ScrollBox.

enableScrollByPage can be used to


enable paging over the components in
Scrollbox.

(100,11)

width

100

height

11

orientation

BOX.LAVOUT.HOREONTAL

icrcllDirTtinn

SCROLLBOX SCROLL HORIZONTAL

<LT jfifiwSrrollbars
C! position ^
enableScrcllByPage
Scrolng Events
onReachingBegining
cnReachingEnd

try>
BOX_POSmON_AS_NORMAL
fal
Nct Defined
Not Defined

onPuil

Not Defined

onPush

Not Defined

. FixedHeight
containerHeight

In case of SPA based forms over Phone,

Android & Blackberry, Scrollbar can be


configurad with Scrollbar or Arrows in
terms of look and feel.

j- Skin
slcin

Skin Defaults

C..- SPA (Phane,Android.BlacfcberrvI>


leftArro.v

rightArrow
top Arrow
bottcm Arrow

Copyright 2012 Ko y Solutions, Inc. CONFIDENTIAL

68

Exercise - Matching a Design

kony

Objectives

Be able to design and build a Ul when


given a model to emulate.

Concepfs

This exercise will require the student to


understand margin, padding and
container widgets.

Use Preview mode to quickly view


changes as you prototype the Ul.

Procedure

Build the App you see on the right.

Use everything you've learned so far.

Great exercise to focus on creating an


app with a specific look/feel.

There is no "right' answer so how it


looks on all devices is up to you.

Use Preview Mode!

69

kony

Text Widgets
(Self Study)

kkony*

Label
Used for displaying text and as space buffers (no text).
Can be skinned to affect background, font color/size and border.

Unique Label properties:

lfi.W4

Alignment:This for alignment of the widget within its container.

Content Alignment: This is for the text inside the widget.

Long Text: Specifies if the widget can allow text which has more than 1500 characters

Wrapping (iPhone only): Specifies ifthe word or characters must be moved to the next
Une when you reach the right margin.
Word: will wrap only on whole word boundaries

Char. will wrap at any character to fill right to edge of label boundary

70

Link

kony

The only difference between a Link and a Label, is that the Link exposes a click event

By default the Link will display as blue and underlined.

You can skin your link, but careful! If you make it NOT look like a link, user will not know

Unique Link property:

onclick: specifies what to do when the user cllcks the link. We'll cover this in a bit

TextBox

kony

TextBox is used to capture user typed input.


The keyboard is automatically shown when the user puts focus on the textbox.

Most devices offer littlecontrol over the look of the keyboard pop-up and when It pops up is
controlled by the device OS. iPhone is the exception

Shown below are some examples of unique iPhone properties:


Placeholder (the faded helper text)
Label in keyboard
Keyboard Type

Keyboard type:

typcDefaut

Auto Capitaliza!en
Cise Button Required
Cise Button Text
Cese Button Text I18n Kev

typeUPl
typeNumberPed
typePhonePad

Left View Image:

-E

Enter your usemame

71

XA

TextBox - Properties

kony

maxTextLength: specifies ifthe user is limited to entering a certain number of characters

textlnputMode: general property with the following options:

TEXTBOX_INPUT_MODE_ANY: allowing any typed n characters

TEXTBOX_INPUT_MODE^NUMERIC: only allows numeric characters

onDone: The event when the user has dismissed the keyboard or put focus on another
widget

onTextChange : allow you to write code to do something AS the user is typing (autosuggest
text, for example)

Acouple of interesting platform specific properties. (Note: refer to the Kony Widget User
Guide for detalls on all properties):

Auto Complete: turns on/off the OS auto-complete/suggest feature when typing

TextBox - More Properties

kony

Allthe Platforms, except J2ME and baslc xhtml versin, expose the onTextchange event in
which we can write the event for auto suggest feature.
The onTextChange function cali will have 2 parameters passed in (widget,
changedtext) :

widget: the textbox widget that triggered the cali

changedtext the text including last character enterad

Auto Filter: (BB, Android and Windows Phone 7 only) The

vales you enter are matched against the f ilterlist and


possible matches are displayed.
f ilterlist is a textbox property exposed in JS. It is a JS
array of vales - by default it'll do a "starts with" search in this
array to find matches

Atlanta. GA IPKt

Atlanta. GA (FTY)
Atlantic. IA (AIO)

AHMltlC City. NJ (ACY)

F//fer Criteria: (Windows Phone 7 only) allows you to specify

atl|

how the f i l t e r l i s t is searched for matches. Vales

nclude: StartsWith, StartsWithCaseSensitive,


StartsWithOrdinal, etc

72

r
RichText
RichText control supports the HTMLtags to format text
The following tags are supported:
-

<b> </b> - to make the text bold


<> </i> - to make the text italic

<u> </u> - underllne of text

helio -.velromptoSSJH
training .
Cali xxx-xxx-xxxx (or support
post training.

<a> </a> - anchor text to display a link. Supports optional href attribute. href can be
URL based or can cali a method nternally.

<mg> </mg> - to display an image. Supports src attribute. src can be local image or a
URL based image. This tag is not supported in Phone.
<sub> </sub> - to display subscrlpt.

<sup> </sup> - to display super scrlpt.


<label style="color:#rgbhexformat"> </label> - Displays the text in the color specified.

<tel number=""> </tel> - Displays a telephone number on Native Applications.


<a href="tel:"> </a> - Displays a telephone number on Mobile Web platforms.

Rich Text (cont.)

4
kony

RichText has an onClick property that is triggered when a user clicks on a link within the
text:

The function cali will have 3 parameters passed in (self, linktext, attributes):

self: the RichText widget that triggered the cali

linktext: text of the link on which user has clicked or touched.

attributes: a JS object containing the attribute(s) of the link.

For example, if we populated a RichText widget with:


frmMain.rtLinks.text = "helio <a href = l>one</a> or <a href = 2> two</a>"

If the user clicked on the first link ( one ) then the parameters would be set as:
self. would be frmMain.rtLinks, the name of the widget

linktext: would be "one"

Note: Use this widget only ifyou have small amounts text as it will consume lot of memory.
For large amounts of text use a browser widget.

r
r

73

TextArea

kony

TextArea is a TextBox-like widget that is used to capture large amounts of text.


TextArea accepts things like carriage returns to somewhat format the text (on devices that
expose it -Android does not).

As you type text, each device reacts a bit differently:

Phone: the control will not grow In size, but scrollbar will appear iftyping goes beyond
control boundaries.

Android and BlackBerry: expands the size of the control to accommodate the amount
of text; the screen will expand if necessary.

Windows Mobile and Mobile Web: acts like a multi-line textbox. Itdoesn't grow in size
or have scrollbars, but the text will continu to scroll as you continu to type. However,
initial number of lines can be set using "No of Rows" property for Mobile Web.
TextArea is typically used to capture user comments or notes

Note: From a layout perspective, you can't control the initial size of the control It'll always
render the same size (height).

Button

i'

kony

Buttons can be created n all shapes and sizes using skins.

All buttons have a normal and focus skin - focus when the button is "pressed" or selected
(for non-touch devices)

Images for buttons cause the buttons to become the size of the image - an important
reason to have seprate images for each device.

When images are used and the text set, the text is overlaid on the image - important for
localizaron

In BlackBerry, there is an option to set the Image to 3 part image (in forked skins)

Using this we can set 3 left middle and right pieces of a button .

W^.
T,^- IimlHr

:-..

*_*-

.i,-..,.
'

This is useful when the text is dynamic and you want to increase the size of a button
based on the text size

74

A'

Button

kony

To set/get the text of a button in code, use the text property:


<form name>.<button

name>.text

Buttons have an onClick event. The specified function cali can have 1 parameter passed
n (eventobject):

eventobject: the button widget that triggered the cali

We'll cover how to write functions and respond to events in just a bit...

Note: If using images for buttons of odd shapes, make sure the background matches the
container background OR has transparency around it to let the background show through

Text Widgets - Reference

kony

Please refer section "4. Basic Widgets" in "Kony_Widget_User_Guide.pdffor detailed


information and all the properties of above discussed widgets.

75

kony

Beginning App Building

mmmmmmmmm

Table of Contents Day 2

kony

Debugging/Troubleshooting

Module - JavaScript

Kony Studio APIs

Dynamic Widgets

Kony Studio APIs

Module - Event Editor

Module - Selection Widgets (Self Study)

76

Basic Application components

So far we've gotten a taste at application building.

Next is to cover other basic elements for building applications ncludlng:

\'-

kony

Appiying logic in our applications - i.e. coding.

Once we start writing code, we'll need to cover debugging and troubleshooting

Connecting to data.

r
-

r
-

r
77

Logging and Debugging

kony

Kony platform provides different techniques for debugging the application.


Print statements - printing data/statements to the device SDK native log
> Useful for general debugging.
Good for long running workflows to view data.
Can be automatically excluded for production use.

Good for sharing debug info - easy to send logs to other people.

Alerts - using alerts to display data/statements while running the app.

" Good for controlling flow in development (using confirmation type - yes/no).

Good for mmediate feedback.

Bad for ntroducing lots of extra clicks.

Inline debugging - using breakpoints in code.

Most powerful for real troubleshooting.


Can choose to examine any data at debug time (unllke Print where you pre
determine the data to log).

II

Logging and Debugging - print()

ic

kony

kony. print (<text to print>) function of Kony JS API can be used for placing
debug statements in the device's log.

Below are some examples of using printQ function.


prints the message.

kony.print("Entered calclate Rate function")

kony. print ("final amount is > "+f inalAmount) - valu of the


finalAmount variable is appended to the message.

kony.print("result table is

>"+result)

will append a text versin

of the JS table object to the message - VERY useful.

Many device SDK loggers In debug mode print a LOT of data to the log - best use
something easy to find, e.g. kony.print( "$$$$$$$$$$$$$$$$$$$$ "+debugData) .

78

Logging and Debugging - print()

kony

Kony default debug logging is controlled by the Build tab n the application properties
window.

debug - will print all the Kony platform's nternal debug statements - VERY verbose.

relase - keeps Kony platform logging to a minimum.

Neither of these affect YOUR print statements.

To remove print statements from the application, select the checkbox "Remove print
statements in custom modules".

3 Project Pro|
Project Properties
Editproject properties

Application KonyServerDetails Build

App Settings NativeApp SplashScreen(NativeApp,SPA) MobileWeb Push Nctification H8N

Build: Idebug

Remove print statements in custom modules (Recommended setting for production relase)
Note: To avoid compilation issues please have the print statements in a single line.

Phone and iPad Logging


Phone and iPad log
statements are printed to
the Xcode consol

In Xcode go to Run ->


Consol to bring up the
consol

Print statements are inline

with Kony debug


statements:

Kony statements

Print statement

:iti--3i ti u

iti .,

ff...i .,, uiatM.ut.*.!:] tt,-Ttrrliri-lTi llt tt.arttailMM * Mhrttfti

...... .kmt iB/kim..w/ KVI'Hfili

mi

IDt'lllH r |'f liTff.ia. I.t.lti lui::>..iat,i-.,>

liutmu ifcrtu-.i >nt '--!

unto m

r ftniii) tailmnKi*t**twt

n.j.n.1 ijiij-.iiii'.'! . . . . v i l : mi,

.,.,., 1..,..., ... i . . n .-.

r
..(.. im.ii. mi hu; , lUf.fMWMaWatt >,* iinm >.!...
iilm ir;(ln)'t*i. !.-*..a

ni .1.it(>i i.<tk, ,-.-..,rr,,

i,.,.i|,i ,.,!(.

"""*"*T" r"J'\ ,*.T."Ti*'Il1l.mrilt* *"' "*** ,fT' t"<i*tihiii


mw*w

79

Android Logging

kony

Logs can be viewed by launchingAndroid's Dalvik Debug Monitor utility


Findthe utility at: C:\android-sdk-windows\tools\ddms.bat
B~0~,IM.

. gj
Mrtp

J-

IhM* 1VMHr^ Mp,^. Iww. V-*-:f'- Kl-f

MM..W

fe*

"MI

-;.ji .t

-i i'

1\U

.......

1'

-f-

AImom

lustra nitor IcmicJ.

<3>0

Log
Am

p.a

Mftugt

tj

QtaiMZi

..->

Sf.-ttl

>rra

J- 17 ott

;n

f**>d

!, - - t<mn>)T>.*Urii--lM#KHjU>ttiC*l>^w,'

ata i? o

35

lo -..!

-M1MU-

.'i*.

M-a I7rUJ..

JS
.

poftw^nuMuc*

rppvwMhwaMtA
hry

kmilutn

Imatf

X,

MB<MM

9KM>

tw*a ptjfc- >tfj m%***\&m*m<t**ttnCTfr HiiHUMMitfiTttvfKi *!*. i- j*r< n WM


T^*<Th^^V^]7)^WH17l:^lUn;ll^H.^^^:l^.)t^*.,^.,^v^.,.

Vl.aarl

' . - MU

IW

ItmMl

a miz.

ipliIMgWi^uIhm^
-txttfUNM

ttet-ci

m-Mihta.

.:

>Un4f

r>*Ttwd-.i mwiJJS JBMU U _77,Ta3ai97(:nKBi9 BONHbmim


AAAAAW.JC.XtiM tLS/,k\rhTTi\*\bd.;: *.<ttUMttV UDUb,TM..M

-a im&l.

J .--rr.

CC fr*J B et,ti K7iW ,m Wmi

wajMi.'.

y-**-

WWCW0CC8 Wgqg kwumiio T<u WtfBW | mMCT i +* i**. : *i*rr*t :'<

A . . m^hmwr 9 f,

>

ftr

Android Debugging (cont.)

kony

Logs are given different tags like StandardLib, WindowsLib. You can crate filters to check
for only specific logs (like only custom logs).

Time

UaJ

Log Filter

+ - !0 S N
fcateRto)

Filter Name: eustomlogs

pid lag

Message

06-0617:44:32332

749

WmdowiLib

Eitcutirg thernethod ndex IG param5[0]:Lu

06-0617:44:32532

749

WYndewsLib

Euting tht mfihcdindei:0

106-0617:4432552

749

StandardLib

Mknq thes(qmtnti30764:tjble.List ;[l:tibiei

by pid:

06-0617:44:32.562

749

StandardLib

filledthesgment!!

byLogleve): |tDebug_

06-0517:4432562

D 749 LuaSegUt

06-0617:44i3-.5S2

749

WmdowsLib

! 06-0617:44:32.552

749

WindowsLib

06-0617:44:32592

749

tuaFcrm

Setting dattSetOataO
Enecuting themethod indei11
Displaymg theform(rmThree
Freeing theform!!!! frmtwe

06-0617:14:33.772

749

dalvfom

GCfreed 1573ebieets / 76904bvt inI74ms

+& 1Loa.

(<(d m

by Log Tag:

StandardLib

ITI

|Cancel |

i!eustomlogsj!
pid

tag

Message

06-0617:4432322

749

StandardLib

entered the fill segment function

06-0617:44:32.552

749

StandardLib

filiingthe segment!!30784:table.L st :l:table.List:[] Map;(five=f.ve, tw =hvo. one=one. thiee=three, four=l

06-0617:4432362

749

StandardLib

fillei the segment!!

Time

80

"

Android Debugging (cont.)

kony

Logs can also be viewed using the SDK logging tool


Run it from a command prompt with C:\android-sdk-windows\tools\adb logcat

BlackBerry

kony

BlackBerry debugging is done via the JDE tool for each JDE versin
With the BlackBerry simulator open, do the following to launch the debugger:

Run the ide.bat file located at:

C:\Program Files\Research in MotionXBlackBerry JDE x.x.x\bin

In the men, go to Debug -> Attach -> Simulator

Ignore/dismiss all warnings that come up


-

You'll see a LOT of debug statements

To avoid all the system statements:

Compile app in Relase mode

Leave print statement turned on

"

81

%A

Windows Mobile

kony

Running the Windows Phone (7 &7.5 emulators) automatically brings up the Kony logging
tool:
Windows Phone LogViewer

a'isa

Windows Phone 7 log viewer


Thisapplication helpslaapp devetopers to valdate the actualoutpu:against
the expected output. TKs also helps user to see the platform errors or

kony
Filter the types of

J VM J --.form J User Jj Error J Information _. Wammg


LogTime

messages you see

Message

Message Source Message Type

7/5/2011 ;2:4836 PM Logserv.ee b started

Platform

User

User

User

User

SSSSSSSSS5SSSSS$SSEEEEEEEEEEEEEElected

" :;::.

124934PM catego^VYVYYYVVYVV^VYYY {[-11= abflt0200000".


I"name1 = "Audio &MP3-)

7/5/201112:49:34 PM

"-""APP INFO*""

View the log entries

SSSSSSSSSSSSSSSSSSEEEEEEEEEEEEEEEElected

7/5/201112:4937 PM cargo^YYYYYYYYYYYYYYYY ["id'] = "abcatOiOIOOO'.

("name ="Audio Systems &ComponentiT


7/5/201112:493" PM "

APPINFO

{]

^SS^SW.^^^WFPf^CFFFFFFFfl^.^

Remove Ssi;r;ted i;ern;- -Remove AlIJternsi


Log File Name

Physical log file

jCAUsers\Pco Recr!'\ApPDai\Lo:ar\Wp7Logs\7\5\20in24B47PM.txt

| C:\Users\Pico RecfcUppData\Lcaf\Wp7Logs\Best5uyRemix7V5\2011249

locations
Cper F: 3ei

Restan Log

Thin Client Logging

kony

The platform log statements AND the thin client logging are pushed to the middleware.log
file that can be found in your eclipse folder.

The log is a rolilng log spanning mltiple files where the latest logs are always found at
middleware.log (where middleware.log. 1 is the previous log and middleware.log.2 contains
data before that)

middleware.log tile is generated using log4j and the configuration file for the logger can be
found in the middleware-log4j.properties file (D:\Workspace\middleware\middlewarebootconfig\)
middlew3re-log4j - Notepad
Re

Edit Format

?&

^iDjxJ

View Hdp

*log4j.properties*-- start add for service wars deployed

logj. logger.com.kony=iNFO,filelog4j.logger.com.konylabs=DEBUG,fi le

~B

log4^. logger. com.kony.v;eb=DEBUG,file### temp appender for backup

log4;j.appender.fi1e=org.apache.1og4j.Rol 1inFlieAppender
1oqj1.ajjpender .file. maxFi1 esi ze=10240KBl og4 i. appender .file. maxBackuplndex=5
liT:-iriWi^iirTM|L^iWfclIgiifct.7IR7Wit^Fi?l oa-i i. appender.file. threshold=debug

Tog4j.appender.file.layout=org.apache.log4j.PatternLayout# %L should be used only in


dev, its extremely slov;#log4 j. appender. file, layout. ConversionPattern=[?x] ?d{ABSOLUTE}

?5p %ci2}:%L - %rn%nlog;4i. appender.file, layout.conversionpattern=d{dd mmm

yyyy/HH:min:ss} %5p %C\Z} - ^m%n

There is a LOT of data logged...make your print statements very unique and easy to find

82

Thin Client Logging

kony

Look for the following platform debug statements in the middleware.log

DEBUG api.Networkb - Parameters - these statements indcate the request


parameters set for the given service cali

Result Table Returned from network Cali - these statements indcate the response
fetched from the middleware

You can also get Important request information such as user agent, referrer, browser
timestamp etc in the middleware.log. For example:
[requestID=949d27 3f-37ca-47d7-898 3-7fabe63d59d6
UA=Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us)

AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2


Safari/6533.18.5

referer=http://testqa. konylabs.net/test/p?num=2&cacheid=lcca9d7 7c-1534-49148420-5cf8 6652d6ebsformid=frmTestb

URL=http://testqa. konylabs.net /test /p/72. 33866 7092 844 84


TS=1307361124519]

Using Alerts for Debugging

kony

Alerts can also be used for debugging!

Can be cumbersome to click through.

Nice if you want a quick confirmation to keep the flow going or to show debug statements ifyou
don't have access to debug tools (QAtester, for example).
You can either use the Alert action (in the Event Editor) or use the kony.ui.AlertAPI.
Typically, in code you'll keep it simple. For example:
kony.ui.Alert(
{

"message"

"My Alert Text" + " my Second String",

"alertType"

constants.ALERT_TYPE_ERROR,

"alertTitle"

"Alert Messages Title",

"yesLabel"

"OK" ,

Alert Message Title

"noLabel"

"alertlcon"

"alertHandler"

},

{});

myone.png

My Alert Text my Second String

nuil
OK

wmmmm

83

Using Alerts for Debugging

kony

For Confirmation Type of Alert Use :


kony.ui.Alert(
{

"message"

"My Alert Message !",

"alertType"

constants.ALERT_TYPE_CONFIRMATION,

"alertTitle"

"Alert Type Message - TITLE",

"yesLabel"

"OK" ,

"noLabel"

"Not-OK",

"alertlcon"

"myone.png",

AlertType Message 1TTLE

"alertHandler"

}r

AlertHandlerFunction

My Alert Message !

{} ;

0K

Using Alerts for Debugging


function AlertHandlerFunction(response)

kony

if (response == true) {

0n_0k_Click()
} else {

On_Not_Ok_Click()
}

03-29

Fren OK

Click

08-29 18

39 08 737

1094

ccm.crgn. . .

From OK

Click Onwards

08-29

39

797

1034

cera. crgn. . .

Frcm Nnt-OK Click Onvarda

13 28

13

34

33

148

980

Olivarda

function On_Ok_Click() {
kony.print("From OK Click Onwards")
};

function On_Not_Ok_Click()

kony.print("From Not-OK Click Onwards")


>;

84

Inline Debugging

kony

The last troubleshooting technique is using the Konyinline debugger.

We'll cover this in a bit when you're really getting into the code.

For now, using the Alerts and logs and get familiar with using them for your troubleshooting.

"

85

Support for JavaScript

kony

Along with La, JavaScript support is available from Kony 5.0 for client side loglc

JavaScript Is an implementation of European Computer Manufacturers Associatlon


(ECMA) Script Language standard.

ECMA-262 has three versions and in kony environment JavaScript should be compliant
with ECMA v3.

Like La, JavaScript is also light weight scripting language

Support for mltiple mobile device platforms such OS and Android allows you to get your
app to a wide range of users.

JavaScript may not be known for its object oriented properties, but t does support most of
the features required to be considered as an Object Oriented language.

It gives flexibility to import existing 3rd party frameworks, components inside Kony

Writing Code - Creating a Module


..<
(t

K*

*i%

I.v*

h*

tote

JlSMm*!*!^^.

kony

**#

- , ,

*<.ml-.

0 - J

tS*>Ap P!*"*. %"**


,

I.-.,!-..

Ir-

/?
V ltn-lartnB'

ti

,1

" /*

''

.\
The code modules do

SO -

"

NOT belong to the form,


they can be accessed
from anywhere in your
application

i ^J

..... ci-jaJtes

Just start typing in your

code!

........

Note: best practices are to


have code for a form in a
module name that reflects

prtvtn r*-*'"-''"- -,'-.";


M*tl* H K i m

''ti>i.nEta^t&ab

the functlonality.

-:

-.'..7>

86

JavaScript - Exercise

kony

Objectives

Design a login page & cali function on click event of login button.

On appropriate user credential show a welcome message.

On unauthorized access start the counter and after three incorrect attempts exit the
app ( Not appllcable for SPA or Thin Client).

Concepts

Crate a module and write a JavaScript function.

Hook the JavaScript function to Button widget.

Procedure

Write one function that will be hooked up to the onclick event of the Login button.
Your function will have to determine User ID as "Admin" and Password as "Password".

If the Login button was pressed, get the vales of the User ID and Password TextBoxes
and valdate. Also, you should clear out the text in the TextBoxes.

On successful login show label text as "Admin has been authenticated".

JavaScript - Exercise(cont)

XA

kony

lUser=frmLoginPage.tbxLogin.text;

lPassword=frmLoginPage.tbxPassword.text;
if(count==3)
{

count =0;frmLoginPage.lblResult.text="Exiting the app at third


attempt "+count;

kony.application.exit();

else if((lUser=="Admin") && (lPassword=="Password"))

{ frmLoginPage.lblHead.text=lUser+" has been authenticated";}


else

{ frmLoginPage.lblResult.text="Invalid login credential. Try


again !!!!!"tcount;
count=count+l;
-

frmLoginPage.tbxLogin.text="";
frmLoginPage.tbxPassword.text="" ;

87

JavaScript - Exercise (cont.)

kony

>.

JavaScript- Unsupported methods

\A

kony

Following methods & properties of the JS Object are not supported by the JS objects that
are created and returned by Kony JS APIs.
Methods

toLocaleString

valueOf

hasOwnProperty

isPrototypeOf

Property

Constructor

Note : The user defined JS objects will still respond to the above methods and property but it
is recommended to not use these for the uniform codebase.

88
"

A*

JavaScript-String Library

kony

Afew useful kony string API functions:

kony. string .containsChars (inputstring, characterArray):This API verifies


if any one of the specified set of characters is available in the given string and returns a
boolean value

inputstring : Specifies the input string that needs to be verified.


characterArray : Specifies the set of characters that need to be searched
within the input string.

status

[boolean]

true - if the given input string contains any one of the characters in the specified list.

faise - Ifthere is an error in the input or if the given Input string does not contain any of
the specified input characters.
Examples:

flag=kony .string.containsChars("abdcdADV" , [" | ","-"] ) -^ flag = faise


f lag=kony. string.containsChars ("abdcd | ADV" , [" | ","-"]) -^ flag = true

"

4,

JavaScript - String Library (cont.)


kony.string.isAscAipha

(inputstring):

returns a

i
'i
kony

boolean valu true, if the

inputstring contains only ASCII alphabet characters.


Examples:
a = kony.string.isAsciiAlpha( "abdcdADV" )-> a = true
a = kony.string.isAsciiAlphaf "123ab3dcdADV" )-> a = faise

kony.string.containsOnlyGivenChars (inputstring, characterArray): ThisAPI

verifies if only (and only) the specified set of characters is available In the given string and
returns a boolean value.

Example:
var inputstr = "abdcdADV";

var charsArr = ["a","b", "d", "o", "A", "D", "V"];

var resultantstring =

kony.string.containsOnlyGivenChars(inputstr,charsArr); ->
resultantstring=true

var inputstr = "abdcdADH";


var charsArr = ["a","b", "d", "c", "A", "D", "V"];
var

resultantString=kony.string.containsOnlyGivenChars(inputstr,charsArr
) ;->resultantString=f alse

89

kkony*

JavaScript - String Library (cont.)

kony.string.isNumeric(inputstring): returns a boolean valu true, if the


inputstring contains only numeric characters. Otherwise returns a boolean value faise.
Examples:
a = kony .string.isNumeric( "12344" ) -> a = true
a = kony. string. isNumeric( "12344ABC" ) -> a = faise

kony. string. rep (s, n): returns a string where the string s is repeated n times
Example:
a = kony.string.rep("JS" , 4) -> a = "JS JS JS JS"

kony.string.reverse(s): returns the string s with the characters reversed


Example:
a = kony. string. reverse) "Helio JS user") ->a = "reSU SJ olleH"

AJ^

JavaScript - String Library (cont.)

kony

kony. string. trim(s): returns a string by trimming off the leading AND ending spaces
from string s
Example:
kony. string. trim("

Helio JS user

") -> "Helio JS user"

kony.string.startsWith(sourcestring, comparestring, ignorecase[default

true]): returns a Boolean value (true/false) Indicating ifthe string sourcestring begins
with the string comparestring by following the optional specified rule of ignorecase
indicating if the check is case sensitive.
Examples:
kony. string. startsWith("Helio JS user", "helio") -> true
kony. string. startsWith( "Helio JS user", "helio", faise) -> faise
kony.string.startsWith("Helio JS user", "JS") > faise

90

r
r

JavaScript - String Library (cont.)

kony

kony.string.endswith(sourcestring, comparestring,ignorecase[default

true]): returns a Boolean value (true/false) Indicating if the string sourcestring ends
with the string comparestring by following the optional specified rule of ignorecase
Indicating if the check is case sensitive.
Examples:

kony. string.endsWith( "Helio JS user", "User") -^ true


kony. string.endsWith( "Helio JS user", "User", faise) -> faise
kony.string.endswith) "Helio JS user", "JS") -> faise

kony.string.equalsignoreCase(si, s2)): returns a Boolean valu (true/false)


indicating if the string si is the same as string s2
Example:
kony.string.equals!gnoreCase("Helio"

"hELLO") -> true

JavaScript- String Library (cont.)

kony

kony. string.containsNoGivenChars (inputstring, charsArray): returns a

boolean value , if the input value does not contain any of the specified characters in string
inputstring.

Example:

var a=kony.string.containsNoGivenChars("abdcdADV",

["|","-"]);

a=true

kony. string. isValidEmail (inputstring) : This API verifies if the inputstring is a valid
emall address and returns a boolean value.

The API performs the following validations on the input string:

has at least 6 characters

has @

has at least 4 characters after @

has . (dot) followed by at least 2 characters

has at least 1 character before @

Examples:
var a=kony.string.isValidEmail("abcd@"));->faise
var a=kony.string.isValidEmail("abcd6abc.com") );->true

"

91

JavaScript -Kony Studio APIs


^*MBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBm^*m

Tal

4'
kony

lESH

Table API

NA

MathAPI

Not required in JS but works for backward compatibility.

String API

S kony.string.method namespace

OS API

S All date related APIs are removed from the kony.os namespace

and developers are expected to use the Global Object Date


instead.
PushAPI

kony.push. method

NetAPI

/ kony.net.method

Data Store API

NA

Timer API

S kony.timer.method

Phone API

kony.phone.method

Widget API

categorized into Widget, Container Widget and Scroll Container

Widget
Base API

kony.method

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^B

92

JavaScript - Kony Studio APIs (cont.)

kony

Basic API

kony.application.methods

Contact API

kony.contact.methods

Streaming API

kony.stream.method

Internationalization API

S kony.il8n.method

Theme API

kony.theme.method

Crypto API

kony.crypto.method

Local Storage API

v'

kony.store.method

Datbase API

kony.db.method

Geo Location API

kony.location.method

Note : Basic API is consist of most of the APIs like Badge, Appmenu, Application Event
API, Gesture API etc.

msmmmmmm

JavaScript- Integrating 3rd Party JS


i H^ Using3rdPartyJS

| frmOne

s ^ forms a)

&_ MyModule.js

i**

kony

r. Th.rdPartyJS.js E3

function checkNum(num)

* W mobile (1)

frmOne

3
-4

j, tablet (0)

1 desktop (0)

if(num<0)
{

? popups(0)
* tmplate; (0)

num = num *-ij


num="-$"+num;

j m modules (2)

. %la(0
* S JS (2)

1
else

>j MyModule.js

\\ ThirdPartyJS.js-*

num= % +num;

{j web_module (0)
i r--criiirrf?l

;- frmOne

*j MyModule.js 7a

; ThirdPartyJS.js

function showO

frmOne.lb!One|text="nput value is:"+checkNum(frmOne.tbxOne.text)

\ 7

Here checkNumQ is function having


declaration in a 3rd party JS file.

93

JavaScript - Integrating 3rd Party JS

IA

kony

3rd party JavaScript functions can be used in kony application only ifthey are compliant to
ECMAScript 3 and not using any unsupported methods or properties as per kony
guideline.

To use 3rd partyJavaScriptfunction we need to copy<third party>.js files containing


function definition in modules folder of the kony application.
Ul can be customized using custom widgets

JS based Custom widgets are currently available with SPAbuildsonly


Custom widgets can also be created using JQuery library in kony

Copyright 2012 Kony Solutions. Inc. CONFIDENTIAL

94

r
r

XA

Dynamic Widgets - Overview

kony

Widgets can be created dynamically and added to the form hierarchy

Form is also a widget, so it can also be created dynamically

Widgets can also be removed from the form hirerachy and these
changes reflect on the form when the form becomes visible.

If changes are to be in current visible form, then changes are reflected


mmediately.

Use Cases:

Look and feel of the forms can be changed dynamically based on the service
response or based on the user input etc.
In a flight booking scenario, fields can be created dynamically based on the
number of the passengers entered by the user.

Dynamic Widgets - Overview

kony

List of the below widgets that can be created dynamically

Browser

Label

Switch

Button

Line

Tab

Calendar

List Box

TabPane

Camera

Map

TextArea

CheckBoxGroup

Form Menultems

TextBox2

ComboBox

ObjectSelector3D

Video

DataGrid

PickerVew

Form2

RadioButtonGroup

Hbox

RichText

Hz Image Strip

ScrollBox

Image2

Segment2

Image Gallery

Slider

95

Dynamic Widgets Creation API

kony

In order to crate widget dynamically we have to provide the three


objects

basicConf contains the basic configuration properties, eg : id and isVisible


etc.
Name

,'alue

B L-3 General

/Id

" Nsegment210695377211

VjsVisible^ /true

layoutConf contains layout specific configuration properties eg : margin and


padding etc.
Appearance
orientatjo BOX_LAYOUT_VERTICAL

'Trgi Nirdit
-paddina^'tdit

XA

Dynamic Widgets Creation API

kony

pspConf contians platform specific configuration properties eg: iPhone and


iPad specific properties for searchBy and searchCriteria.
iPhone

indica tor

SEGU row SELECT

enableDicbonary

faise

showProgressIndicator

true

progresslndica torColor

PROGRES5 INDICATOR COLOR WHITE

bounces

true

editStyle

SEGUI_EDiTING_STYLE_NOr

mEditag^^^
f searchCriteriaA
V^ea: :n= .

NotDefined

SEGU1_SEARCH_CRTTERIA STARTSWITH
'ene

basicConf, layoutConf and pspConf properties changes from widget to


widget.

Below is the sample snippet for creating widget dynamically

var sampleWidget= new kony.ui.Widgetname(basicConf,


pspConf) ;

layoutConf,

Note : In case of Hbox and Vbox it should be it should be kony.ui.box

96

Creating Widgets Dynamically

kony

We shall see how to crate the following widgets dnyamically

Button

Hbox

TextBox2

ScrollBox

Form2

r
Creating Widgets Dynamically

kony

Example Button:
Defining the properties for Button
var btnBasic={id:"Onbutton", skin:"btnSkin",text:"Click Here"

onClick:onClickCallBck};
var btnLayout={containerWeight:100, padding:[5,5,5,5 ],
margin:[5,5,5,5 ] , displayText:true};

var btnPSP={externa1URL:http://www.konysolutions.com,

submitURL:http://www.konysolutions.com,glowEffect:true };

Creating a Button
sampleButton= new kony.ui.Button(btnBasic, btnLayout,
btnPSP);

97

Creating Widgets Dynamically (cont.)

i^
kony

Example TextBox2 :
Defining the properties for TextBox2
var txtBasic = {id:"textBoxl",placeholder:"enter text",
maxTextLength:20,isVisible:true};
var txtLayout = {hExpand:true,

widgetAlignment:constants.WIDGET_ALIGN_TOP_LEFT};
var txtPSP = {keyboardActionLabel:
constants.TEXTB0X_KEYB0ARD_LABEL_G00GLE};

Creating a TextBox
textBoxl = new kony.ui.TextBox2(txtBasic, txtLayout,
txtPSP);

Creating Widgets Dynamically (cont.)

kony

Example Hbox :
Defining the properties for Hbox
var basicConfBox = {id : "boxIdTest",
orientation:constants.BOX_LAYOUT_HORIZONTAL};

var layoutConfBox = {containerWeight:80, percent:faise};


var pspConfBox = {borderCollapse:true,
blockedUISkin:"blockUISkin" };

Creating a ScrollBox
boxTest = new kony.ui.Box(basicConfBox, layoutConfBox,
pspConfBox);

Note : Orientation should be constants.BOX_LAYOUT_VERTICALin


case of Vbox.

"

98
"

Creating Widgets Dynamically (cont.)

kony

Example ScrollBox :
Defining the properties for ScrollBox
var scrollBasic = {id :"scrollBox",
orientation:constants.BOX_LAYOUT_HORIZONTAL,};

var scrollLayout = {padding:[2,2,2,2], containerWeight:100,


margin:[5,5,5,5], containerHeight:100, percent:true};
var scrollPSP = {scrollArrowConfig:["leftArrow.png",
"topArrow.png","rightArrow.png", "bottomArrow.png"]};

Creating a ScrollBox
scrollBox = new kony.ui.ScrollBox(scrollBasic,
scrollLayout,scrollPSP);

Creating Widgets Dynamically (cont.)

kony

Example Form2 :
Defining the properties for Form2
var frmBasic = {id:"frm", addWidgets:addWidgetsCalBck};
var frmLayout

={paddingInPixel:faise, padding:[5,5,5,5]};

var frmPSP ={};

Creating a Form2
var frm =new kony.ui.Form2(frmBasic, frmLayout,

frmPSP);

addWidgets :An event callback invoked by the platform when the form is
accessed for first time after its construction.

Widgets can be added to form in addWidgets callback or in any javascript module

99

-V*1
kony

Adding Widgets Dynamically

Widgets can be added at run time to container widgets such as Form,


Hbox, Vbox, ScrollBox and TabPane etc.

add(widgetLists): This method is used to add widgets to Form, Hbox, Vbox


and ScrollBox.

wdgetLsts:comma separated list of widgets


eg:frmHome.add(buttonForYes, buttonForNo);

addAt(widgetref, index): This method is used to add widgets to Form, Hbox,


Vbox and ScrollBox at the specified index.
Widgetref: Reference of the widget that need to be added
Index: Index number at which the widget is to be added
eg:ScrllBoxl.addAt(lblDesc,

15);

Adding Widgets Dynamically - (cont.)

kony

addTab(tabld, tabName, tablmage, box, masterDataLoad): This method is


used to add a tab to the TabPane widget.
tabld: Specifies the id of the tab

tabName: Specifies the name of the tab


tablmage: Specifies the image of the tab

box: instance of Hbox or Vbox

masterDataLoad: Deprecated, works only for backward compatibility


eg:tabPane.addTab("tPane","LocTAB","app.png",
masterDataLoad:{});

boxl,

addTabAt(tabName, tablmage, box, index): This method is used to add a


tab at the specified index to the TabPane.
tabName, tablmage and box: Same as described for addTab method
index: Index number at which the widget is to be added
eg:tabPane.addTabAt("LocTAB","app.png",box,

2)

100

Removing Widgets Dynamically

kony

Widgets can be removed at run time from container widgets such as


Form, Hbox, Vbox, ScrollBox and TabPane etc.
remove(widgetref): This method removes a widget from Form, Hbox, Vbox
or ScrollBox.

widgetref: Referenece of the name of the widget


eg:frmHome.remove(buttonForYes) ;

removeAt(index): This method removes a widget from the Form, Hbox,


Vbox or ScrollBox at the given index.
Index: Index number of the widget to be removed
eg:ScrllBoxl.removeAt(15);

Removing Widgets Dynamically - (cont.)

kony

removeTabByld(tabld): This method is used to remove a tab based on the


tabid on the TabPane.

tabld: Specifies the if of the tab


eg:tabPane.removeTabById("tPane");

removeTabAt(index): This method is used to remove a tab based on the


index on the TabPane.

index: Index number of the widget to be removed


eg:tabPane.removeTabAt(2) ;

101

Considerations

kony

Widgets when added to the form hierarchy should ensure that widget ID
(identifiers) is unique in the form.

Adding Widgets with duplcate IDs will result in undefined behavior and
platforms may throw widget error.
Adding the same widget to mltiple hierarchies is not allowed

Existing widgets created from the IDE (during the design time) in the
hirearchy cannot be reassigned / modified directly
egl:frml.labell = new kony.ui.label(..); // is incorrect and
may throw Widget error.
eg2:frml.labell = nuil// is incorrect and may throw Widget
error.

Exercise -

Dynamic Widgets

kony

Objectives
Be able to add widgets dynamically

Concepts:
Widgets can be created dynamically
Widgets can ne added and removed dynamically from the container widgets
such as Form, Hbox , Vbox, ScrollBox and TabPane etc.

Procedure

Crate a screen using IDE which asks input for "movie name" and

'number of

tickets" and a button as shown in the next slide.

On click of the button , crate screen2 dynamically as shown

n the next

slide.

Based on the number of tickets entered in screenl , corresponding number of


rows are created in screen2 and each row should have a label and textbox.

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^H

102

Exercise - Dynamic Widgets (cont.)

kony

darkknlghcrise
Name

Number

.^^^^B^B^^^^^BI^^^^^l^^^^B^^^Bpip^

^^^^^^^^^^^^^^^^H

Nirnc

^^^^^^^^^K^B^Ki

^^^^^^^^^^^^^^^H
I^^^^^^^^H^H^H
Confirm Booklng

SCREEN1

SCREEN 2

Number of tickets entered on screenl is 5 , so five rows are created on


screen2.

I-

103

Kony Studio APIs

The Kony Studio APIs expose

kony
functions you can cali in JS code to interact with the native

capabilities of the device.

The APIs are broken up into various categories, a

few are:

Phone Service APIs

Application APIs

Internationalization APIs

Operating System APIs

Push Notlfication APIs

Network APIs

Cryptography APIs

Gesture APIs

Hybrid APIs

HTML5 APIs

Badge APIs (OS)

^^^^^^^^^^^^^^^r^f^^f^^r^^^^^T^^^r^^rfj^H

Android Permissions and Setup

kony

Many of the device features are protected on Android and you must give the app explicit
permissions to access those functions.

Right click the application and go to Properties


On the Native App tab pick Android

Select the permissions, click the


Add > button to turn on

permissions

For example: to access GPS,


add

ACCESS_FINEJ_OCATION
permissions

_ 1 '1 C

l nrfM 1 *M1iHC\
i

--

> ..*rnM

t;MW.nl.lt*U

Allt. ' . ' . ' I

._

.-

104

Phone Service APIs

kony

The Phone Services API provides hooks to the following native capabilities of the phone.

The following methods perform phone based functions:

kony.phone.sendsMs; phoneNumber, text ): sends an SMS message specified In the text


to the number specified. Method returns a 0 for success or -1 for failure

kony.phone.openEmail(toRecipients, ccRecepients, bccRecepients, subject,

kony.phone.dial(number} : dlals the Specified number.


messageE-ody, isMessageBodyhtml, attachments ) : to launch the native email Client with
predefined email addresses, subject, body, and attachments.
function openMyEmail()

var to = [abc@fqh.com'];
var ce = ["abc@abc.com"];

var bec ["xyz@xyz.com"];


var sub =

"Helio";

var msgbody = "Testing openEmail";


kony.phone.openEmail( to, ce, bec,

sub, msgbody,

faise );

GeoLocation APIs

kony

The GeoLocation API defines a high-level interface to location information such as latitude
and longitude associated with the mobile device.
This API is designed to enable both one-shot position requests and repeated position
updates.
getcurrentposition API
kony.location.getCurrentPosition(successcallback, errorCallback,
positionOptions)

This API s invoked asynchronously to fetch the location details.

successcallback - Specifies the callback function that must be executed when the API cali
is successful. This callback has following syntax with location details passed as an argument
successCallback(position)

errorCallback (optional)- Specifies callback function that must be executed when API
cali fails. This callback has following syntax with error details passed as an argument
errorCallback(positionerror)

positionOptions (optional) - Using this parameter, the user can customize the retrieval of
the geolocation.

No return vales for this API.

105

GeoLocation APIs

kony

watchposition API
kony. location.watc/PositionfsuccessCallbao/c, errorCallback,
positionOptions)

This API is invoked asynchronously to fetch the location details.

However watch operation contines to monitor the position of the device and invokes the
appropriate callback every time the position changes.

successcallback - Specifies the callback function that must be executed when the

API cali is successful. This callback has following syntax with location details passed as
an argument

successCallback(position)

errorCallback (optional) - Specifies the callback function that must be executed


when the API cali fails. This callback has following syntax with error details passed as an
argument

errorCallback(positionError)

positionOptions (optional)- Using this parameter, the user can customize the
retrieval of the geolocation.

Returns a number that denotes the unique ID of the watch operation

GeoLocation APIs

kony

clearwatch API

kony.location.clearWatch(watchID)

The watch process identified by the watchID argument Is mmedlately stopped and no
further callbacks are Invoked.

If an invalid watchID is passed, method returns immediately without performing any


action.

watchID - Specifies number that uniquely identifies the watch.

No return vales for this API.

106

'

Contact API -Add a Contact

kony

The Contacts API provides the ability to view the PIM (Personal Information Manager)
datbase on the device.

kony.contact.add(contactDetaiis): adds a contact to the address book.

Syntax: var newContact = kony.contact.add (inputTable) where:


"

newContact is a reference of the table that's created or "nuW if contact is not created.

inputTable is an array with all the required fields shown in the example below:
inputTable = [firstname:"John3",

phone:[[name:"mobile",

lastname:"Steve",

number:"99999999999"]],

email:[[name:"home", id:abc@yahoo.com],
[name:"work",

id:def@kony.com]],

postal:[[name:"home", street:"Raheja",
city:"hyderabad",state:"AP",
company:[[name:"work", company:

zipcode:"50 0 310"]],
"kony",

title:"architect"]]

firstname and phone fields are mandatory with at least one phone number n phone field.

Contact API - Find & Delete a Contact

kony

kony.contact. find(firstName): returns a list of contacts found in the address book.

Syntax: var foundContact = contact.find(<searchCriteria>) where:

searchcriteria must be first name

if no match is found, it returns nuil.

kony. contact. find(" *") returns the list of all the contacts available in the address book.
kony. contact. delete: deletes a contact from the address book.

Syntax: Var removedContact = kony.contact.delete(<contactRecord>) where:

contactRecord is a contact array populated from a kony.contact. find cali

If no contact is deleted, it returns nuil.

107

XA

Contact API - Delete a Contact

kony

kony. contact. delete: deletes a contact from the address book.

* Syntax: var removedContact = kony .contact .delete(<contactRecord> ) where:

contactRecord is a contact array populated from a kony.contact. find cali

If no contact is deleted, it returns nuil.

Application Library

kony

There is only one method cali provided for Media Player functionality.

kony.application.openMediauri(URL) - opens the specified http URL string that


points to an audio/video file. This method ASSUMES that the media can play on the
device.

Following API can be used to invoke native library.

Following API can be used to termnate the current App.

kony.application.openuRL(URL) - Opens native browser with the provided URL, and


the application goes into background.

kony.application.exit()

Following enables you to set a mode for your application such as native, hybrid, and
wrapper.

kony. application. setApplicationMode (applicationMode )

This API should be called only in preappinit.

applicationMode [integer constant].- which designates for


APPLICATION_MODE_NATIVE , APPLICATION_MODE_HYBRID and

APPLICATION_MODE_WRAPPER as 1, 2 and 3 respectively.

108

AA
-

Operating System APIs

kony

This library is implemented through the os namespace. A few APIs are:

kony.os.toNumber(e) - converts the string e to a number.

If the string can't be

converted, it returns nuil.

kony.os.tocurrencyfnumber)- allows you to convert the given number to represent


currency.

kony. os. userAgent () - Returns a unique identifier for the device. This device ID is
used by Kony Middleware to dentify the device. For example, if this API is executed on
a BlackBerry 8100 device, the return value will be "rim/8100".

kony.os. freeMemory() - Returns the number of bytes available for allocation.

kony.os.nascamersupport()- Return True / Faise , and Available on all platforms


except Mobile Web.

kony. os. getDeviceCurrentorientation()- returns the current orientation of the

device. The possible vales are portralt or landscape.

Operating System APIs

a/l

kony

kony.os.deviceInfo()

name: Specifies the name of the platform as Phone, iPad, BlackBerry, Windows Mobile,
Palm, Mobile Web, Android, Symbian, and J2ME etc.

model: Specifies the model number of the platform. For example 8900 etc. Not applicable
for Mobile Web.

versin: Specifies the versin of the platform in a string format Not applicable for Mobile
Web.

deviceWidth: The device width in pixeis Valid only on Native Apps channels and not
applicable for Mobile Web.

deviceHeight: The device height in pixeis Valid only on Native Apps channels and not
applicable for Mobile Web.

Channel for all platforms.

Provldes the Android API Level based on the SDK Versin. Example : SDK 1.5-3, SDK
1.6-4,etc.

109

Form/widget APIs

kony

formName.show()

This API is used to display the form on the device.


formName.widgetID.setvisibility( True / Faise )

This API is used to change the visibllity status of a widget dynamically.


formName.widgetld.setEnabledf True / Faise )

This API is used to enable/disable a widget in a form when displayed to user.


This method is applicable on Button, Link, ListBox, CheckBoxGroup, RadioButtonGroup,
ComboBox, Camera, TextBox, Calendar, Segment (as individual rows can be marked
clickable and non-clickable), Hz_lmage_Strip, Map, TabPane and Browser_Wldget.
To access a widget's properties, use:

<formName>.<widget ID>.<property>

"

Example:

myForrn.niyLabel.text = "helio world"

XA

Dynamic Skinning

kony

A widget can have more than one skin defined (e.g. normal skin, focus skin, etc.).

Dynamic Skinning allows you to change the skin of a widget during runtime through code.
Reference the skin as an object, not a string.
For example: For a Phone Widget you want to display different skins for successful and
unsuccessful dial attempts. Here an example in code:
funfunction dynSkinning() {
if(frmHome.xTBX.text != "nuil") { frmHome.btnDynaSkin.skin = successkin;

else {frmHome.btnDynaSkin.skin = failureSkin; }


frmHome .lblResult .text = frmHome .xTBX .text;
}

Assumes you have created the two skins referenced.

110

AA

Dynamic Skinning (cont.)

konyi%

You MUST ensure that skin exists for the widget in the IDE before the code is executed.

The following table llsts the widgets and platforms which support dynamic skinning:

Widget

Android/

Android BlackBerry

Phone W"ntlows'

'/pad Winddows Mobile Web SPA/Playbook

Tablet

6.x

Form

Yes

HBox

Yes

VBox

Yes

Yes

Button

Yes

Yes

Yes

Yes

Yes

Yes

Yes

ComboBox

Yes

Yes

Yes

Yes

Yes

Image
Label

Yes

Yes

Calendar

CheckBoxGroup

Yes

Yes

Y(-s

Yes

Yes

Line
Yes
:

IE:

Yes

Yes

RadioButtonGroup

Yes

Rich Text

Yes

Yes
Yes

Yes

fes

Yes

Yes

TextArea

Yes

Yes

TextBox

Yes

Yes

ScrollBox

Ves

Yes

Signature
Vkle:

Yessupportec
on 6 x)
Yes

Copyright2012KonySo!u1ons,lnc. CONFIDENTIAL

221

XA

Preprocessor Statements

kony

There are times when you need to write code that applies to only a specific platform
You can use the kony.os.defineinfo() API, but the statement will be compiled for
every platform and be part of the code

if def is a compiler directive to selectively compile code only for a certain platform.
Syntax is: // #define <identifler>

Defines an identifier.

//#undef <identifier>

> Removes a defined identifier, or does nothing ifthe identifier is not defined.

// #ifdef <dentifiei>

Tests whether an identifier is defined, and parses the code block until either a #endif
or #else directive is reached.

// #fndef <identifier>

Tests whether an identifier is not defined, and parses the code block until either a
#endifox #e/se directive is reached.

111

AA

Compiler Directive (cont.)

kony

// #else

Acode block executed when #ifdefor iifndef return faise. Code is parsed until a
#endif directive Is reached.

// #endif

Ends a code block.

Following are the few predefined identifiers

iPhone (or phone) and iPad (or ipad)


BB (or bb)

Android

SPA (or spa).

Mobile or tablet or desktop.

in addition developers also can crate more identifiers through #define

Eventobject

kony

When a function is called from a widget event, information is passed to the function about
that widget

For example, if I assign a function to a button onClick event, I will get passed in that button
object that was clicked
function whatsMyText(myButton){

kony. print( "button text is : "+ myButton. text)


}

When I hook that function up, the system passes me the event object:
tWwtrMlltwwr

iwt r-"^*.a fun.-t.rtR-.

Sdn>fu-tt.-< -.tM,r(

I I ru-me ..'ijii'.'.I
hj<* * - .

.^--t-

V,*

<dE -

-o,

The eventobject is relative to what event on what widget is being used.

112

XA
"

Exercise - Eventobject

kony

Objectives
" Pass a widget into a function as an eventobject

Access widget properties from JS code

Access the location services of the mobile device

Concepts
The Phone Services API provides hooks to the native location services

When a function is called from a widget event, information is passed to the function
about that widget

Widget properties can be accessed from JS

Procedure

This exercise will extend the earlier exercise in which you created a login form

Write one function that will be hooked up to the onclick event of both the Login and
Help buttons. Your function will have to determine which button was pressed.

If the Login button was pressed, get the vales of the User ID and Password TextBoxes
and print them to the log. Also, you should clear out the text in the TextBoxes.

If the Help button was pressed, access the Geolocation services and print the result:

XA

Exercise - Eventobject (cont.)

kony

kony.location.getCurrentPosition(onGPSsuccess, onGPSerror);

function onGPSsuccess(position) {
kony.print("

Latitude:

kony.print("

Longitude:

" + position. coords .latitude);

kony.print("

>Current Position" + position);

" + position .coords .longitude );

function onGPSerror (posError)-{


kony.print("

>>Error code:

kony.print("

Message:

" + posError.code);

" + posError .message) ; )

Be sure to set the ACCESS_FINEJ_OCATION property to True in the Project


Properties -> NatlveApp -> Android dialog

Run it on the Android emulator and check the log for your results
"

113

Exercise - Eventobject (cont.)

'i'

kony

With your app still running open a cmd window and enter these commands to set the
"current location" of the emulator:
telnet

locaihost 5554

geo fix -76.8888 45.9999

Press the Help button again to see that the "current location" of the emulator has
changed.

D/StandardLib<

768>:

D/StandardLib<
D/StandardLib<
D/StandardLib<
D/StandardLib<

768>:
768>:
768>:
768):

D/GpsLocationProuider<
D/GpsLocationProuider<
D/UM FunctionC
D/UM Function<
D/UM Function<
D/StandardLibC
D/StandardLib<

768):
768):
768):
768):
768):

Login button vas pressed


**User ID : flanerjr
**Passiord: passwdl23
KlllIMHlimKMMIIIIKmillKmmMKKMMKM

52): flLARM_WflKEUP
52): startNauigating
Non Synchronized Function.execute called.
Executing the La Function
Dispathcing the function

**Help button uas pressed


D/PhoneLib< 768): Executing the nethocl index : 3
D/LocationManager< 768): getflllProviders
D/StandardLib<
768): **GPS info: < status 0.0, longitude = -76.8888. latitude
-

45.99989833333334,

D/StandardLib<

768):

>
"

Store APIs - Overview

kony

There are times when you need to store data on the device. For example:

Store an airline boarding pass barcode.

Store login credentials for "remember me" functionality.

LocalStorage APIs allow the users to store and retheve data in persistent store on the device.

The data stored using the LocalStorage APIs is accessible only from the cllent-side for Thin
Client platform.

"

kony.store.setltem API
kony. store. setItem(keyValue)

This API creates a structured clone of the given value.

If this API raises an exception then the list associated with the object is left unchanged.

keyname - Specifies the key name for which the tem needs to be set.

Value - Specifies the value that must be set using the given key. This value can be a
number, string, Boolean, or an array.

Eg:

var keyValue4 = { name :

"John" } ; kony.store.setltem ( keyValue4) ;

114

Store APIs

kony

kony.store.getltem API
kony. store, get tem (keyname)

This API returns a structured clone of the current value associated with the given key.

Ifthe given key does not exist in the list associated with the object then this method
returns nuil.

keyname - Specifies the key name from which the tem needs to be fetched.

Returns the tem saved using the specified key.

kony.store.removeltem API
kony.store,removeitem(keyName)

This API removes the tem identified by the key, if it exists.

If no tem with that key exists, the method does not perform any acton.

keyname - Specifies the key name for which the tem needs to be removed.

No return vales for this API.

Store APIs

kony

kony.store.key API
kony.store.key(index)

This API returns the name of the nth key in the list.

If n s greater than the number of key/value pairs in the object, then this method returns
nuil.

index - Specifies the index for which the key name is to be returned.

Returns the keyname of the specified index.

kony.store. clear API


kony.store.clear()

This API allows you to empty the datbase by clearing all the key-value pairs.

No return vales for this API.

kony.store. length API


kony.store.length()

This API returns the length of the local storage.

115

Exercise - LocalStorage APIs

kony

Objective:

Be able to utilize the Data Store API to store and retheve data to/from the persistent
store on the mobile device.

Concepts:

store APIs allow the users to store and retrieve data in persistent store on the device.
Procedure:

This exercise will add three buttons to our Login app: Save ID, Recall ID and Delete ID.

When the Save ID button is clicked, the vales in the TextBoxes should be saved to

When the Recall ID is clicked, then the vales should be read from persistent store and

persistent store using kony.store.setltem;). The TextBoxes should also be cleared.


populated in the TextBoxes.

Delete ID button should delete the vales from persistent store

After you have this working, then selectively enable and dlsable the buttons depending
on context. For example, Recall ID and DeleteID should be disabled unless something
is stored.

a'

Exercise - Store APIs (cont.)


-

. I *

kony

5554;!conyavdmap

116

WebSQL APIs

kony

The WebSQL APIs allow applications to store data in databases, that can be queried using
a variant of SQL.

The actual datbase used for storing the data and its visibility to other applications is
defined in the following table:

liSWBWSiffrBH
applications

Phone/iPad

SQLLite

No

Android/Android Tablet

SQLLite

No

Blackberry

SQLLite

Yes (SDCard)

Windows 6.x

SQL Server CE

Yes (File System)


No

Windows Phone

SQLServer

Symbian

SQLLite

No

Single Page Application (SPA)

SQLLite

Browser Implementation

Note: For BlackBerry, these API are supported only on 5.0 and above versions. SD Card
must be created to use the WebSQL APIs on a BlackBerry emulator.

'

XA

WebSQL APIs (cont.)

kony

kony. db. openDatabase API


kony.db. openDatabase (name, versin, displayName, estimatedsize)

This API allows you to open the specified versin of a particular datbase.

name - Specifies the actual name of the datbase to open.

versin - Specifies the versin of the datbase to open.

displayName - Specifies the display name of the datbase to open.

estimatedsize (optional) - Specifies the approximate size of the datbase in


bytes. Valid only for SPA platform.

Returns the unique ID of the datbase.

Usage var databaseld = kony .db. openDatabase ( "konytestDB",


Datbase", 5*1024*1024) ;

"1.0",

"demo web SQL

117

XA

HTML5 WebSQL APIs (cont.)

kony

kony.db. transaction API


kony.db.transaction(dbaseObjectld, TransactionCallback,
TransactionErrorCallback, Successcallback)

This API allows application to execute the specified transaction on the given datbase.

On invoking this API, it returns immediately and asynchronously executes the


transaction.

This API creates a SQLTransaction object.

dbaseobjectid - Specifies the unique ID of the datbase.

TransactionCallback - Specifies the callback function that contains the


transactions.

TransactionErrorCallback (optional) - Specifies the callback that must be


executed ifthere is an error in executing the transaction.
Successcallback (optional) - Specifies the callback that must be executed if
the transaction is successful.

No return vales for this API.

WebSQL APIs (cont.)

kony

kony.db.transaction API

Usage kony.db.transaction( "myDatabase", myTransactionCallback,


myTransactionErrorCallback, mySuccesscallback);
function myTransactionCallback(transactionld)
{

SQLTransaction contains implementation of executeSql method


Invoke datbase.executesgl method for sql trasaction

function myTransactionErrorCallback(transactionld, SQLError)


{

This callback function is used to roll back the updates to the


datbase.

function mySuccessCallback()
{

Business logic

118

WebSQL APIs (cont.)

?.'-.
kony

kony.db.readTransaction API
kony.db.readtransaction(dbaseObj ectld, TransactionCallback,
TransactionErrorCallback, Successcallback)

This API allows you to read a specified transaction.

On invoking this API, it returns immediately and asynchronously reads the transaction.

This API creates a SQLTransaction object for read-only transactions.

dbaseobjectid - Specifies the unique ID of the datbase.

TransactionCallback - Specifies the callback function that contains the


transactions.

TransactionErrorCallback (optional) - Specifies the callback that must be


executed if there is an error in executing the transaction.

successcallback (optional) - Specifies the callback that must be executed f the


transaction is successful.

No return vales for this API.

WebSQL APIs (cont.)

kony

kony.db.readTransaction API

Usage kony.db.readtransaction("myDatbase", myTransactionCallback,


myTransactionErrorCallback, mySuccessCallback);
function myTransactionCallback(transactionld)
{

-SQLTransaction contains mplementation of executeSql method


-Invoke datbase, executesql method for sql trasaction
}

function myTransactionErrorCallback(transactionld, SQLError)


{

Show the appropriate error message


}

function mySuccessCallback()
{
Business logic
}

119

WebSQL APIs (cont.)

kony

kony. db. executeSql API


/cony.db.executesglftransactionld, SCLStatement, arguments,
SQLStatementSuccessCallback, SQLStatementErrorCallback)

This API allows you to execute a specified SQL statement on the given datbase.

On invoking this API, it returns immediately and asynchronously reads the transaction.

transactionld - Specifies the unique ID of the transaction.

SQLStatement - Specifies the SQL statement that must be executed.

arguments (optional)- Specifies the arguments for executing the SQL statement.
Vales can be NULL, REAL, TEXT, BLOB or nuil to ignore this parameter.

SQLStatementSuccessCallback (optional) - Specifies the callback function that


must be executed when the execution of the SQL statement is a success.

SQLStaternentErrorcaiibaofc(optionai) - Specifies the callback function that must


be executed when the execution of the SQL statement is a failure.

''

No return vales for this API.

'""-

"^

'"

"

WebSQL APIs (cont.)


"

kony

Jcony.db.executeSgl API

Usage:
kony. db. executesql (transactionld,
successCB,

"SELECT * FROM KONYDEMOTABLE", nuil,

errorCB);

kony.db. executesql (transactionld,


"company name")");

"INSERT INTO DEMO (id, data) VALES (l,

kony.db.executesql (transactionld,
"Kony") ");

"INSERT INTO DEMO (id, data) VALES (2,

function errorCB(transactionld,

err)

kony .printf "Error processing SQL:

" + err .code) ;

function successCB(transactionld, resultSet)


{

kony.print("SQL operation success");

120

WebSQL APIs (cont.)

kony

kony. db.sqlResultsetRowItem API


kony.db.sqlResultsetRowItem(transactionld, SQLResultSet,

This API returns the row available at the specified index.

If there is no such row, then the API returns nuil.

transactionld - Specifies the unique ID of the transaction.

SQLResultSet - Specifies the name of the SQL result set.

ndex - Specifies the index from which the row is to be retrieved.

Returns the row tem at the specified index.

Usage var rowltem = kony.db.sqlResultsetRowItemftransactionld,

index)

resultset,

i);

kony.print("KONYDEMOTABLE"+rowItem["id"l + " Data = " + rowItem[ "data" ])

Note: Use resultset. rows. length to know the length of a result set.

XA

WebSQL APIs - Limitations

Table ames and Column ames are case-sensitive.

When using the binding "?" placeholders, ensure that the number of binding

kony c

parameters and the number of vales are the same.

For example, the following statement can cause the datbase to be inconsistent:
var stmt3 = "insert into EMP_DETAILS vales (?, ?,?,?,?,?) ";
kony.db.executeSql(tx,stmt3,{'1', '2', '3 '},successcallback,errorCallback);

Nested datbase transactions are not supported across platforms. Avoid starting a
new transaction in the successcallback function of an existing transaction.

The error codes might vary between the platforms. This is due to the fact that
underiying SDKs do not expose all the errors that can be mapped to HTML5 WebSQL
Specification.

Accessing insertid key in the resultset rows leads to an error in SPA.

121

Event Editor - Overview

kony

As we've seen, an event is an action triggered in an application flow.

We've hooked up code to a button's onclick event. Here are some other example of events:

Events when the application is loading or going into the background

Loading up a screen or dismissing a screen

Events triggered by the user like: clicking a button, selecting a value from a dropdown,
user clicks a men tem, the user changes the orientation of the device, etc.

An Action Sequence is a set of actions performed when an event is triggered In a Kony


Application

So far we've only created action sequences of one action: invoke function

It's the Event Editor, that we use to define an Action Sequence for an event and we'll now
look at what we can do with this tool...

122

Event Editor - Launching

kony

Events are exposed on the property sheet in the Event section AND possibly n the
properties for specific device types
"Not Defined" means just that - the event has not been configured yet

Property:
Name
4

Sequence

Value

Code

Define Action Sequence

Genera.

title

frmHome

title il8n Key

None

renderer

Ph one: true, Andr id;true,Bli

headers

None

footers

None

enabledForldleTi neout

faise

type

FORM_TYPE_IMATIVE

Action Sequence

( Appearance
- Skin

* yJxvtT^
jr

NotDefined^C
NotDefined \
Not Defined
]

init

preShow

onHide
onDestroy

postShoirV

\.

Not Defined

Not Defined S

^--^^onOrientatior :>. snge

Edit^^-^

i-- iPhone~~"~-

Event Editor - Configuring

kony

Right-clicking tems brings up the menus


EvcniEdaw

a*lct FerrrvCepup: timThird

Existing

| OpenMw-g [Ato.

actions in
the flow

Managing

. Toim r,m

Naming a
Iniert beroic

tonta ifnct (Synduvflcui)

ln;trt>tttr

Invokt MBvKt(AjyTichronoui!

the

actions:

Nvitjmtoorm Poptip

makes it

Add Mipping

global for

Show titn
-i :l Pr.procei (;::,

copy, add,

Add Ottmcfi

delete and

sequence

AddStvpptr

use

elsewhere.

: -i.:. > '-.r Trrc

move

n.;. Ir* ' 3u*n :


fiddC{n-nm

Available

Add 11.. Wiubi*

actions

Mate An, (hii;i; mjdt te 9kb! ;e.T^cn:u vil' t< "dlerted K

123

XA

Event Editor-Action Sequence tems

kony

Following is the list of action sequence tems available in Kony IDE


Invoke Service (Synchronous)
Invoke Service (Asynchronous)

We'll discuss these a bit


later on...

Navigate to a form/Popup

Add Mapping
Show Alert

Add Preprocess Decisin


Add Decisin

Add Snippet
Invoke Function

Invoke Sequence
Add Comment
Add Local Variable

Action - Invoke Function


Invoke Function

This action tem is used to invoke a


JS function defined in the code
modules.

Dropdown will list all the JS


functions defined in the code
modules.

Input parameters, if any, will be


visible in the "Input params" tab.
Vales can be assigned using the
Mapping Editor.

The function can be seen in the


"Function" tab

Link to edit the function

124

a'

Mapping Editor-Overview

kony

The Mapping Editor is used to pass data from one object to another - a graphical way to
say "this = that" or the "Target' = "Source"
Mapping editor helps in reducing
the coding efforts
The Source and Target llsts are
context sensitive (based on how

the mapping editor was called)


Lets you filter by type of object
(variable, skin, widget, etc) or
search for specific tems
To make the assoclation, click on

a source tem and click on a target


item. The target tem will now be
set with the value from the source
item.

Mapping Editor-Source

The Source consists of the following:

Global Variables

Data Store Keys

H8NKeys

Skins

Response of the service you have


invoked

and Target

kQfC

The Target consists of the following


components:

Global Variables

Data Store Keys

Service you are invoking

Form to which you are navigating

Allthe widgets on this form

Form from which the mapping editor


was invoked

Allthe widgets on this form

Note: i18n Keys appear only in the source because vales cannot be assigned to them once
they are defined.

^^^^^^^^-T^^^^^t^^^^T^^^^^^^^^^^^^^^M

125

Mapping Editor - Launching &Considerations k-t%

Mapping Editor can be launched from following action tems:


Invoking a service (Synchronous or Asynchronous): To map service parameters.

Navigating to another form: To map data from one form to other.

Mapping within the same form using Add Mappingaction

Some considerations for using the Mapping Editor:

Data type of the source and target should be the same.

When mapping a collection to another collection, map the parent objects first and
THEN map the Individual children.

Source and the Target cannot be same.

Tabs are listed under form elements. Henee, you cannot map any data to a tab widget
using the Mapping editor.

Note: The Mapping Editor supports one-to-many mapping, that is, same element in the
source can be mapped to mltiple elements in the target.

Exercise - Mapping Editor

kony

Objective:

Use the Mapping Editor to map vales on the same form

Procedure:

Ok, we'll add some in-form mapping to our Login app

The idea is that when a user clicks the Login button, we want to:

Get the User ID from the TextBox

Change the Text property of the top Label to read: "<User


ID> has Authenticated" where <User ID> is the text that was
entered in the User ID TextBox

Change the skin of the label to be dlstinctive (e.g. colored


background and bold red text)

Clear both the User ID and Password TextBoxes

Do all of this in the Mapping Editor (i.e. no code)

126

Exercise - Mapping Editor (cont.)

kony
g^n

XA

Expression Editor

kony

The Expression Editor is used whenever you need to assign vales to objects that can't be
done using a simple mapping (a = b).

Expression Editor can be used in the following situations:

While mapping data from the Mapping Editor


When adding a code snippet in the Event Editor.
While building a decisin in Decisin action item.

For a local variable with "ValueType" as expression.

The Expression Editorgives you access to all form objects, API methods, skins, etc.

3 Comes with a Compile button to valdate that your syntax is correct.

Allows you to just type In parts/all of the expression.

Easy to piece together your syntax.

I Qfc I

CompileI

127

Expression Editor (cont.)


. fad

ExpressionEditor
frmHome.btnDynaSkin.text =
n*,t,

' Content Assiit Is enabled in thi< text rea


"

+ 'ncHome.xIBX.C

.>vr. .- | ;

* text: TextBox2 - KonyAPI

"w. i uiinilPri lud artnj.:r,IP ilrir|

* textinputMode : TextBo - KonyAPI

Clear |

* toLocaleStringO Object - ecma5;rip!-5.|s


^ il'nm ., -)

* '.-:.

O toStringO Objed saiwscnpt-Sji

m.-.-i

HQHHBC
Expression window shows your
expression as you crate it.

Select the below tems to

Event Object
Variables

Code assist will help while typing


widget, property or variable
name.

Code assist can be invoked by


pressing ctrl+space key

Expression Editor - building an expression |coni


3. Type the desired code snippet to be
sa

trimmed using code assist/

raiirr\-..<rri (-(Jatea

lrmHa*ntMfti2>nBfattS -

f"TB)t: Te>tBo*2 - hteb&tCommon fcrn2

1. Type string. and press ctrl+space


will enable code assist.

Finished expression:
Expression Editor
frmHome.btnDynaSkin.text * Content Assist is enabled in this text rea

2. Highiight and delete the placeholder

tony. string. trlm(frmHoe. xT3X. texL|>

text - leaves cursor in the "()"

128

r
Action - Expression Editor (cont.)

kony

If we look at our last exercise, we mapped our text from the textbox to the text on the label.

What if we wanted the label to say "you typed in: <whatever>".

In the Mapping Editor we can do that by right clicking our Target and adding an expression:

r
Right-click the label's text property.

Type In the hardcoded part of the string...


G
Conten Assist is enabled in thrs text rea

I "

'you typ-d In " + ksny.string.trirr.(;riHcir.KTEX.i:exi:!

a Bt Mrt

Cancel

I Clear j

. Compile I

telilla I

a V

Vaoautn

a ayJ(.i/il.n,;.. ,.:

...and type the expression to append.

2- u-.rr)., t

Action - Navigate to a Form/Popup

kony

Navigate to a Form/Popup

This action can be used to

navigate to another form or


popup.

asease

r
Allthe forms and popups defined in the application are
listed in the dropdown.

Use Open Mapping Editor to


map data to the form that will
be shown.

Note: This action is not applicable


for form - preshow event.

129

Action - Navigate to a Form/Popup (cont.)

kon3^

The Mapping editor associated with the navigation routine will be different than the
standalone Mapping action.
In the Mapping action, you only have access to the form itself.

In Navigation, the mapping Source will be the callingform and the mapping Target will be
the form being navigated to.

The limitation of the Mapping editor is that you do NOT have access to OTHER forms in
your project.

If you need data from another form, you'll have to either:

Access that data from the expression editor in the mapping action.

Store the data in a variable on the other form and retrieve the data from the variable.

Let's look at an example of using the expression editor to solve this...

A A

Action - Navigate to a Form/Popup (cont.)

kon*1

Here's a simple example:


form A

affije 10:22 PM
helio, rm form A

typed something In..|

Simple Navigation action to go to form B

form B

helio. I'm form E

10:23 PM

We want to navigate to
form C AND show the

y value from form A...how


to do this?
form C
<S 10:23 PM
neJ10r4;ffi-fOTTTn:

the text entered on form A Is: typed something

130

Action - Navigate to a Form/Popup (cont.)

y',
kony

Here's the Mapping for the navigation to form C (from the button on form B):
-

..-*

a*

Note: you won't have "click" access


to the objects on form A so you will
need to know the widget name to
type it in.

We could have stored that

value in a variable, but now


we have that data twice in

memory: on the form and in


the variable.

r
r

1/

Action - Navigate to a Form/Popup (cont.)

kony

Forms stay in memory until explicitly removed (we'll talk about how to do that later).

To go "back" to a form, just navigate to it, it'll just re-show the form already in memory
Note that some devices have a hardware back button. Clicking that will also automatically
show the previous form.

Android, BB and WP7 have hooks you can use to control what happens.

Android

^_jvmdo^5oftlnputMode_FORM ADJUST RESEE

C^^_ onDeviccBack
MM.H_\TM

*m-3
in*m

i*
o.

__3^* Defined

onDeviceMenu

Not Defined

headerOVertap

faise

footerOverlap

faise

i fWitkwt,

1.

t_

r
r

Note: by adding "code" and doing nothing, you've effectivelydisabled that button. WP7 and
BB have seprate properties (Enable Back and Ignore Escape) ifthat is all you want to do.

r
131

Exercise - Navigation & Expression Editor

kony

Objectives:

Be able to use the Expression Editor along with the Mapping Editor to pass data
between forms

Use the Event Editor to navigate from one form to another

Concepts:

The Expression Editor is used when you need to assign vales to objects that can't be
done using a simple mapping.

The Expression Editor gives you access to all Form objects, API methods, skins, etc

In the "Navigate to a Form/Popup" pane of the Event Editor the mapping source will be
the calling Form and the mapping target will be the destinatlon Form

Exercise - Navigation & Expression Editor

kony

Procedure:

This exercise will build on the previous app (Login).

Add two new forms to the app.

When the Login button is clicked, navigate to the second form, which should have a
label on it (identlfying it as Form Two) and a button.

When the button on Form Two is clicked, navigate to Form Three, which should have a
label and a button.

Set the text of the Form Three label to read: "<User ID> authenticated" , where <User

ID> is the value that was typed into the User ID TextBox on Form One. Assign a
custom skin to this label.

When the button on Form Three is clicked, navigate to Form One and clear out the
TextBoxes.

132

Exercise - Navigation & Expression Editor (cq^rU*


Do all of your work n the Event Editor, Mapping Editor and Expression Editor
Expression Editor

S5

frmThree.IblAuthentication.text =

1 ok |

* Content Assist is enabled in this text rea

;nr.Lcgi3.tbxCne.text + "authenticated "

Cancel

1 Clear | \
| Compile |
4

000000000000000
Select the below tems to build expression

Exercise - Navigation & Expression Editor (corj^'i*

WSSB 9:30 PM |
Enter your XYZ login credentlals

User ID:'

&BI]4B4:16PM

This is Form Three


lafong Authenticated

Password:

Goto Form One


Login

133

Action -Add Decisin

kony

Add Decisin

This action item is used to execute actions based on conditions.

The Decisin must be a Boolean expression - build using expression editor

Nesting is required to do "else" functlonality

8; Evenl iditor
Define Action Sequence

Enter expression which should e.-sluate totrue/false

I Action Sequence
+ Decisin :a==b
i/tme

_Alert

[2] Form/Pcpup

lkony
e *

Action -Add Snippet


yWd Snippet

This action item is used to execute small code pieces without defining a function in JS

FiWn^firi
1 .llmt faMI 1*i-hlrii -1 HH*lr.l -t*
aDC.at^cabe.ButciaMM -

-i nipprt; fiml myOo...

ca~

Cnp4a

pe*. ":= Mam.


!*=, "not. ii. Kd-.'|,
p3\

VERY useful for small amounts of code

Uses the expression editor

v.::

i- :.-

134

'

Action -Add Preprocessor Decisin

kony

Add Preprocess Decisin

This action item can be used to define code specific to a platform.

Action item defined will be applicable only to the selected platforms.

Useful to match code to rendered widgets Qust like #if def in code)

"

_ -", TI'..fntwan

*> tIMMCtty '> a*

For more granular control (down to model number, for example), use the
kony.os .devicelnfo API cali

XA

Action - Show Alert

Show Alert

kony
Define Alert -

indcales either one is mandatory

Type: Serror

Action to show an Alert dialog

General

to the user

MeiiageType: constant

!nternationali:ation

General

"

3 types: error, information and

^Message;

confirmation

Messages can be localized

Message can be simple text or


an expression (to show data)

Configure the alert title


(ignored for mobile web)

Button text is configurable (not


only for confirmation type)

C ^ e n t A ^ e n a h l e d i n , , - is te* ares

1 > 1
' Compile

la

Tille:
OK Label:

Customize the Alert Icn for-

Android platform.

H[x]

135

Actions (cont.)

kony

Add Comment

This action item is used to provide a comment to document your action flow

Comments are excluded when the code is executed.

Alternatively comments can be added using "If indicator in JS code.

Add Local Variable

Used to crate a local variables (String, number, Boolean) to use in your action
sequence

Similar to creating global variables in the Services tab


Variable Data

MaM

Define Columns

VMocIyyr twM

Dat

p mylocalColiection;'!
* FintName::trmg

SalT>pr Uia^j

iS* Addrewes::co!!ection

* Street"String
* city;:stiing
'* iiptode::itring

simple example

collection example

Event Editor - Services View

kony

Shows you the various app-wide components


_i Properties "i BestBuy Services '.~-~.

Global Variables

Data store keys

Defined services

Global Action sequences

/ ScraperView

s '*.' Global Variables

"*fcn applicationKey::string
jff glbLabe!Navigaticn::co.lection

Ix] glbPageCcunter;;number

Crate new entries (not for services)


Add

'^33glbTotalPagecounter::number
to glbReviewCount::number
"tn glbSearchText::string
a? glbTb18ackHcme::collection
33 glbTblBackProductL5t::ccllection
'aglbsSearchbuttonClicked::boclean
Txj glbLblCategcry::string

Jp glbTempcataD::strng
L DataStore Keys

Refresh

* xml services (5)

it. srvBestBuyHome
.1, srvPrcductList

Edit/delete items

jj,, srvProduct6ySearch
'* srvProductDetai

Add

El

dt

Delete

Refresh

jJt srvPrcductReview
ebservke-scap services (0)

9 javaservices (0)
** composite services (0)

** scraper services(0)

jsonservices (0)
tmplate services(0)
** looping-connector services(0)
''; Global Event Sequences (0)

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^H

136

r
Event Editor - Services View (cont.)

kony

Global Variables: They are used to store data across the application and are of two types:
Simple - Data (String, Number, Boolean) can be assigned.

Collection - This is a data set that has mltiple records. You can add as many columns
as you want to a collection and then add data to them.

m
Define Columns

Name: myCollection

Data

* P Cu5tomers::collection

r^ii

9 FirstName::string
* LastName::5trng
** Age::number
s rS1 Emai!s::collectcn
v* DisplayName::string
v* Email Address:: string
v* isPrimary;:boclean

r
Note: All the global variables defined here are accessible in the JS code modules but the
global variables defined in the JS code modules are not accessible from the Services
view.

XA

Event Editor - Services View (cont.)

,
-i*
kony

Global Variables (cont):

Creating global variables in the Services ViewONLY tells the IDE how to display that
variable in the various editors

< Using the example Customers variable below, the following line of code will execute
jUStfine: Customers=[fred="A", wilma="B"]

" When using the editors, however, you won't have access to a "wilma" key since it
wasn't in the definition (never mindthe fact that now there actually IS a wilma key)
Define Columns Data I
* cS3 Customers::collection

FirstName;:string
9 LastName.:stiing
<* Age::number
i ceP Emails::collection

9 DsplayName::string
v* Emai!Address::string
9 hPtimary.:boolean

Defining global variables is a best practice because:

For maintenance, you knowthe "shape" of the data without having to paw through
someone's code to see how they set the data in that table

For access, you now can access the data through the editors making activities like
data mappings much easier or even possible

r
137

Event Editor - Services Tab (cont.)

kony

Dafa Store keys: These are used to save data on to the mobile device persistently using
event editor. Data store keys can be defined only from Services Tab. Even data store keys
are of two types:

Simple - Data (String, Number, Boolean) can be assigned.

Collection - a table can be populated and data can be added.

Note: The data stored in these keys are saved on the device using the device's native data
storage mechanism

Using the event editor, you can:

Save data - assigning a value TO a key saves that data on the device (the data store
key is the Target)

Read data - assigning a value FROM a key reads that data from the device (the data
store key is the Source)

Clear data - assigning "" or nuil to a data store key, clears the data from the device

Event Editor - Saving data

kony

Data Store keys can be used to save data to persistent storage using Event Editor.

Assigning data TO the data store keys triggers the data save
Data from variables (IName &
Target

FilterBy: All

Search:

IData) are persistently stored by


mapping to data store keys.

W Variables

3 glbLengthmumber
cP IData:co)lection
p IName:strng

cfP IID:string
rff1 lDesig:string

On using this mapping, Kony IDE


generates the code to save the
data persistently.

m lName:string

I DataStore Keys
en gdsMyName-se5sion:string<->Variables.lName
cr? gdsMyDetail5:collection<->Variables,ID3ta:add
m lName-se5sion:5tring<->Vaoables.lData.lName

Data is stored persistently to


device using the Data Store key

m l!D'Session:stnng<->Variable5.lData.lD

cd !Desig-se5sion:5tring<->Variables.IData.lDesig

ames.

The data can now be retrieved

using the data store keys


Setting vales to nuil clears the
data

138

AA

Event Editor - Services View (cont.)

kony1 *

Data Store keys can also be used to read data from persistent storage using Event Editor.

Vxessing the data from the Data Store keys reads the data from device memory
HtiDy : Al

j '* *; ":

iu Dmq lattwwt rw}

'

Data can be read from Data store keys at


any point (app initialization, for example)

fH Ftn f<mO*t5*wttUyi
*

t*fcct

Mitm

< Common

ftt hwtttlnna/ tJ**Mo K*yiiihM.fln*

,T1 >>wWfcvvl**"

If no key exists in storage, nuil Is


returned

-.

- ,rl*if

On using this mapping, Kony IDE


generates the code to read the data from
persistent storage of device.

'>."

rn , b< k*MrboolMn

Copyright 2012 Kony Solutions, Inc. CONFIDENTIAL

277

XA

Eventobject

kony

Many times an event will have some data associated with it.

For some Kony events, you'll get passed various pleces of information in your event
callback function.

A typical example is that you're passed the widget that raised the event. You can have one
function handle 3 widget click events simply by checking which widget raised the event
programmatically and coding accordingly.

This automatically generated parameter is called the eventobject and is exposed in the
event editor.

"

MHM.WtMl(M.

IwaC^Kt

iii|ii

Passing it to a function cali

Accessible in the snippet

'

139

XA

Action - Invoke Sequence

kony

Invoke Sequence

Used to cali a previously defined


sequence marked as "global"

Dropdown will list all the


available global action sequences

3B

Select "Use as global" to use


Global action sequence as it is.
Edits will be reflected globally.

Input parameters
Param name

Valu

$ Event Editor

Define Action Sequence

Select "Use as local" to copy the


action sequence actions to this
event - they are now inline actions
as if you entered them yourself.

Action Sequence
4

Alert

4 <<S true

{:] Function:returnStnng

|3j Form :frmHome


4 '

Globalsequence: goHome
,J Snippet: frmHome.I...

j7i]Form:frmHome

Global sequences can be called n


code like any function. For

example, calling goHome o in JS

XA

Event Editor - Best Practices

kony

It's pretty easy to get confused when trying to map more complex business loglc in the
event editor - especlally if you're using data, manipulating tables, etc..

UNTIL YOU BECOME A PRO... use the event editor for straightforward things - the types of
things we've done so far

For anything complex, especially here in training, do t in code first.

Coding it allows you to match the series of steps and code the flow of events
sequentially.

You can insert print statements easily.

Nothing is hidden or "done for you" when you do the code.

It's best that you learn to master both techniques - you'll be able to determine exactly when
to use each technique.

Bottom line - if you find yourself getting all "wrapped around the axie" doing something in
the event editor you're probably doing something wrong OR doing it in code is better.

140

"

kony

Module - Selection Widgets


(Self Study)

Overview

kkony5^

The following widgets are classified as the Selection Widgets:

ComboBox

ListBox

RadioButtonGroup

CheckBoxGroup

Slider

Picker

These widgets help us gather some user Inputs by selecting one or more of the available
options that are presented by this widgets.

They also have common methods and properties for getting and setting information.

141

ComboBox/ListBox - Overview

kony

A ComboBoxwidget allows you to select a single Item from a drop-down list.

A List Boxwidget allows you to select single or mltiple tems from a drop-down list.
For example:

Selecting a Country from the List of countries. (ComboBox)

Selecting all the mobiles that a user has from the list of all brands. (ListBox)

In the Normal state only the default selected item would be visible.

In the Focus state drop-down list containing a list of tems s opened.

On selection, the selected item is displayed on the ComboBox/ListBox and the list Is
closed.

Note: For the ListBox, check the Mltipleproperty check box on the IDE to make multi
select. It s set as a single select by default.

ComboBox/ListBox - Various Views

kony

For the iPhone, use the View property to determine how these widgets get displayed.

The View property works as follows:

listView/onscreenwheel - displays as the wheel

tableView- displays as horizontal list of tems

toggleView- displays as a strip


Rock Paper ^

J Omer

142

ComboBox/ListBox - Various Views

kony1*

Images of how all the other devices display the ComboBox widget:

Android collapsed

Sdssors

r
r

BlackBerry Bold collapsed

{J

S-wr^

BlackBerry Bold expanded

Android expanded

Windows Mobile

Palm Pre

Rock

Rock

Rock

Paper

Scissors
Other

Pp#r

Scissors
Sduon

Other

Ottwr

Copyright 2012 Kony Solutions, Inc. CONFIDENTIAL

ComboBox/List Box - Drop-Down Image

235

* *

kony

The Phone, BB and J2ME allow you to choose the Image used for the dropdown indicator;

i.e. the arrow mark at the end of the combo box is customizable.

Use the Dropdown Image propertyto browse for the correct image

The dropdown image size vahes from platform to platform. For example:
iPhone 3 : 32 x32
Phone4 : 64 x 64
BB

: 10x10

When the size of the text is larger than the size of the ComboBox/ListBox:
-

iPhone automatically fits in the text by removing some text

The rest expand the widget height and the custom image will get stretched to fit

143

ListBox Additional Properties -Android

kony

Android has a slightly different set of properties for the ListBox:


List Icn: specifies the dropdown
image and the image shown in the
dropdown popup

Ticked Image: specifies the image


for a selected item. Replaces the
default

UnTicked Image: specifies the


image for an unselected Item.
Replaces the default
List Style: Default is show and
Spinner Style shows the selections
in a wheel control

CheckBoxGroup/RadioButtonGroup

kony

CheckBoxGroup allows you to make one or more selections when you have many choices.
When you select a check box, a check mark appears inside the check box to indcate the
selection.

[japple
Jorange
I>/1 banana

| Jklwl
RadioButtonGroup allows you to make one selection when you have many choices. When
you make a selection, a dot appears in the radio button to indcate your selection.
i Jverymuch
l J somewhat

144

CheckBoxGroup/RadioButtonGroup (cont.) ko 'V*


Ticked Image: Specifies the image to
be displayed when you make a

selection.

UnTicked Image: Specifies the image


to be displayed when a selection is
cleared.

FocusTicked Image: Specifies the


image to be displayed when you focus
an selected Item. (Available on BB only)

n n uch

Focus UnTicked Image: Specifies the


image to be displayed when you focus
an Unselected item. (Available on BB
only)

_^__

i*

CheckBoxGroup/RadioButtonGroup - iPhone kon** *

Phone's View property:

listView

tableView:

can have Group Cells set true or'

Grouped Cells set true

Grouped Cells set faise

faise

Ticked Image and UnTicked


Image properties
V.,l.n;l

v'alje2

toggleView:

Value 3

Can have View Style property


set to: plain, borderedox bar
Voluol
Vaaiiau^

onscreenwheel

"

145

Selection Widgets - How to Poplate Data

X'

koni%

To poplate data to any of these widgets from the IDE use the Master Data property.

Using the Master Data property dialog we can:

Set Display Vales and their Key

Determine default selections

Specify 18N keys

Checking the Use as test data in preview mode to ONLY use these vales during preview

With all selection widgets, both the Key and the Display Value are available for the selected
item(s)

XA

Assignment - Selection Widgets

kony

Objectives:

Be able to use the four selection widgets (ComboBox, ListBox, RadioButtonGroup


and CheckBoxGroup) in an application.
Be able to use preview mode to explore various display properties of selection
widgets.

Concepts:

'

A ComboBox widget allows you to select a single item from a drop-down list.

A List Box widget allows you to select single or mltiple tems from a drop-down
list.

CheckBoxGroup allows you to make one or more selections when you have many
cholees.

RadioButtonGroup allows you to make one selection when you have many
choices.

146

Assignment - Selection Widgets (cont'd)

kony

Procedure:
-

SBDe 10:12 PM

Ok, let's see how these widgets look

Crate a 1 screen app that has one of each:

Darkral

Snorlax

ComboBox

Plkachu

ListBox

RadioButtonGroup

L ;Groudon

CheckBoxGroup

l " ,'Wallmer

(".'Octlllery

Configure their Master Data with several


vales and play around with the various
options for each widget

[^jBulbasajr

Set the Master Data to be used for Preview

Check out your work with Preview mode

Run on several platforms including Mobile

1>f JCharmander
JSquirtle

Web and Phone


Copyrighl2012Kony Solutions, Inc. CONFIDENTIAL

293

A a

Selection Widgets - Poplate Controls

kony

In JS, we can poplate the selection widgets using the masterData property.
masterData takes sets of key-value pairs. For example:
myForm.myComboBox.masterData = [

["a",

"very much"],

["b",

"some what"],

["c",

"not so much"),

["d",

"not at all"]

To set a default selection, we'll use the seiectedKeys or seiectedKeyproperty (depending


on if the widget is configured for multi-select)

seiectedKeys takes an JS table of keys and seiectedKey takes one item. For example:
myForm.myListBox.seiectedKeys = ( "b", "c" ]

myForm.myRadioButtonGroup.seiectedKey = "a"

Note:there are no update data methods. Reset masterData to show new/updated vales

147

Selection Widgets - What Was Selected?

kony

Use the seiectedKeyvaiues property if the widget was set as multi-select. It returns the
array of selected key-value pairs . If nothing is selected, the return value is nuil.

For example, in our CheckBoxGroup example, I pick "apple" and "kiwi":


var selectedltems = myForm.myCheckBoxGroup.selectedKeyValues

selectedltems --> {{"a", "apple" },-{ "d" , "kiwi"}}

Get the first key with: selectedltems[ 1 ][ 1 ]


Get the first value with: selectedltems) i] [2)

Use the seiectedKeyvaiue property ifthe widget was set as single select. It returns the
array of the selected key-value palr (singular) . If nothing s selected, the return value is
nuil.

For example, in our RadioButtonGroup example, I pick "somewhat":


var selectedltem = myForm.myRadioButtonGroup.selectedKeyValue

selectedltem > {"b","somewhat"}

Get the key with: seiecteditem[ i ]


Get the Value With: selectedltem) 2 )

Slider Widget

kony

Slider is a widget that you can use to select a value from a defined range of vales by
movlng an indicator in a horizontal fashion.

Set Mnimum and Mximum vales in the IDE (vales must be integers)

All slider value properties are read-only properties - can't set these vales in code

Slider widget is available on: iPhone, Android, Blackberry, Windows Phone 7 and Palm.

Note: by default, Render is turned on for only those platforms

148

How to Get the Selected Vales

kony

The Slider's onSlide event is triggered with a change in the selected value. This event is
called for every valu change AS you are sliding.

The function you specify can have this signature:


function onSlideCallback(sliderObj, selectedValue)

Typical use is to update a label with the value. Use the widget parameter to know
which slider (if more than one) was changed

The onSelection event Is triggered when the selection is made. This event is called when
you have stopped sliding (ralse finger or stop presslng arrow keys)

The function you specify can have this signature:

You can access the final value with sderob j. seiectedvaiue

Alternatively it can be accessed using <formlD>.<sliderlD>.selectedValue

function onSlideCallback(sliderObj)

Keep processing to a minimum in the onSlide event. Doing anything processor intensive
can make for a poor user experience

Slider Widget- Display Properties

kony

Min Label: text or number to be displayed for the


minimum value

Max Label: text or number to be displayed for the


mximum value

Min Label Skin: skin to be used for Min Label text

Max Label skin: skin to be used for Max Label text

Thumb Image: image to Indcate the thumb.


Focus thumb Image: indcate that there is focus on
the thumb

Left skin: skin for the left side of siider bar

Right Skin: skin for the right side of slider bar -

149

PickerView Widget - Overview

kony

A PickerView widget uses a spinning wheel metaphor to display mltiple sets of vales and
allows you to select a single combination of vales.

You can select a single combination of vales by rotating the wheels and aligning the
desired row of vales with the selection indicator.

It is available on OS, Android and Windows Phone 7.

1HF
Ford

H
Suzuki

LHonda

uu=.

Green

2010

Blue .

2011

I Green

2009

Suzuki ! Blue

2010

Honda ] Black

2011

PickerView - How to Poplate Data (IDE)

You can set the data through the IDE using the Master Data property.

The various "columns" are called components.

The sum of all components widths should be 100.

kony

sa

'

I:

Currently, you can only use text for the display value (no images).

150

PickerView- Howto Poplate Data

kony

Like other selection widgets, you set the data using the masterData property.

masterData takes sets of key-value pairs, for each row along with the width. For example:

myForm.myPicker. masterData = pickerData


var pickerData = [

[ [ "d", "Ford" ] , [ "c2", "Suzuk" ] , [ "c3", "Honda" ], ["c4", "Chevy"), ["c5". "BMW"], ["c6", "Kia"], 40 ],
[ ("y1", "2010"] , ["y2", "2011"] , [ "y3", "2012"], 30],

[ [ "Col1", "Red" ], [ "Col2", "While" ], [ "Col3"," Blue" ], ["Col4","Black"), 30]


]

Remember! The widths need to add up to 100

To set selected keys use the seiectedKeys property


seiectedKeys takes a table of keys (one for each component In order). For example:
myForm.myPicker.seiectedKeys = {"c3","Col3","y2"} > Honda, Blue and 2011

r
PickerView - Know What was Selected

kony

To know the selected vales, use the seiectedKeyvaiues property.


seiectedKeyvaiues returns the array of selected key-value pairs. If nothing is selected, the
return value is nuil.

mm

Suzuki ]Green
Honda

For our previous example:

User selected: Honda, Blue and 2011

we can get the selected vales with:

Blue

Chevy JBlack

'2010
2011
2012

var mycarvalues myForm.myPicker.selectedKeyValues

myCarValues Will be: [[ "C3", "Honda"], ["Col3", "Blue"), [ "y2", "2011"] ]

151

PickerView - How to Update/Remove Data

kkony.V-

To set the data for a specific component, use the pickerview. setComponentData method

Syntax is: pickerOb j. setComponentData (componentlndex, data) where:

componentlndex: is the component ndex you're setting the data for (starts with 1)

data: the data table for the new vales

For example, to add "2008" to our list of years:


var pickerBasic =

{ id:"picker",

info: { key: "PickerView" },


skin:"pickerSkin",
focusSkin:"pickerFSkin",
masterData:)

[ ["yl","2009"],["y2","2010"],["y3","2011"],
[ ["mi","Jan"],

["m2"

40],

"Feb"],["m3","Mar"),["m4","Apr"], 60

] ],

isVisible:true,

seiectedKeys:["y2","mi"] };

PickerView - How to Update/Remove Data

|<ony*

var pickerLayout = {margin:[5,5,5,5], marginlnPixel:true,

widgetAlignment:constants.WIDGET_ALIGN_CENTER, hExpand:true,
containerWeight:99};

//Creating the PickerView.

var pickerObj = new kony.ui.PickerView(pickerBasic, pickerLayout, {});

//setComponentData method cali to add data in IndexComponent 2

pickerObj.setComponentData ( 2 ,[("1", "2008" ] , ["2", "2009" ] , ["3", "2010" ],


["4","2011"],["5",

"2012"]));

152

r
r

PickerView - How to Set a Key in a Componer^* > *

To Set default vales in the PickerView, use the pickerview. setSelectedKeylnComponent


method.

"

Syntax S: pickerview.setSelectedKeylnComponent(key,componentlndex) where:

key: is the key value you want to set as the default

componentlndex: Is the ndex (starting at 1) of the component you are setting the default
for

Using our example, to preselect "Green", enter the following:


pickerObj.setSelectedKeylnComponent ("m2",

2);

Note: Typical to use setSelectedKeylnComponent in the form's preshow event or in the


onSelect event if a particular key was selected n one component to set an particular
key in another component.

Note: Keys are strings. In JS 2 does NOT = "2"

Switch - Overview

kony

The Switch widget is identical to the Switch Control (on-off switch which is noncustomizable) in iPhone.

fo

OFF

The Switch widget gives you the flexibility to customize the text and the image of the switch
to match your requirements.

r
This widget is available only for iPhone, Palm and Advanced Thin Cllents

r
r
r

153

s*

Switch Widget - Some Properties

kony

Left Text:Specifies the text to be displayed on the left portion of the Switch.

Right Text:Specifies the text to be displayed on the right portion of the Switch.
Right text

Note: Left Texf and Right Txalso support internationalization.


You can specify the Left and Right images in the skin:
<

tSw

Left and Right images will expand if the


text is more than image size. If the text
is still large then it will be cut and it will
NOT wrap to the next line.

Add New Mtk

Wtntu>.P<*pti1in

Uyto feup /
W^j.
/
,[*1I"-iJf

Image size should be more than text

**/+*>*

size .

!...'-- F;.-

es

S
jT

jS

*~~

a~

Note: the middle concave is added by OS


|

Switch Widget - Know What was Selected

k-;\-*

//Defining the properties for Switch with the ID :"swtch"

var swtchBasic = { id:"swtch",

info: {key:"switch"}, leftSideText:"on",


rightSideText:"off", skin:"swchskin",
selectedlndex:0, isVisible:true};

var swtchLayout = { margin:[5,5,5,5], marginlnPixel:faise,


widgetAlignment:constants.WIDGET_ALIGN_TOP_LEFT,

containerWeight:99};
//Creating the Switch.
var swtch = new kony.ui.Switch( swtchBasic, swtchLayout,

{} )

154

Switch Widget - Know What was Selected

4'

kony

onslide: This event is triggered when you slide the Switch and there is a change in the
selected value .

Use the seiectedindex property to determine what value was selected.


var

index =

index = i

swtch.selectedlndex

if the left side is selected.

index = 2 if the right side is selected.

The following code snippet displays the selected value.


function onSlideCallback(switchWidget){
var

index =

swtch. selectedlndex

if(index == 1)
kony.print("on left side")

else if(index -=2)


kony.print("on right side")
}

"

Switch - Considerations & Limitations

kony

Considerations:

Use a switch widget when you have a single question with 2 possibitles.

Typical usage Is as a switch: on/off, yes/no, 0/1. Typically sets the state of a value

Common to use this to set preferences (ex: remember me on a login screen)

Since this widget is not used across all platforms, you will need to use another widget
for those other platforms. Remember to turn render faise for the ones where you use
the switch.

- it's a NATIVE Phone look so definitely use It for iPhone. Using it on non-iPhone
advanced Thin Client platforms could look out of place to the user.

155

"!

Selection Widgets - Limitations

kony

All platforms:

You cannot place a selection widget inside a Segment

You cannot place images inside a selection widget

J2ME platform:

If you do not specify the focus skin, it is not possible to identify the traversal.
Thin Client:

The ondone event is not supported on the basic versin of thin client as the Java script
s not supported on browsers of basic devices. You'll need to trigger getting the
selected value some other way

The HExpand property is not applicable.

focus skin is not supported.

Assignment - Selection Widgets

kony

Objectives:

Be able to get the currently selected vales in a PickerView widget

Be able to get the value of a Slider widget as it's being moved

Concepts:

selectedKeyValues returns the array of selected key-value pairs. If nothing is


selected, the return value is nuil.

To set the data for a specific component, use the


pickerOb j .setcomponentdata method

The Slider's onslide event is triggered with a change in the selected value. This
event is called for every value change AS you are sliding

Procedure:

Build an application that has a PickerView, Slider, Button and Label

PickerView configuration:

Have a bunch of vales in a 3 slot PickerView (car makes, colors and years).

156

Assignment - Selection Widgets (cont.)

kony

Slider configuration:
y 10:10 PM

Make the slider such that t will slide between 1 and

]J-

the number of car makes you have.

Hook up the slider so that after making a selection,


it will pick that key value for the car makes (either
have a big IF statement OR set your car keys such
that you can genrate the key with the slider
number - ex. keys of "a1", "a2", etc - you'd just have
"a" and then append the slider value to genrate the
key).

Suzuki

P"!

Honda

Red

2009

Chevy

Green

2010

What did I just select?

Button configuration:

you plcked a Red 2009 Honda

Clicking the button will poplate the label with the


-

selected car details.

157

Table of Contents Day 3

kony

:"$ Form Basics

| Segment Widget
1 Debugging-Inline debugger
^^^| Module - BrowserWidget

1 Module -App Properties &App Life Cycle Events

| Services with Network APIs


1 Network API

Copyright2012KonySolutions, It c.

CONFIDENTIAL.

315

158

r
4'

Form - Overview

kony

Form is a visual rea which acts as the topmost container holding other widgets required
to display a basic application screen.
Form Is the starting point of an application.

Any number of widgets (Container, Basic, and Advanced) can be placed in a Form. But a

Form cannot contain another Form.

Form occupies the entire width of the screen.

Height of the Form doesn't have a llmit and is determined by the number of widgets
present in the Form.

A widget placed directly n a Form always occupies the entire width of the Form.
Height of a widget is determined by Its content.

mmmmmm

Form - Overview (cont.)


Note - An application can have

O Applications 3

any number of Forms. A Form


which

is

set

as

"Mark

kony
c,. Navigator
"

B G]2 TestApp
B forms (2)

as

Startup" is displayed on starting

B *Q mobile (2)

the application.

E-lfuHSOSP
,- frmHon-

J> tablet (0)

\ desktop (0)
1 6 popups (0)

S ?_* templates (0)


H-fc modules (1)

Copy

H Delete
Rename

Ctrl+C
Delete
F2

Mark as Start Up
Set Nature

! v/ webjnodule (0)
B < resources (2)

f Fork

B ^i. services (0)

; Refresh

F5

Jetty Web Server


i

Only the form marked "Mark as startup" during the designtimeis loaded into memory
when the application is started.

" Other Formsgets loaded into memory ,when an Application gets loaded.

r
-

159

Form - Overview (cont.)

kony

0*

A Form s defined to have a Ufe cycle method that gets called at appropriate events. These
events will allow you to manage the application for better handiing of resources.

Form Life Cycle Methods :


1. addWidgets

Property:

Name

Value

4 :.; General

2.

Init

3.

preShow

4.

postShow

5.

onHide

title

frmHome

title il8n Key

None

renderer

Phone:true,Andrcid:tru...

header

Nene

footers

None

enabledForldleTimecut

faise

type

FORM TYPE NATIVE

Appearance

6.

onDestroy

G Skin
* & Event

Form - Life Cycle

init

Nct Defined

preShow
postShow

Not Defined
Not Defined

onHide

Not Defined

onDestroy
cnOrientationChange

Not Defined
Edit.,.

kony

Application ininazed

Actions

-Access any Widget


-Access any
-preperty

-callsioivO

ve addWidgets()

160

Form - Life Cycle Events

kony

addWidgets
addWidgets callback event is invoked by the platform when the form is accessed for
first time after its construction. This function gets executed only once on in lifetime of
the form. If a destroyed form is accessed, the form is re-initialized and this callback s
once again invoked. This event is explicitly triggered for dynamic widget construction.

For accessing its widgets or

Accessing its properties or

Invoking form show() method

Ex :- Assume frmDynamicform is not yet initialized. Then the addWidgets lite cycle event
triggered for any of the following methods.

frmDynamic.labell

frmDynamic.title

frmDynamic.show

Form - Life Cycle Events

y\
kony

Init

Init is Invoked only once in the form's life cycle, when the form is ready with the
widgets hierarchy. This is called after the "addwidgets " method, and allows user for
the one time initializations. When form is destroyed and reused again, init gets called
as a part of form's lifecycle.

Note :- Masterdataload and Transactionaldataload are replaced with init method.

preShow
This event is triggered just before the form is visible on the screen.

This event is triggered every time the form is shown.

This event is called even on device back or while navigating backto the form through
title bar navigation tems.

Note :- in case ofTC preShow and postShow will notget executed when navigating using
browser "back"

161

Form - Life Cycle Events

kony

postShow

postShow is triggered every time after the form is rendered on the device's screen.

During the execution of the network cali in this event, user cannot perform any action
on the form and a network Indicator is displayed.

This event can be used to display other forms (e.g. Interstitial screen) during service
calis

For example, here is where you'd cali the backend service to retrieve the data to be
shown on this form.

Gets called even on device back or while navigating back to the form through title bar
navigation tems.

onHide

This event is called when the form goes out of the visibllity.
>

Another form is about to initiate once after this event.

XA

Exercise - Form events

kony

Objective:

Be able to understand the execution flow of all the lifecycle events of a Form.

Concepts:

Initevent is triggered after the addWidgets event but before the preShow event.
The preshow event is triggered just before the Form is displayed when a
formName.show() or a "Navigate to Form/Popup" action is called.

The postshow event is triggered after the Form is displayed to the User.

Procedure:

We are going to make a simple change to our navigation exercise


On Form One (Login form), configure allthe events with printstatement indicating so
and so event is getting executed. For Example for preshow event, configure below line
using a snippet:

/cony.prinf"""""**"****'""*""'**'" Executing Pre Showeventof theLogin Form.")

162

I
I
r

Exercise - Form events (cont.)

kony

Now crate another form consisting of three buttons with text as "Go Back to Login",
"Destroy Login"

On click of "Login" button on Login form, navigate to the new form.

On click of "Go Back to Login" navigate back to Login form using formName.show()
method.

On click of "Destroy Login", destroy the Login form using formName.destroyO method and
navigate to it.

Now on launching the application, as the form is initialized first time, all events get
executed and you will see all the print statements.

On click of "Go Back to Login", only pre show and post show events of Login form gets
triggered.

On clickof "Destroy Login" all the events of Login form gets triggered as life cycle again
starts.

"

163

XA

Segment - Overview

kony

Segment acts as a predefined tmplate to poplate mltiple rows or records of similar type
of data at runtime (same as the iPhone table view)
Segments are typically used to show a list that can be:

Static - for example, used as a men

Dynamic - to show service or transactional data like a list of products

For example, here is a screen showing products:


nlBLtti 5:33PM

tftr
Here is the form at

t..v;. . :<,; | :-,-

runtime.
Ccoy DVDFJye' trijWG
139.W
<-.-...mi .-

'

Here is the form at


O* MI Di

design time.

Dynt*m DVDW^*i
wthMO UpcioTvfrUon

Bit tfw-Jtr 2.i

fc5*n0vD*yw
Men

Segment - Overview (cont.)

kony

Segment as a container supports only the following wicgets

Button

Image

Label

Line

Link

Rich Text

Phone

Box

Switch

ge applications

f Alarm Clock

72.00KB

1 Android keyboard

* 80.00KB

Other widgets cannot be placed inside a segment.

flL Android System

^P 0.00B

Browser

"

5.81MB

Calculator

4f

0.00B

Camera

336KB

H com.android.gesture.builder

The segment exposes it's own onRowClick event.

If a button is used in a segment, you can have a seps rate onClick event for the button and
the for the segment.

Copyright 2012Kony Solutions, Inc. CONFIDENTIAL

328

164

"

mimBm^^^m

Segment - Orientation

kony

Segment as a layout allows widgets to be placed either vertically or honzontally using the
orientation property.

This property should be set before adding any widget to the segment.
Setting this property to BOX_LAYOUT_VERTICAL means:

Widgets can only be placed vertically n this orientation.

A widget placed n this segment will always occupy the entire width available.

VBox widget cannot be placed inside a segment in this orientation.

You can use an HBox widget if you need to allgn widgets honzontally
Segment with widgets aligned vertically

Labels placed vertically to


show employee details

HBox is used to place


widgets horizontally.

Segment - Orientation (cont.)

kony

Setting the orientation property to BOX_LAYOUT_HORIZONTAL means:

Widgets can only be placed horizontallyin this orientation.

Awidget placed nthis segment will always occupy the entire height available.
HBox widget cannot be placed Inside a segment in this orientation.

You can use an VBox widget ifyou need to align widgets vertically
Segment with widgets aligned horizontally
first Name

VBox is used to place labels


vertically to show employee

Last Name

details.

Employee ID

Placed two image widgets


horizontally in the segment

Designaren
Vertical

165

AA

Segment - Views

kony

The viewType property indicates how the segment widget should be rendered at runtime.
The viewType property can be set to table or page view
SEGUL VIEW_ TYPE_ TABLEVIEW:

Each populated row of the segment tmplate would be placed one after the other
vertically in a tabular format.

Default & most commonly used view for Segment.

For example, display user accounts and vales in a list:

-:::^rv. 'lame

Acccun: L5l:-n:r

Accounts Overview

Segment at design time

Checking 494

$2000.34

Segment at runtime

Checking 490

S400

Checking 495

1000.19

Savtngs 567

Segment - Views (cont.)

$4000

A'

kony

SEGUI_VIEW_TYPE_PAGEVIEW:

Each populated row of the segment tmplate would be placed horizontally.

Each row can be accessed using the left or right swipe gesture on the segment rea.

Page indicators (optional) will be displayed at the end ofthe segment to display the
pagination.

Additional properties available for this view for better Ul experience:

Need Page Indicator: Specifies if the page indicator must be displayed when in a page
view.

PageOnDot Image: Specifiesthe imageto indcate that the page is currently being
viewed.

PageOffDot Image: Specifies the image to indcate that the page is notbeing viewed.
Note: No default dot Images are displayed if"Need Page Indicator" property is set to true
and other two Image properties are not provided.

166

; t

Segment - Views (cont.)

kony

page view navigation:

On touch devices, right/left gesture on the current row rea will result in the
next/previous row of the segment respectively.

On non-touch devices, like Blackberry Bold, left/right click of the keypad/touch pad
provided will result in navigation to the prevlous/next row of the segment.

Accounts Overview
Checking 494

Accounts Overview
Checking 490

Checking 495

page view properties


Accounts Overview

ka

Segment - Views (iPhone & iPad only)

kony

Apart from the earlier mentioned views , Segment also persiststhe following view Types:

SEGUI_VIEW_TYPE_COVERFLOW

SEGUI_VIEW_TYPE_STACK

SEGUI_VIEW_TYPE_LINER

SEGULVIEW_TYPE_ROTARY

SEGUI_VIEW_TYPE_INVERTED_ROTARY

ir Appearance
oriental.. BOX.LAYOUT.VERTICAL
margin Edit

padding Edit
Sire (pix( (448,200)
widtt 448

heigr 200
Size(%)

(100,45)

width 100

heigr 45

'

SEGUI_VIEW_TYPE^CYLINDER

showScn true

viewTyp. tMI&WlhAM-JMma

needPag true

SEGUL VIEW_ TYPE_INVERTED_CYLINDER


Mode

wem 1

Platform

Valu

U\ Default (All)

SEGU.VIEW.TYPE.PAGVIEW

Phone

egulvie'.v.tvp.page'v'ie'.v
segu vie1,'.' type coverflow

segul.view type stack


segu view type linear

Cancel
JC~

SEGU.vlEW.TYPE P.OTATORY
SEGU.V1EW.TVPE INVERTED ROTARV

SEGUL'.IEW TYPE CYUNOER

SEGU VIEW TYPE INVERTED CYLINDER

167

kkony*

Segment - Static Data Population


The following displays the setting of segment data via the Master Data property

Select the Use as test data in previewmode option to use this configured data only for
preview mode

Master Data dialog


Form layout

Rster Dato for Segment

r Usebelow data forpreview modeonly

WAcouriB-ame.txt

I IbWccountHame.i lSiy

KAccountf3al.txt

1IjUccouiBalJlftey

Chedong-49-1

Norte

110

Hone

Checking-190

None

S1900.20

None

Chedong -B5

Hone

S1200.16

None

Savings567

None

1600

None

A segment (yellow outline) with 2 labels:


biAccountName and biAccountBa

jhe 2nd and 4,h columns are for internationalization

XA

Segment - Dynamic Data Population

a
*i%
kony

To set the data dynamically, we need to provide a set of key-value pairs for each "row" of
data.

The key should match the widget name and the data will be what is displayed by that
widget

For the example on the previous slide, our data might look like:
mySegData =

{biAccountName
{biAccountName
{biAccountName
{biAccountName

:
:
:
:

"Checking 494",
"Checking 490",
"Checking 495",
"Savings 567",

biAccountBa
biAccountBa
biAccountBa
biAccountBa

:
:
:
:

"$2000.34"},
"$400"},
"$1000.19"},
"$4000"}

Use the setData method of segment API to assign the data to the segment.
For example: myForm.mySegment. setData (mySegData)

The segment will then update to show this dataset (if on the current form)
The data corresponding to a widget will not be shown If its widget ID mapping is not part
of the assigned data.

168

Segment - Widget data map

kony

To do this, you must set up a widget data map that tells the segment which piece of

Also send a dataset to a Segment using other keys (not the widget ID)

data should be shown by which widget.

<form ID>.<segment ID> .widgetDataMap = Dbject Array> where.'

Setting up this must be done BEFORE calling the setData method

<object Array> is a collection consisting of key-value pairs where the key is the
widget name and the value is the key in the dataset.

Using our previous example, if the data were:


mySegData

[{acct
{acct
{acct
{acct

"Checking 494",
"Checking 490",
"Checking 495",
"Savings 567" ,

bal
bal
bal
bal

:
:
:
:

"$2000.34"},
"$400"},
"$1000.19"},
"$4000"}]

We'd set up our widget data map as follows:


myForm.mySegment.widgetDataMap={biAccountName: "acct", biAccountBa: "bal"}

We could now cali our setData method and the segment would know where to get each
piece of data and which widget to assign it to.

Segment - Hidden Columns

kony

Hidden columns of a segment allow you to store more data, for each row, than s displayed
n the segment

For example: you want to show the account name and balance but you also need to know
the account ID f the user selected that row but don't want to displaythat account ID to the

You have access to ALL the data (displayed and hidden) in the user selected row

user.

1 Define your segment as we've done before with the 2 labels for account and balance

Set up your data to include this new column of data

Define a hidden column named accountiD

For the selected row, you can now access account name and balance (both displayed
to the user) and accountiD, the hidden piece of data

169

Segment- Hidden Columns (Static)

kony

Specify hidden columns in the segment's Hidden Columns property.

Open the dialog and add your hidden columns and identify their data type

Once done:

These defined hidden columns will be visible in Master Data property and can be
populated like any other column

You can also specify data for them using the segment's widgetDataMap property
I lidden Columns Cdilor

XLttftiGgMWnjn*

) Irpt

MtttB

(P1

f*

f"*

Segment- Hidden Columns (Dynamic)

kony

Followingcode snippet sets the data for a segment dynamically along with the data for
hidden columns:

First poplate the required data into a JS array:


mySegData = [{acct
{acct
{acct
{acct

:
:
:
:

"Checking 494",
"Checking 490",
"Checking 495",
"Savings 567",

bal
bal
bal
bal

$2000. 34",
$400"

$1000
$4000

19"
,

acctID

"103'

acctID

"104

acctID

"105

acctID

"106

>r
},

'}
'}]

" Then map your data (not necessary if the data keys match the column ames):
myForm.mySegment.widgetDataMap={biAccountName:"acct",biAccountBa:"bal"}

Finally, poplate your widget with data


frmHome.mysegment.setData(mySegData);

Altematlvely hidden column value can be assigned to some widget in the next form
using expression editor.

Note: ifyou do everything through code, you don't need to set up the hidden columns. you
can access the data by the key(s) in the dataset

170

r
Segment - accessing the selected row

-i*

kony

The segment exposes these properties to retrieve the data from the selected row of the
segment:

x^

selectedlndex: It is a 1-based ndex containing the index of the selected segment


row (it's also writable to forc focus on a segment row).

n.

selectedltems [ o ] : will returns the actual data of the selected row n the segment
along with the hidden data (if has). The returned data is an object.

cP

r
-i ^

In our example, if the user clicked on row showlng "Checking 490", then:

myForm.mySegment. selectedlndex

willbel.

myForm.mySegment. selectedltems) 0 ) will contaln the data specific to the


selected row:

var selectedData = myForm.mySegment.selectedltems[0]

selectedData.acct -> "Checking 490"


selectedData.bal ->

"$400"

selectedData.acctID ->

"104"

Note: If we used the widget/hidden column ames (no widgetDataMap), then we'd access the
data with those keys.

i>

Segment- Mapping Editor


r

kony

You can access the segment's selected rowthrough the Mapping Editor
As a Source, the segment will make availableit's selecteditemsproperty

Mapthose vales to other widgets, variables, function parameters, etc.

-.,._ 1

'

T'JZT'

^-_l

Shows

<?33~ r^i

selected vales

:E~

mapping the
segment's

to other labels
on the form

- M

":z:.~\

"

171

Segment - Skins

kony

Following are the different skinning options available for Segment:

widgetSkin
Specifies the skin to be applied to the entire SegmentedUI.
frmOne.segOne.widgetSkin= seg2Normal

rowSkin

'

Default skin for the segment.

This skin will be applied when the segment row is not focused/selected

You can set this skin value In code. For example (assuming I have created a segment
skin called "skSegmentNormal"):
myForm.mySegment.rowSkin = skSegmentNormal

mmm*m

Segment - Skins (cont.)

'i

kony

rowFocusSkin

Determines the look and feel of the segment row that is focused/selected.

Important to provideto give user feedback when he/she selects a row (critical for nontouch devices to see which row is focused)

You can set this skin value in code. For example (assuming I have created a segment
skin called "skSegmentFocused"):
myForm.mySegment.rowFocusSkin = skSegmentFocused

172

Segment - Skins (cont.)

kony

alternateRowSkin

Specifies the skin that is applied to every other row in the segment when not in focus.

Used to provide contrast between rows

You can set this skin value in code. For example (assuming I have created a segment
skin called "skSegmentAlternating"):
myForm.mySegment.alternateRowSkin = skSegmentAlternating

sectionHeaderSkin

This skin is applied to the section headers used in the segment.

This skin is applicable only when the Need section headers property of the segment Is
set to frue.

You can set this skin value in code. For example (assuming I have created a segment
skin called "skSegmentHeader"):
myForm.mySegment.sectionHeaderSkin = skSegmentHeader

Event Editor Equivalent

kony

If we wanted to do this exercise ALLn the event editor, here's what we would have had to
do:

Add a Hidden Column to our segment:


5

Hidden Columns Editor

Manage hidden columns

'Hidden cclumn name

Type

prcductlD

text

Set the hidden data in the Master Data property:


Master Dato for Segment
Click on column mele icrt

Segment without Sections


, Use as test data n previewmode
IbIName.trt

IbIName

18key

IblPrtce.trt

lblPrice.18fce',

picture fame

None

SI 2.00

None

1001

teapct

None

S3959

None

1002

None

ares rug

None

S129J0

None

1003

None

cabinet know

Norte

SI.59

None

1004

None

-.-

None

S38.29

None

1005

None

prcductID.txt

productlD.il6k...
None

None

173

XA

Exercise - Segment Data

-i*

kony

Objectives:

Be able to poplate a Segment programmatically

Be able to access the selected row of a Segment

Be able to set and access "hidden" data in a Segment from JS code

Concepts:

The setData () function Is used to assign data to a Segment in JS code

If the widget ames and data keys don't match, the widgetDataMap method can be
used to define a mapping from data to widget

Hidden columns of a Segment allow you to store more data in each row than are
displayed in the Segment, but you have access to all of the data

A Segment exposes selectedlndex and selectedltems [ 0 ] properties


allowing you to retrieve the data and ndex of a selected row.

Exercise - Segment Data (cont.)

kony

Procedure:

Now let's poplate our Segment with data from JS code.

In the form's preshow event cali a function that creates a local array with the product
data using keys called: "name" and "pnce". For example:
var segData =

{name : "picture frame", price : "$12.00"},


{name : "tea pot", price : "$39.99"},
{name : "rea rug", price : "$129.50"}
]

Set your Segment's widgetDataMap property to map the keys ("name" and "price")
to the Label widget ames.

Cali your setData method.

You should see a Segment just like before:

Note: Aslong as the Master Datahas the Preview data option checked, it'll NOT be used
when you compile and run.

174

*4

Exercise - Segment Data (cont.)

kony

We'll now do 3 things to our app (all in JS code please):

1. Change the Array object to have a 3rdpiece of data "productID" and poplate those vales
with some unique numbers ("1001", "1002", etc).
2. Crate a new Form with 3 labels on it: IbIProductName, IbIProductPrice and IbIProductID.

3 In the Segment's onclick event, cali a function that sets the second Form's 3 Labels with
the data from the clicked row and then show that second Form (remember, use
formName.show())

Run and enjoy!

nibJjJ^
alcture frame

1:02 AM

$12.00

lea poi
'rug

SBD 1:02AM
Jarea rug
$129.50

$129.50

cablnet knob

$1.59

jish sel

$88.29

Il003

Oh, and feel free to add a back button to the second form (use event editor)

Exercise - Segment Data (cont.)

kony

Do the same exercise using the event editor only - no code.

Note: don't delete your code, justdon't cali it. You'll want to be ableto hook your code back
up later on and be able to run it both ways (for the master data, for example, to turn that

"off", and set it in code, you only need to check the "use In Preview" option and it'll not be
used when you build).

Turn off yourcode in pre-show (thatset the data) and use Master Data.

It's important you know how to manage segments andtheir data BOTH ways. As we move
on into more advanced stuff, you'll see which technique makes sense for you.

Sftj]<3 1:07 AM
Jigure frame
tea uoi

$12.00
$39.99
$129.50

Eish_set_

175

Inline Debugger - Overview

kony

Kony Studio provides a Debugger to detect and diagnose runtime errors in applications.

Kony Debugger follows a Client/Server design.

Debugging Server is hosted through Kony IDE using Kony JS Debug perspective in
eclipse.

ADebugging Client will be embedded into each application during the build process.

When launching in Debug mode, this Debugging Client connects to the debugging server

using the IP address and port number configured with theapplication during the build
process.

Both Server and Client application shouldbe running on the same network for debugging to
work.

This design allows the developers to debug an application remotely running on a device as
well as on an emulator/simulator running locally.

Note: Debugging is currently supported for JS on Phone andAndroid platforms only.

176

Inline Debugger - Overview (cont.)

kony

Kony Debugger can be used to control the execution of an application using the following
available options:

Setting the breakpoints in the application flow.

Suspendlng the launched applications for debugging.

Stepping through each line of code to understand the runtime functionality.

Examining the content of each variable during the application flow using the variables
view.

Note: Kony Debugger allows only one platform to connect to the Server at a time.

Inline Debugger- Prerequisites

kony

Ensure that the following Kony Plugins are available in dropins/pluqins folder of the

eclipse:

'

"

org.keplerproject.ldt.debug.core.jar
org.keplerproject.ldt.debug.ui.jar

org.keplerproject.ldt.launcher.jar

While building an application for debugging, ensure to select the build mode as debuq

from application properties (Buildtab).


mmmaa

LU
Jtate;&JM

App Settorj; Najive App Splosh So-gen (Native App, SPA) Mobte Web Desl-top Web Push NoBficabon

"3
f"~ Remove pontstatements mcustoni modules {Recommended teltma for proaucOon relase)
Note: To avoid tompiation nsues please have the print statemenls n a mote Ime.

P Podasethe appIttBbon codetonowiththeruntime bnary


r Usenos ftxBlackberi-v Mobe Native App
Note: Recommendedonlyif yon see Bad DNSExcepBon* n kBerr y log (Bes.

P* Padtaoe the applicabon code alono, withthe runtunebriary


K? EnableSmoothScroing

Build the application for required platforms for debugging.

177

Inline Debugger - Kony JS Debug (Android) k -i*


Switchthe perspective to the "Kony JS Debug" and configurethe app.

Crele, manage. and runconfigurolions


; Kony 35 Debug - TestApp/fomis/mobiIc/fnriHoine.kl KonyOne Studio
Project

Jrs-

Run

Wndow

Hetp

11> - o 4

Ejff Kony JS Debug ^Debug

Kony I Hb 1New.configuratioo
Debug As

^Navigator

beb
OrgarWe Favontes...

Name: | tie.-tj.oeifigura ton

9 EdcseAppkabon

5 JavaAjjpW
"L lavaApotcatan

1 HOSfc

' |locawst

A JUnit

jij JUrHPtug-iTest

.,'Kony Acrjiication
B <S KonAppkatwiAndiod)

I Showdebupoernetworkconvnurvcation consol

IP wvr^connojratJDn

#. Kony ApokabonPrione!
# 05& Framework

, RemteJava Appkahon

:tmatt!*dl.of liilems

I Cebjg |

Posa

Click on "Debug" once after the configurations are completed.

Note : Incase of android Debugger Port should be changed to Jetty HTTP Port.

VL
Inline Debugger - Kony JS Debug (Android) kon-v

Once the Debugger is started then an application will be created with the name of the
Debug Configuration.
To view this application Click on

:','- KonyJSDebug- New_configuraton/segmer


File Edit Navigale Search Project Run

O *

UJ

*t ~ O - <4, *

Window -> Show View -> Other -> General -> Navigator -<Jg Kony JS Debug | Debug
Here the name is "New^configuration".

Kony

^ Debug c_~. Navigator t


y \. New_configuraticn
X .project

p
^
^
l*
^
lP

A breakpoint suspends the execution of an

application at the location where the break point is set.

Breakpoint can be set in any these JavaScript files.

Once click on resume debug then the control


will stop at the break point.

applicaticn.js
appskins.js
fimSegmentTet.js
frmShowDetails.js
konylibrary.js
segmentmodule.js8

Q startupjs*
^ segmentmodule.jsU i-.
-><>

var sec/daca
BS9tei
id:

),

"abe",

"001"

pnce:
r.air.e:
id:
i.

"22",
"def",

"002"

178

Inline Debugger - Breakpoints


Use the following steps to set a break point:

Open respective code module to be debugged.

Right-click on the marker bar (vertical ruler) to


the left of the Une to be debugged.

kony
2? Kony JS Debug | yi Debug | | Kony Lfj Resource
^ startup.jsS

S kony.appIcacior-.secAppli.cariorJ'Iode
1 var appCcnfig

A context men appears

appld:

"5egir.enr.3asi.cEx",

Disable Breakpoint
a. Tcggle Breakpoint

Select Toggle Breakpoint to select or unselecta breakpoint.

^ frmSegment

; var globaihctpheaders "= };

^ applicaticn.j:.

Show Quick Drff

QrkShift-Q

Show Annotation

Alternatively breakpoint can be set / unset.when


you double-click the marker bar.

1 v'

Show Line Numbers

re"

Preferences...

Breakpoint Properties...
frrr.5esrr.er.r.est.GlofcaIs O ;
frir.5r.cwDetaiIsGlobal3 () ;

1:: function rr.akeCaii (eventobject) {

136

kony.phone.dial(eventobject.text) ;

137};

Inline Debugger - Important files

kony

startup.js:
This is a platform generated file.

This file invokes appinit() method.

This file is the starting point for the application.

Invoke the global method ofeach form to initialize all the properties of a form.
This global method will be in form JS file.

Following global initializations/functions will be present In this file:


addWidgets

init

c pre-appinit

post-appinit
Global Variables Initializations

Application Men event definitions

179

Inline Debugger- Debug Perspective

kony:

For debugging, we'll be using the KonyDebug perspective

The Kony Debugperspective can be launched from Window->Open Perspective->Other


option by picking Kony JS Debug.

- t^.K*~,K&Z _
0:,

I ~> I

^,~

4 ^ n -,,.11 -i

- ,_

, .

I... .

X,

Q
*-*r~--*

[ |
i.. . *

1. Debug View

(i]

2. Variables View

*m

3. Breakpoints View
4. Emulators View

El

5. Script Editor
6,Outline View
7. Consol View

SnJ.i .i mi.

8. Expressions view

...

/ 11 -

i iuicu- wr

5A
Inline Debugger - Debug Perspective (cont.) kon-i

Debug View:
This view allows you to manage the debugging of an application.

Step Controls, Resume, Suspend, Terminate options on this view can be used to
control the execution flow of the debugger.
>Debug a T
m
7* ; . =s.
,

It displays the stack frame for the suspended

New configuration [Kony Applicaticn(Andrcid)]

" y Jf.KonyA9ef Embedding v8 ,jS2i3l

threads of the debugging target.

j? jJvsScrptThrtad (Suspended)

_,.,...

= applnit [startup.js3:19]

Breakpoints View:

= thertiecaiiBackrtartup.js3-.22]

Breakpoints View can be used to view, modify or disable the breakpoints which are

added.

Breakpoints %
U
o Breakpoints

This view can also be used to go the

'<* s?

V \ lD | t - R

yi e application.js.chromium [line: 136)


;VI 9 startup.]s3.chromium [line: 17]

respective code of the breakpoint.


Variables View:

This View is used to view the information


related to the variables associated with the

1* Variables
Valu

. *

stack frame.
4

be displayed in detailed view.

>

tObject] (d=6)

params

More information of the selected variable will

[Function] (id=16)

constructor

launchmode

1
"'

180

4<%
Inline Debugger - Debug Perspective (cont.) kong.i

Script Editor:
This Editor is used to view the required application logia

Script Editor is JS syntax aware.

Code will be debugged in this editor. Breakpoints can be added or removed using this.

Outline View.

This view displays the list of all the user-defined or platform generated functions within
a JS file which is opened and focused in Script Editor.

Double-click a function to navigate to its implementation in script editor.

Consol View:

This view will list all the logs and Information related to debugging flow.

It will also display the print statements used by a developer in the application flow.

It will also list the stack trace incase of an exception during the application flow.

Emulator View:

An emulator can be launched for debugging using this view.

Inline Debugger - Debug Perspective (cont.) kof

XA

Expressions View:

Kony Studio provides an option to evalateexpressions using this view.


These expressions gets evaluated when application is suspended.
This view is used to add/evaluate expressions that are available in JS files.

An expression can be enabled/disabled from the optionsavailable in this view.


jct'jq- ',!,-._;--.;iju'-:c- ;:-!_: i^cl-.-rr-dT- ;r;,0-:..->;
k Edit {tangate Serch groject Sun $mdow Help

"-"

t* * 0 * <, * * / *

"'

ft,1

* . * <& *

j ff-KwiyJSDebog fo Pehug"] Kon> ._Rescurce


V-Drtug ;.; -. Njngttor

;.-.

*SBl'DDj

.-: | i|) * a D ^Varbte^ Bnport

^. Nfi*_ccnfiguiilJOn [fcn,-;'p!.;;::cr -idrttdi]


VlatN

'? Rote 'konvAgenf nbtdfling V8 3S.2J.Ji


j9 iaviScnpt Thresd (Siiipended
= ipplratstjTtupjsJT]
= them*CllSictIstiitup.jssi2j

p ttjftupjs* n

Object] (idd)

C'Qi Emulators 8
.

-D|

4 . Emuldors

LBktesIolt(|i

Android

4 K f'tcbiie
*T3

.-: function pFlsi5(FKa*s) f

fm3eijiKCi:Te3!;GlobaIa (j;
f mShowecsiiaSIctali |) ;

X GiluyTib

Device;
t: Badenj

181

Inline Debugger- Debugging application

kony

The application will be suspended at a breakpoint (if configured).


If no breakpointis configured inthe generated JS scripts, the application on the
emulator/devlce will continu to run.

Breakpoints can be added/removed during the debug session


Use following options of Kony Debugger to debug each Une of an application (found on the

Debug tab): ^^__^


f V* Debug E

)t-_ Navigator Q Applications

'I ** # I

The Step Into control (F5) of the Debug View allows you to step into the next method
call/line at the currently executing line of code.

The Step Over control (F6) allows to step over the next method cali (without entering it)
at the currently executing line of code.

The Step Return control (F7) allows to return from a method which has been stepped
into.

Note: These options are also available in "Run" men.

Application can always be resumed using "Resume (F8)" control.

Inline Debugger - Kony JS Debug (iPhone)

44
kon*i

Setting up an application for debugging onan Phone simulator needs following additional
steps:

Build the application that needs to be debugged with debug option for Phone platform
on Kony IDE.

On Mac machine, goto the folder where the iPhone plugin ofKony has beeninstalled.
Open a Terminal from this folder and navigate to your plugin folder (OS-GA-5.0).

Navigate to the gen folder

Now pul the application codefrom Windows machine using extract.pl script as
follOWS:

perl extract.pl <IP: 8888>/<appID>r/s?type=iphone <anything>


open VMAppAppWithRonyLib.xcodeproj

Now build the application for simulator on Xcode and run the same by selecting
KDebug OS Device with some PhoneliPad simulator.

"

() (S) IKDebug IiPhone 4.3 Simulator !|


Run

Stop

Scheme

When launched, note the IP and Port in the simulator.

182

r
Inline Debugger - Kony JS Debug (iPhone)

kon-\ *

Switch back to IDE and Right click on Application to be debugged.

Navigateto Debug as -> Debug Configuration

Name can be

Above steps will launch the following window

anything

>
-

r
Make sure the IP and Port

in the Debug configuration


window of IDE is same as
n iPhone emulator and

then click Debug.

Inline Debugger - Kony JS Debug (iPhone) kc

V.

Debug perspective will launch as follows.


~a .,_,::

%,

- , *'&JVSl*nKnmnet*t-.1/^nt<a4

r
J

183

AA
Inline Debugger - Kony JS Debug (iPhone) k *Y"*

Makesure navigatorview is part of IDE. Follow the steps belowto add navigator.
Wxow

Help

New Editor

Open Perspective

| QAppkatjorts
Custoftwe Perspective..,
Save Pspecbve As...
Reset Perspective...

ose Perspective
Cise Al Perspectoves

O Emulators

IEnterprise Explorer
EOuline
.Project Explorer
.Services

Navigation

Inline Debugger- Kony JS Debug (iPhone)


? Debug O Nav^ator 'Z _
S ] Phone_Debog

kony

Once navigator window is

<

launched we can view the

*. .project

ES 0

Debugger Configuration added.

^ appkca&on.js
t?1 appsions.js
$* DetxjgMeglobaSseguences.js
<P ftmOne.jS
P tonytbrarv.js
i^Sampte.jS
(? st/jrtuD.is
JSSampleApp

stArtup.js

Expand the Debug Configuration


created to view the JS files

available as part of project and


set the desired breakpoints.
After setting the desired
breakpoints switch to debug tab

* Sanrte.js ti

. jcunction xys () 1

and click the resume con.

launch the application in

"Kolieata"

key3:

Clicking the resume con with

"RyderabBd"
"Pune",

key2:

for

{var k

in x)

emulator.

kcr.y.prir.t Ccev

)e -

"

Valu

*^i"

mi

-. =

Pnor*_Detxj9[Kan*Aortcanonrphone))

"5 Ororrwn . Probxd 1.0

- # JavaScro(TrTead(SusptnorcO:f<

184

Inline Debugger- Kony JS Debug (iPhone)

Execute the code through emulator.

Carrler "=

kon*i *

11:32 AM

Start Debugging

Now debugging started. Use Step Into to see the result n xCode consol and enjoy.

r
Inline Debugger - Considerations
'

4
kony

Always ensure same code s running on the debugging server as well as on the application.

Once a debugging session s terminated, remove the respective instance from Debugtab
using following option by right-clicking on terminated instance and selecting: Termnate and
Remove

A terminated debugging session can also be relaunched from the Debug tab using
following option by right-clicking on terminated instance and selecting: Relaunch
If you get one of the following errors when starting a server:
"

"Waiting for Emulator/Device to connect"


"Address already in use: JVM_Bind"

Re-launch eclipseand start the debugging server. This is required as sometimes the port is
not closed even after terminating and closingthe debugging session.

185

Inline Debugger- Exercise

kony

Objective

Be able to set breakpoints and use the inline debugger to Inspect JS code

Concepts

A breakpoint can be set n any JS file in the Navigator [Debug created application]

The vales of program variables can be Inspected in the Variables View in the Kony
Debug Perspective.
Procedure

Take the Segment exercise and try debugging it with the inline debugger

For this, you'll want to debug BOTH your own JS code and generated JS.

> Set the breakpoints in the Debug application files.

Play with examining simple data and complex collectlons (what is the segment's
selectedltem look like in the debugger?)

Try stepping Into and over code

Get comfy with this tool! It'll be VERY handy as the exercises get more complex

186

Browser Widget - Overview

kony

The browser widget is used to display HTML content within an application.


-

For example, to display the Terms & Conditions using the main .com website WITHIN an
application (instead of opening a native browser as a seprate app).

By using browser widget, the flow control still remains within the application. If native
browser is used to open a URL, then control is transferred to the native device.
The rendering capability of the browser widget is still the same as that of native device's
browser.

Each platform evokes its own rendering engine which generally is same as the default
browser of the platform.
The address bar is not visible when Browser widget is used. (In comparison, there is no

way to disable the address bar when launching the browser by using

kony.application.openURL(URL)).

v'

Browser Widget - Overview (cont.)

-i*

kony

The HTML content can directly be provided in two ways.


1

Static content
x

Browser Dolo
Gcfc on column name to sort

** &$aa

<~ URL

Content

Enter Content Here:


<htmj,>

<bodp
-

<hi>MyfVstHeadfig<)*il>
<p>My firstparagraoh,<fp>

<ybody>
<Aitml>

187

Browser Widget - Overview (cont.)


2.

-\ *

URL

r
3rowser Dota
Clickon column name to sort

C Content

URL:

i? URl

|http://finance.yahoo.corri/q

Method: jget

_]

Key

Value

goog

<*

'

iv ote
r

:- Dynamically set the static content using htmIString method. Bind the URL using
equestURLConfig method.

Copyright2012KonySolutions.lnc. CONFIDENTIAL

375

Browser Widget

kony

Browser widget can be used to crate a hybrid application wherein t acts as a main data
container of the application while menus and application title bars are displayed as native
components

Sulla 6:33 PM

Button

E-mail address*

Password*

Browser Widget-

Remember my e-mail address when ] return.


Foreot or don't have a password?

App Men

188

Browser - Events

kony1

The Browser exposes 2 events for all platforms:


onFailure:

Sample Usage:

This event is triggered when there is a probiem in loading data with the requested URL.

function browserOnFailure() {
var

str

"Unable

to

load

the

URL"

kony.ui.Alert(
{

"message"

str,

"OK",

"yesLabel"

"Error",

"alertTitle"

constants.ALERT_TYPE_ERROR,

"alertType"

"myone.png",

"alertlcon"

i.i (

"noLabel"

nuil

"alertHandler"

Copyright2012Kony Solutions, Inc. CONFIDENTIAL

377

Browser - Events

kony

onSuccess:

This event is triggered when the URL is loaded successfully.


Sample Uasage:
function browserOnSuccess() {
var str = "Successfully loaded the URL";
kony.ui.Alert(
{

"message"

: str,

: "OK",

"yesLabel"

: "Info",

"alertTitle"

: ALERT_TYPE INFO,

"alertType"

: "myone.png".

"alertlcon"

: "",

"noLabel"

"alertHandler":

}-

nuil

{});

i^^^^^^R

189

Browser - Platform Specific Properties

kony

detectTeINumber:

Specifies if the browser widget supports the detection of phone numbers in the web
page and displays the phone numbers as clickable URLs.

Ifyou do not want the Browser to detect the phone numbers, set the value to faise. By
default, the value is true.

Availability - All platforms. On BB, default value is set based on the device constraints.
enableZoom :

Specifies if Zoom (ability to change the scale of the view rea) and Pan (ability to
change the content in the view rea by moving and sliding) must be enabled.

To enable Zoom, set the value as true.

Availability-All platforms except BlackBerry.

screenLevelWidget:

Specifies if the browser widget must occupy a major portion of the device screen.

Setting Screen Level Widget as true increases the performance.

Availability - All platforms

Browser Widget Vs RichText Widget

kony

'

Though browser widget is slow to render, it has an advantage over the RichText widget in
terms of performance while rendering HTML contents.

If the input text has a lot of HTML tags, the browser widget can be used for better
performance to show the contents.

For example:
<h3>Message from ABC Corporation</h3> <pxfont color="red",
size="3"XB>***If you need to book or change flights on Swiss
Airlines, please cali ABC Corporation directly at 277-472-1891, so
that a Customer Service representative may assist you.***</B>

</fontxbr/xbr/>

If the input text does not contain full HTML tags and is limited to RichText and well
nested, the RichText widget must be used.
For example:
<b>Please note: fare rules are subjected to change </b>

190

Browser - APIs (Rich Client only)

kony

Similar to the native browser, it is possible to navigate between screens in the browser
-

widget (basically, back, forward and reload/refresh).

The following API methods can be called from JS code:


<FormName>.<browser ID>.canGoBack(): Specifies if browser can go back
into history by returning a boolean.
<FormName>.<browser ID>.canGoForward(): Specifies if browser can go
forward into history by returning a boolean.
<FormName>.<browser ID>.goBack(): to navigate one step back in the
browser history.
<FormName>.<browser ID>.goForward(): to navigate one step forward in the
browser history.

<FormName>.<browser ID>.reload(): to reload the current web page.


<FormName>.<browser ID>.clearHistory(): Clears the page history.
Where <browser ID> is the Browser widget.

For example:
frmHome.browserOne.goBack()

A*

Browser - Considerations

kony

The Browser widget has the following important considerations:

The Browser widget, unllke other widgets, is slow to load.

The Browser widget uses a lot of initial device memory. The memory usage increases
in proportion to the number of images and static text rendered.

If there are mltiple instances ofthe Browser widget in the same application, there may
be issues related to sharing of information (cookies, for example).

You cannot have mltiple Browser widgets in a screen. As a guideline, its best not to
have more than two Browser widgets in an application.

Limitation: Browserwidgetdoes not change its orientation along with orientation of the
other widgets of the form.

191

kony

Module - App Properties & App Life


Cycle Events

Configuring Project Properties

kkonyA'-

For every application, there are a lot of project level properties that determine how the app
will function.

Project properties:
Application level
Kony Server
Build

App Settings
Native App

Splash Screen (Native App, SPA)


Mobile Web

Desktop Web
Push Notlfication

192

Configuring Project Properties (cont.)

kony

Right-click the application for which you want to set properties and select properties

r
_^

1"

M . . . w : . % ^ , v m W ^

-_'-' 'J

- >

Openbcrwcc Dcfrrttion

ci*c

(A KD*fte

Mhtt

- !'"

" :-w

y cw

,/jfkua
- A,,;

>

OntX0*veiit"tL8i%Ji}etUtt'
***#>

1:::

!.-J

T'*"'"^-!

1 ^IriT

M| M||

*ii>*j

-.,..

M**

| t*

->WMnw

*>*<

**"**"

u i *nn

< Be . .

M M i :--

w*

^hWTlaVM

- A muiA. *M

-(*!.!

*****

Win

EMWMOm

"S>W [ H*M
:"ilw

"1

-,

-"

'.--.

"***-**"*

P*

<vM>*tr'>rl 1

** "cu

S.StaDcWfe

SX-^-h^r-*..

M| lili !<
un

1. -^/.'. T..IH-T,

nHIII

r ** n

c*

1/

Application Properties

kony

,-.,.,
JDJ.
Apphrntinn PioprrtH-'.

*>K.pon \o",
**."
)<ctSvDT^i Suid AppSewqi Sjsr.e * u+Svttr,fmv*w,3*) ***:web DelopWeb Vmtiiw'

App ID - default the


name of your project
I- *-- d

" w w 've-Vi* *x> CMM

rMrk-*ttve*SiGnTl

noni

Dn>^iJ*Unl

'wO**Vetf j or*-mnt

wtr>VieS

pou~min>

iwMm

xm-^iww

HotOetWd j tni-jfemt

HwrOefnM

AMf.

'-jtOe-M

OBMrv; hmOetoeC | ta>l*r*t;

l*t.Oined

twow'jywi

uxrvrvM

MU.tfihn *pp Se a (Srfrit, 0*** ti jyxs.

ttaMftmK

various app lifecycle


events

IMLVfad

NWe: tv>ien>>>< ofJetVnjiJ, fltxi* s evrec

Specify the map


widget key required
for any map use

UMtmaDo-drjrihrr: [""

<***;-i.e)9etWY: |~"

Reference action

sequences for the

rm *rt n be uwd m -je key *w * w Mgrtt sfcaion

| ^g I C**w

193

Kony Server Properties

kony

saans

->

Apjiltf ntittn l'uijiiril'i'

L_
OTU^>*T *CCWW NM'** !*^^I..AC>, t**J ***(. [**,Vtt !\*<*WiW

Point to the Kony


server to use and

on what port
Set up web
context for app
and server (uses
"AppID" and

.UTtLnrIMa>m^

"middleware" as

default)
Enter basic
authentication
credentials f

required
(Applicable to
Native

applications only)

Build Properties

kony

2=E
Ajfiptir_aliun l'njfji-d

L_i
.**. lp*#TV."pUr>-JW>.*) **** OwtMpWO "*"***"*"'

ir. lo *.ixJ tmJ**i aun wat ht wM tuteHerfen i ur^fetnr.

Mfeerj

<

Debug or Relase

<

To remove print
statements

C Piatgi ff ctcneocooi fcnijir tnelaM brwt


Me*: Becomtrijea <rt ' rsu **c U*d DN CKepeon'tn KM*-p oc 1-r.

P &^>*>ttiSffepfl

BB and Windows
Mobile options
Select "Use MDS

for BlackBerry
Mobile Native

App" to enable
the device for
wireless

connectivity

194

r
-

App Setting Properties


"".

I.T

kony
App setting allows to
enable application level
settings

,-

Applii nlurii Piii|iitii',;


E.y. ..vKaiwi i*aDn

.:..,,(... r!*. IkAl laiirikf

!ut. In. ^mwi^,~.^u&.-Aiv. WA> >4>MWrf> rwhtvW.*, utf<tof.*t

tfA^i*... |

Key:Unique identifer

"T""

Display Name: Specifies


the name to be displayed
Display Option: It can be
Switch,TextBox,Label etc.

Keyboard Type:Specifies
a keyboard type if display
option set is textbox
Default Value: Specified
the default value for each

key.

Note: Its applicable only


r.^.

Cn.

toiOS

Spiash Screen Properties

kony

a,"1 ,',"",-i
Afipln niiiin Piopurtmi

While app loads


Spiash screen

Q
: *rt)>rav= 'o.<W'jf^^tm^s,*Aop,iPA)\ ***,.o ZxseA *\ahtoCrfcMon

Colors for

}<

''eyiX'fllCM*':
">?':**

message

(foreground) and
screen (background)

Play a mp4 ,

ominanturuon(fi wconkj:|

m4v,avi,mov and

3^J
_J
_l
_l

mjpeg Video
while App loads
Images to show the
spiash screen
animation in both
Portrait and

SwtH*RkMI

Landscape Mode

Wr: CHy B**7T3ur1j Ca, rcr&yajvlCt

Spiash Screen properties are applicable onlyto NativeApp.

195

A A

Mobile Web Properties

kony
Shortcut icn

for iphone,
fav icons for

Web
Browser and
title of the
app

Check if
HTML5

outputs will
access GPS

Select Phone
Format
Indicator to

highiight the
telephone
number

Mobile Web Properties

kony

3ZC
Applicolion Proponas
L3; *:*w

srooeoe*

<tn*Jton <urr,Sa >U> Rail *tv Vltnp IUr J*v Iftmti'

*hwx?wiQ4i^-uch-<er^6lorinmerv. |
WebpnMi (t#*un-te);
1.9

nt^t^r^) ..^rvNcreWeje te*** l^tB H**JMrxS*wDea*


r'jn):

|U

_J **H.-i , >.;,:

1
'

^j tMM * (p
j "Nef MMi

1"

|l

-*n.h1M0(p.):

Base Font

"3 p^UO^M}!

1"

jW.0w0:

I--

sizes for

~3 Mtt 1fr):

|
[U

iMMnMtM
^JNth^lp.),

1"
1"

~3 B"l*"v ?&)

Select

appropriate

si

various

categories of
browsers

196

Mobile Web Properties

kony

1.T--..1

AppUcobon Prapnrtipa

'<Jto*.StltT<T.(H.w*w. !FiJ,MBtilrlW)

[**%>Wrt> ISrf.M(*fc-l=n

twHuKn

r
-^>l'*V0't'>*0

>j)nOr W eU

More button appears


when app men tems

MWKStnwDeu* S*A

JWmilr'ni..'^

are more than 5. We

J^J
Xe| Of|pw>;

|~

can specify a image for


that App men item
here

iMVt

A A

Mobile Web Properties

kony

H.T'V-l.m-1
Applirnlifin Pinpnfliii it

<c*.w. .-,smom* i* M -mw su,)..5r)C^*}[x>> av*atai.


*TwBwfiMap(ar^KWipnBjflnM.a^u;|

.w | A

HBfclw.i [TwcTw.gV

lT H ^ l M b M l M A VA

Lets you route


your request

'I

though the

_J

siteminder.

Context ID is
used to set the

context path in
the URLof an

application

0"1

197

Mobile Web Properties

kony

Applir.fiiinn Piipcrtirr.

teektm* *znfi*rv9*'4t* !>Jd *tv*tr*w wtw 5te*:totfce*i.:ji*;v5>*n-i^

..ebi>cjr :'

C*rr-M Iot'VtS l((JrVn,HTr!v rH

Lets you import an


external JS file

_l
_l

from a URL in to

-applicaion.Click on *)
to add a row

where you can


specify the URL of
the JS file

Mobile Web Properties

kony

Provide the details


of the server that

must be used for a


Mixed Mode

application

198

\A

Mobile Web Properties

kony

va.f-m.if
Alipln-.iliin I Top (!til 6
-

toekt*w &ns*t*ri*tvto OJ too'jtVtrvjt t*-eto> ,x**Son^&.e<Vo.-J,<!"e*tv,t*) 3e*:iVt> f-^NotAaaon

ttRniWT (ttMn.a):

Garv* Daea'iyti *e^j"at:-sr-j* 5

Specify a

t.tdM** i*/.- L^W M

DfBJttto-**ii*TOlm-oe 1

MH i OW

default

downloading
Jmage that is
displayed

instead of blank

page

r
!.*

Uno*

Desktop Web Properties

kony

ananana
AipfniIhih PfOpQfhn

MxAUWi Uarv.Ur.wOeUlt lUd MC^tmojt .**>

xm* ior***M7f.* *o. >'*> ***** A

wt>t>o-r Pwo.-*): |~

Base font, screen


ISopnkn

| .00 B-.^Us,- jrj

width and

"3

'eWrwmnHtjt:

alignment can be
set

.* IVSIWC U.*^T<r' a(1irl S.I<M.F>htfllJ>K[U>

Enter a message
to be displayed to
the user if browser

does not support


Java Script

199

Push Properties

kony
. jqj K

AfipliLdliunPlOpMtn

Function to
Atotuto" iun. Mr.p Uetak B. U

Wstnnn -u B.*A l*l*-'opl**rt*,'A) ****.*

* Mm*itk&ltH*M**^S

be invoked
<

"when an
Push
notificaron
is rece ived

ll

Rich Client Common Properties

kony

- -I.,-1
Applu ntmn Prurn-rlu-T.

Jcoteaten <y..-jer.r-*!*& Bul

'

Dmm ^JVsrrri

i.!M| M&*tV.*t> D*s>*t>Vn4> l\jj^f*Wc*Mi

Name and logo for


the App men on
Rich Client

togo: |
toi i7 r/wn ka *.je** <* i*nr~ In Tus" ixv' ** *" **

Note: Logo you


specify here is
renamed to icon.png
in case of Phone

200

Phone/iPad Rich Client Properties

kony
Bundle identifier is

a unique name that


identifies the

application bundle

COTVOfXitrtOtZiarOM

Bundle versin is
eiVt*ae. [-os:

the versions of

application bundle

hrM

Qrrt**n.Saw*r?. |

if

Mh

*< EvuptMnaVfert

..

:-

fu

Soban Kjntonig

UM

P*fWr IVvBoTir

tWMftM

*>* '>*"xr*6 teonM

Un

trp^tOscaoof. i'ivT,oe

-eifert.Motw

Using the Platform


Settings rea, we

Ub

laJIeJattOMM]

can set certain

C**"* TtT!S)
i*" 3_canoM;> j"O

Ata

default properties for


an application for
iPhone
?n-h

C-txW

Android Rich Client Properties

kony

m.mw.m!m
Appilcaban Propoftias

tettts^tf^e Atg^Xart-. Suwrm-.tilw-ffA)

MoMtWtfe

Enter the package

Camari f+m-fTfAndr)
VXPOrteti KreertJ

name

P tufOrrmfi
P >t\*I'jattr*
P tonn* tan

ntftiMteiw

TT*)et: (7: 3

r CJDM

I* Lerasccer*
P CaTkeUrajikree

P UM LtXajXJW PreVencc

P Vapor! Mif^jj^i*^ noel

-**c*e* fe EtrpjH SX .nwo greta* ffnoor c* (o U

r^r>r->*i<i wvw
T*e Mo>nj **rm*e<er ere rtt Id Vue'

OZM.P*jn><lJ*J9(T)jnj'

*CCL3S COAAX L0CAT50N

lC>3BJfVCJ0CMl

WRMT

'

*tiiii jAcumj.\ ixa.luwwc


*ccess *x>; loc-vncr.

te &_n*vKf_n wsw

KXSBjM :_>i**l
Af'tn i r Kcarn

urtvencAiT.Jwrcwr!

I
_J

Select the

appropriate
permissions
required for your
application

OA-iUcr IAT3

MIjtfMnDGgl
e?cjt.:cr_Ai>ci
too p*v* M9M30

201

BlackBerry Rich Client Properties

kon ^*

Ajii!ir nlilin Priipr-ftiitS,

Ccneacr Hvei V^^"****""' Vv"*ml">** /erdte..* tler**


Oeepw. ir wwr*
^
<s

Service Identifier

Pattern specifies a
regular expression with
which application will
be launched through
message or e-mail

SrnevttkMknlStlcM* J-.Ti^tjijv
i*rx M*ru leo uexl: | aootceuntet!

When the service

identifier pattern is
recognized , a popup
appears showing the
application to be

launched with the text

provided in Service
Men Item Label

|__f> iiJi_~<ij

Copyright2012KonySo!utions.lnc. CONFIDENTIAL

403

Windows Phone Rich Client Properties

kony

b:
A|i|ilti:nlinn Pl,i|,i'llii.

*tvjiif>iatA>.j.A) WM-mt, :

3 *uttrnt\j*r'

We can set

Windows Views

using the Common


Subtab

Pivot View places


individual views

horizontally next to
each other and

manages left and


right navigation
Panorama View

uses a long
horizontal canvas

that extends beyond


the screen width

202

I
r

Windows Phone Rich Client Properties (cont.)ko


ee
Application Propumea

*" a*,t~~!X<* U< W^W$^) W.a^.hWI.! iMH M*M **l.H.i


Ci i Im.j*I *n*I bU^*""". TJ^> RaiOnt
r^t) NfC7.j

Genrate GuID for

.vm>-ii4e-Uj2J

Windows Phone

7.GuID enables to

view the application


on Windows 7
emulator

Tile Image is used

__

as application icn

r
r
-

Windows Phone Rich Client Properties (cont.)k *\*


Applpcotion l Tpeme*

L3
Jkr*V.tlwn Knry Vt-vt-t I>'j fiulrt fti cntinpiS

fan-on ftinpv/Tad^*mgiri HAriBVstS-^^TTt-i fY,^* t

rfa-h >!**(twij.r op. S1*) '

Mango (7.5)

Tile Title specifies

1 rhrflor*

frieiwo Psvnr- 7Q-fcwnyy;J ij)

the Title headers for

Ke-neie:

the application

Se*.lMwJeleFw)e.

Select 3D Models

*e m tatu'
tn f*.,>

tVK*,r*i>nri>.

ro.CAP.carACTS
ID LaV MMJtyjVttlj

m_rj^_mR,Trrv_riJF4iCi'

Folder specifies the

!
_J

folder where fbx files

are stored and Play


button converts fbx
file format to format

that can be used by


Windows

UJ.UW JEDIT1 T'rjMH


HJ_CAPj.OCATTON

ID r..V WDWUi

m_ra."_mirn (ivi #
HJ_C*i'_H. I

-...,

Set the appropriate


permissions to true
that are required for
the application

r
-

203

> **

Application Life Cycle Events - Overview

kony o

Application life cycle events are used to achieve a functionality for an application during the
initialization process.

Following are the sequence of steps nvolved while an application is launched:


Steps/Events

Description

Customize Code
pJJijijij^rJJr,JijijHr,j^rJJ^r,jij^rJ^rJ^_

Spiash screen

Spiash screen is displayed (if configured) on start of


application.

No

pre-appinit

Application Event is triggered (if configured).

Yes

appinit

Application is initialized.

No

post-appinit

Application Event is triggered (if configured).

Yes

addWidgets

Startup Form's event is triggered

No

Init

Startup Form's event is triggered (f configured)

Yes

preshow

Startup Form's event is triggered (if configured).

Yes

Startup Form

Spiash screen is dismissed and startup form is displayed.

No

postshow

Startup Form's event is triggered (if configured)

Yes

a*

Application Life Cycle Events - Overview

kony

The IDE exposes following two events for application initialization:

pre-appinit: This event is invoked before the application is initialized


For example: Invoking a service cali to retrieve and load localization bundle from a
server.

post-appnt: This event is executed after the application is initialized


For example: Forc an update of an application from market

Note: Events for pre-appinit and post-appinit can be configured separately for Tablets
and Desktop Web.

Initialization of the application involves the following initializations:

Creation of all the defined skins

Initialization of defined Global Variables and Data store keys defined in the services
tab.

204

Application Life Cycle Events - pre-appinit

kon*<

Using global variables, data store keys, skins in pre-appinit event handier will result in
"nuil" as they are not yet initialized at this point.

Example: Creating a dynamic app men:

pre-appinit event can be used to crate a dynamic application men using


kony. application . setAppMenu method.

Different application menu's can be created dynamically for different platforms


depending upon requirement.

Following code snippet can be used to crate dynamic application men:


var appMenuIteml =

["appMenuItemldl","Accounts",

"iconl.png",onClickClosurel];
var appMenuItem2 = ["appMenuItemId2",

"Payments",

"icon2.png", onClickClosure2];
var appMenu =

[appMenuIteml,

appMenuItem2];

kony.application.setAppMenu(appMenu, "sknl", "fcsknl");

Note: setAppMenu method should be called only once and must be set in this event

Application Life Cycle Events - pre-appinit

AA

k -i *

Setting callbacks for Background and foreground events:

pre-appinit can be used to specify the events that need to be executed when the

application goes Into background using the setApplicationCalIbacks method.

1 Syntax: kony. application. setApplicationCalIbacks (callBacksTbl)


where callBacksTbl is an objectof keyvalue pairs for various application events:
Following are the keys that can be used in setApplicationCalIbacks

onactive-. This sspecific to iPhone. This state occurs when there is an incoming
SMS, phone cali, or anything else that interrupts the automatic lockof the mobile
device.

oninactive-. This is specific to Phone. This state occurs when the application has
been idle for a specific time interval.

onbackground:. Statewhich indicates thatthe application Is active and running


in the background.

onforeground:: State which indicates that the application is active and running in
the foreground.

onappterminate::-. State which indicates that the application is terminated and


not running.

205

Application Life Cycle Events - pre-appinit

kony

onkeyboardchange-. Its specific to Mango.This state indicates whether a


keyboard is deployed for an application.
onpowersourcechange-. Its specific to Mango.This state indicates whether a
power source is attached to a device or not.

onnetworkchange-. Its specific to Mango.This state occurs whenever there is a


change in the following:

Status: Indicates the status of the device. The different statuses are

Connected, Disconnected, Roaming or Unkown.

Network: Indicates the network available on the device. The network

statuses are Wireless80211, Ethernet, MobileBroadbandGSM,


MoblleBroadbandCDMA, or None.

Date: Indicates the date on which the event occurs

Note: Available on all platforms except SPA.Mobile Web, and Symbian

^''"^*"

<'

Application Life Cycle Events - post-appinit kon*

post-appinit is generally used to initialize the application components.

This event will be triggered before displaying the startup form

All the global variables, data store keys, skins are accessible in the post-appinit event as
they are already initialized.

Following are some of the scenahos for which this event can be used:

Forc an update ofthe application from Market place by displaying a confirmation Alert
on versin check.

One time application nitializations

To displaychallenge questions or to retrieve survey information at the start of the


application on certain conditions.

To invoke service calis to retrieve data to be displayed on the startup screen

Display an interstitial screen

206

Application Life Cycle Events - post-appinit kon*

Example: Changing the startup form dynamically

post-appinit event can be used to dynamically change the startup form

If the post-appinit function returns a Form, then that form will be used as startup

The following function is an example of dynamically changing the startup form:


function setDynamicForm()
{

var userPref = kony.store.getltemf"userPreferenceStartForm")


if(userPref == "payments")

return frmPayments;
}
else

return frmServices;
}

Service calis can also be invoked in post-appinit event

For example: Retrieving lcale bundles from the server using a service cali

Application Life Cycle Events - Considerations kof/i%

A new form, popup or an Alertcannot be displayed in pre-appinit

In post-appinit, a Popup or Alert can be displayedto forc an application update from


Market by doing a versin check through a service cali.

Anew Form can also be displayed In post-appinit to display an interstitial screen while
making a service cali. The sequence of events is:

Design an interstitial screen to be displayed

In the post-appinit invoke a service cali asynchronously

Display the interstitial screen

Poplate the required data retheved from service cali to startupform


Once the post-appinit execution is finished, the startupform is displayed

Destroy the interstitial screen

207

"

Assignment-Application Life Cycle Events

..

kony

Objective

Be able to dynamically determine the startup screen based on a configuration value


read from persistent memory.
Concepts

The IDE exposes two events for application initialization: pre-appinit and post-appinit

Ifthe post-appinitfunction returns a Form, then that Form will be used as startup

Procedure

'

Crate a 3 screen app with forms: "home", "screenl" and "screen2"


On the "home" screen, have 2 buttons that are labeled "start on screen 1" and "start on
screen 2".

Clicking either button will save, to the device, the name of the corresponding form

Upon application startup, read the value and do the following:


If the value Is nuil (i.e. the first pass), start with the home screen
If the value is "screenl" show screen 1 on startup

If the value is "screen 2" show screen 2 on startup

Assignment-Application Life Cycle Events (c^tw'->

Use the Local Storage APIs


save and retrieve startup
form information

li yULB 6:PM

For both screenl and


Sun on screen Two

screen2, have buttons going

Exit

back to the home screen so

you can click the other button


to test

You'll have to "kill"the app to


restart to test your code.

Use either the device app


management to kill your app

&|J)6:41PM

V 'fifflilJJ 6:PM

OR use the

kony.applica tion.exit()
javascript function to exit the
app

208

r
A'

Application Data Flow

kony

Remember, the Konyserver will retrieve the data from the "backend" source and pass it on
to the client.

r
r
Mobile Device

Kony Middleware

We'll need to define these integration points that we cali Services.

r
209

Data Connectors

kony

There are 7 ways to connect to data:

Using XML services:

communlcates with an external data source using an XML data connector over the
HTTP protocol.

Using SOAP services:

communicates with the external data source using SOAP interface. WSDL URL/file
is required to configure these services.

Using SAP Services:

communicates with an external SAP Server using Custom SAP Connector over the
HTTP protocol and returns a response in JSON format.

Using Siebel services:

communicates with an external Siebel Server using Siebel Connector to use


Business Object and Business Services hosted on a Siebel Server over the HTTP
protocol and returns a response In JSON format.

XA

Data Connectors (cont.)

kony

Using Mainframe services:


communicates with the external data source using mainframe connector to

connect the WebSphere MQ Server/Windows Server over the HTTP protocol and
returns a response in JSON format.

Using JSON Services:

communicates with an external data source using JSON data connector over the
HTTP protocol and returns a response in JSON format.

Using Java services:


Uses a custom Java connector which is a custom Java class that implements the

com. konylabs .middleware. common. JavaService interface.


Used when the external data source has not exposed any services.
The Kony scraper is an example of a Java service.

210

XA

Service

kony

Service - an application component that represents the application's Interaction with the

external data source.

The IDE provides out-of-box support for connecting to XML, JSON and SOAP services.
In case the external data source does not expose the services through these Interfaces, the
developer can build a custom Java service.

Every service must have a unique identification in the form of service ID.
r

The service ID is what we'll use in code to cali a service.

Once individual services are defined, you can combine the services to crate a Composite
service.

This is helpful when data is made available through more than one type of service.

Can be configured to run in parallel or in sequence.

Service Definition File

kony

Once the services are identified and created, they are bound together in the Service
Definition file.

The Service Definition file contains your service configurations for exchanging data with the
external data source.

Service Definition files are copied to the server so the Kony server can follow the definition
and exchange data with that external data source. Copying the file is called publishing the
services.

The Service definition file must be published to the server for your application to work.

Every time you add/remove/change anything for any service, you must republish the
service definition to the Kony server - the IDE does NOT provide a way to run services from
the app.

Note: Generally, services point to external sites and you must ensure that access to the
external site is enabled in your development machine. Similarly once the services are
placed on the server, you must ensure that access to the external sites is enabled
from the server.

vmmmmrm
-

'

211

XML Web Service

We'll start with XML services:

The basic steps we'll follow are:

kony

Identify the web service - we'll use a Fox News public RSS feed for our examples

Connect to the service and test

Configure inputs and outputs

Valdate our results

Publish our service

Test services from within an application

Here's the website we'll use as an example: http://feeds.foxnews.com/foxnews/world

XA

Configuring XML Services

kony

Right click the application and in the "Open Service Definition" context men, select XML
" ' .'.<l..l.'lJ.'.TTP5?Wgflff>ffl!Tl
services and give It a name.
Edit

Navigate

Fe

Edit Navigate

Search

Project

Run

Window Help

f^lfrmTest

Search Services i |
y-' 9 R5Tful Services (1)

B f3 fbrms HNew /J^pircatior.

S ^ other (1)
^

Ctrl^c

Java Services

Delete

Selected Services (0)

B. Librories 0}

JSON Services

F2

. _ * * . Refresh

Kony

X toa

l^SafnpleApp > ^fonns > % rttobte ^frmTcst.ld

Copy

Run

s$ SarnpieApp;XML 5ervice

E3 frmTest Uj

XDelete

Project

ff Kony JS Debug $ Debug

1 X iQa- |
[*j GP Kony JS Debug ? Debug j : : Kony [j^jRowurce
QAppkc... Zl '-- Navig... ^

Search

] JC^jvh

Kony - SaniplL'App/tornps/mohile/frmTesLkl - KonyOne Studio

Cornposi te Services

Locping Services

FS

B J popue t rtefnish Wotepace

SAP Services

Siebe, Services

8 i. modd ***

"

f\ ./nb ,
- -

Change Development Language to la'


Publish

Manframe Services

Define Service Tmplate

Then the XML service editor will be opened.

212

XML Web Service - Optional Fields

kony

User ID / Password: Provide this information if the external web service requires form/basic
authentication.

URLprovider. Enter the URL Provider file name. URL Provider is a Java class that
manipulates the URL or the parameters of the URL for the external data source.
Timeout (in ms): Specifies the mximum time (in milli seconds) the service waits for a
response, before terminating the connection to the external data source.
Services

** X ti

SearchServices : |
e i3 RESTfulServices (1}

B $ other (I)
t> SelectedServices(0)
a. branes (0)

* DefineService
Service ID":

| be;tbu.search

URL*:

Jhttp://api. remix.bestbuy.c

ittpHefl

|get

-.v.. prc3'j:tr:>

Preprocessor Class:

Browse...

URL Provider Class:

Browse...

Data Provider Class:

Browse..,

Postprocessor Class:

Browse...

rtmeout (inms):

DCachabie

Cache Durarjon (see): |

& Sax C imM

User ID: |
NTLMHost: |~~

Password:

IfnJMDomari: |

XML Web Service - Pre/Post Processor

kony

Preprocessor: Acustom Java class deployed on the Kony server that is called before the

service cali Is made. The preprocessor can affect the inputs to the web service. Identify
the .jar name in this property.

Postprocessor: Acustom Java class deployed on the Kony server that s called after the
service cali is made. The postprocessor can affectthe outputs from the web service.
Identify the .jar name in this property.
Service.

* K a

Search Services: |

Define Service
Service ID":

| bestbuysearch

Http Method:

|gT

|hr^;//ap.rerri,x,bestiwv.cDm/vl/prrj^^

RETful Services (1)

8 ^ other (l)
fit bestbuysearch
L_. Selected Services (0)

. liraries (i)

^Preprocessor Class:

jcom.kony.preprocessor.SamplePreProcessor

URL Provider Class:

Browse.,.

Data Provider Class:

postprocessorClass:.

Browse...

Browse...

Icom.konv.postprocessor.SamplePostProcessor

Browse...

Timeout (n ms):

Cachele

Cache Durasen (see): |

Server Au then bea Don

P Baste C MTLM

User ID:

MlMHost: |~~

Password;

HTLH Dornain: |

213

XML Web Service - Caching

kony

Cachable: indicates whether the server response will be stored at the Konyserver cache or
not:

You can optionally pass the Cache Duration value (in seconds) which tells the
middleware to hold the results In the cache for the given duration.

If this service is Cachable and a service cali, for the same data, s made before the
specified time duration, the service response is fetched from the Cache.

If the time has expired, a fresh service cali is made.


Preprocessor Class:

| com.kony.preprocessor.SamplePreProcessor

Browse....

URL Provider Class:

Browse...

Data Provider Class:

Browse...

Postprocessor Class:

| com.kony.postprocessor.SamplePostProcessor 1Browse...

Timeout(mms}:
Cache Durstion (see):
Stive AuUienualiuii

? Basic C NTLM
User ID:

Password:

NTlMHost: f"

MTLMDomain: |

Response encodtng

xa

XML Web Service - Http Proxy

kony

Hffp Proxy: Configuring the proxysettings enables you to connect to the external services
from local machine through a proxy server. Enter the connection information here.

If passwords are used (the service password and/orthe password forthe proxy and/orthe
password for service basic authentication), then they will be encrypted in the service
definition file if the Encrypt passwords while generating servicedefinition file checkbox is
checked.

Timeout (in ms):

Cachable

Cache Duration (see):

Serve AuUienliLdlJuii

C Basic P NTIM
User ID:

Password:

MTLMHost: ||

MTLMDomain: |

214

Creating a Service

kony

Give service a name (Service ID), specify URL and provide HTTP method of service.
Click Get Response to test and view the results.
w

ja;.

i_-'- RESTfiJ Serv.ces (1)

Define Service

-v other (I)

| http://api.remi .bestbuy.com/v 1/products(sel*

GET

Http Method:

0 bestbuysearch
fil Setected Services (0)
LS m-. Libranes (l)

End point URL

]bestbuysearch

Service ID":

SearchServices : \

zi
1Browse... 1

Preprocessor Ctass:
URL Provider Class:

1 Browse... 1

Data Provider Class:

|b,..|

Postprocessor Class:

Browse... I

Timeout (ims):

CacheDuration(see): |

-
(* Basic (~ rTUM
User ID:

Password:

NTLMHost: |

(TLM Doriiain: J

Response encodmg:

j UTF--

"3

0 Ena yptpasswords wMsgeneratingservicedefinition Re


l~l Escape emfaedded xmlm response
-

** Request/ Response

Reauest Response

__

Our Response

<?xrril^tYtesri*etlVef-7vl/xd/Mri_prettY

iy Solutions, Inc. CONFIDENTIAL

XML Web Service - Input Parameters

kony

Most service calis have some sort of input parameters.

In our example, http://feeds.foxnews.com/foxnews/world, "world" is the type of news we


want to receive.

r
r

FoxNews has many other feeds such as: latest, scitech, entertainment, health, etc.

In the URL, "$" specifies an input parameter variable definition.

In our example, http://feeds.foxnews.com/foxnews/$newstype would indcate that

"$newstype" is a variable input parameter.

We'll now need to crate the definition for that input parameter
* Define 5ervce

Service ID":

Hito Headers 'Input Parameters

Output Parameters Results

foxnews

|http://feds.nj3meM.corj.;foKne:vs/sne.vst>Tje
Http Method:

'--

215

XML Web Service - Input Parameters

kony

The following attributes are defined for Input parameters:

ID: a unique identifier for a parameter - this is what we'll use to reference this
parameter in our code.

Tesf Value: the value to be used to test the service within the Service Definition Tool.

This value is not the part of the final Service Definition file.

Scope: this identifies the source for the value of this parameter at runtime. You can
choose either:

request- you need to pass the value from code.

session - t will be passed by the server (note: we'll talk about how to get that data
on the server soon).

Datatype: the type of the data. The datatypes are defined here and are used for
mapping appropriately in the Mapping editor.
Encode: set to true or faise. Specifies if the URL needs to be encoded for this
parameter or not.

Description: Provide some text to describe the input parameter.

XML Web Service - Example

kony

We'll set up our input parameter:


i'HttpHeader5 'InputParameters

Output Parameters Resute

Add
Test Valu

wstype

worid

1Scope
1

Datatype
string

Encode | D scnptton
1

And then valdate our results:

.and the right results come back


Consol shows outgoing cali.

Request Response

<?xml-stvtesheet tvpe-'texfxsl' media-'screen' riref-7^/5tyies/rss2ru!

Sconle

yProjress

<?irrn!-stylesheet type'text/css* media-'screen' href-Tittp:/'/feeds.fbxn

ony5tudoConso!*

M-29-20U 05lO6i4BH!rl is : ":-.cCF://sed!.f:-xri-v.coir7Ioxr.ew5/world"


05-29-2012 O5:06:45]0":i provided by UBLStVtltet -s "cttF://eed3.rorews.cctt/cxr,evs/vcrld"

<rss KmhsCOntent-Tittp://Durl.OTg/rss/1.0.(modules/conteritf xmins:dc'

03-29-2012 D5;WH8]Uslagi OTF-5 to encode trie request.

c^jiV:>http //www .foxnews.Com/world<:/1mk>C^

<channeT>

05-25-20:2 05:06:S]C&ar3et Encodiag fren respcr.se: OTM. usina, eiicadir.g: OTF-S

<desfliliJUi.^l L^LujHai.urt.-^.bkcHxj.'rYouDeade.</destriptx)

05-25-2012 OStO&UlBndag the respcr.se stress.


OS-29-2012 05:06:49)Total Tinte: 1075

<copynght>CopvTioht 2012FOX NewsNer-.vork</copyrtght>

98-29-2012 05:06:49]

<language>en-us </language >


<OubOete>Wed. 29Aug 2012 11:32:24 GMT</pybDate >
<dc:date>2012-O8-29Tll:32:24Z</dc:rJate>
<dc:language>en^3</cfc:lanciuage>

<dc:nghtsCopyright 2012FOX NewsNetwork</dc:figrits>

216

r
XML Web Service - Output Parameters

kony

Output parameters allow us to Identify which pieces of the returned dataset we want to
return to the calling device.

You can configure as many or few output parameters as you need.

"

ONLY send the data that you need. Trimming the dataset saves bandwidth (sending over
the cell network) and processing time (device retrieving the dataset).

Output parameters can be collectlons or single vales.

In our example, we'll return a serles of news articles. We don't want all the data so we'l
configure output parameters for:

Our collection of articles

The news article's title

The news article's details

> The new article's publish date

XML Web Service - Output Parameters

kony

The following are the attributes defined for Output parameters:

ID: The unique name that we use in our code to access this value.

Xpath: the Xpath expression for extracting the required data from the service results.

Scope : this identifies the source for the value of this parameter at runtime. You can
choose either:

response - to have the server send the data back to the calling device.
" session - to have the value stored in session on the Kony Server (can be used
now as an Input parameter for another cali).

Datatype: the type of the data: string, Boolean, number

Record ID: Groups data elements under the specified parameter as a record.

Collection ID: Groups data elements under the specified parameter as a collection.

Format Can be set to none, currency, number or date.

Format Value: Standard for converting to the specified format: Number, Currency,
Date.

Description: Provide some text to describe the output parameter.

217

Format and Format Value

kony

By using the Formatcolumn of the Output Parameters tab, the format of the Output fields
can be set to: None, Currency, Number or Date.

Format Value column can be used to provide the conversin standard for the selected
format.

Example:

Suppose the response has date fields which must be converted to a different Date
format in the results. You can choose the Formatas Dafe and define a TargetFormat in
Format Value.

Request Response
<copynght>Copyrght 2012FOX News Network</c.opyright>

^'"Prlf""'"' M"'" BtttUiaiair^iubDate>


fcdate>2012-08-29T 11:32:24Z</rfc:ajteT;

<JH 1J0UB JSluik/da, igUaLjt^-

HttpHeaders IInputParameters iOutputParameters

XJ
SrcFormal:

Results]

Target Format: | ilM-dd-yvyy

To vw the result of output, cbck on "Results' tab or Test' fink.


Add

The ID fieid is mandatory

Test

I Scope

I XPath

|Wvv-MM-dd

| Datatype

//channel

strrng

item/tjoe

JFinshj Cancel |

| CoUectionID | Reco... | Format j FormatV,i


None

strmg

channel

tem/link

string

channel

I-tone

item/descnpbon

strmg

channel

None

item/pubDate

strmg

channel

XML Web Service - Example

kony

In the output parameters section, identify those data elements you want to expose for the
application.
We'll use the title, publish date and description of each article.
Set up output parameters by writing the X-path (to fetch the vales) for each of these as
follows:
HttpHeaders InputParameters^ OutputParameters

Results]

To view the result of output, dick on 'Results' tab or Test' link.


Add
D

The ID fiet ts mandatory


XPath

Scope

IfsL
1 Datatype

! Collection ID

string

Reco..

| Format | Format Vafue

item/iink

string

/channel \
/ channel \

None

link

dase

tem/descrtpbon

string

charmel

None

date

item/pubOate

string

\ channel /

None

dtate

item/dc:date

string

Ndxarir^/

Date

rjtte

item/rjrJe

None

None

MM-dd-yyyy

X_^

The News parameter is the basis for our collection of news articles.
Note: In this case, in our code, we will access the collection of results using "News" and
specific tems by "channel.title", for example. We'll see how this works in a bit...

218

"

XML Web Service - Example (cont.)

kony

To examine the results:

Click the Results tab.

Http Headers Input Parameters Output Parameters Results

ccollection id=*channe|3>
rrfc?

-~

-><titie>Russian pliceidentify female suicidebomber who killed Muslim leader in Dagestan</titie>


<lmk>http: /'/feeds. foxnevvs. com/M-/foxnews/world/-3/030R6r[R70U/</link>

><desc>SJt;pSgt;Russian plice say they have identified the female suicide bomber whokilled an influential Muslim leader in
<date>Wed, 29 Aug 2012 10:44:12 GMT</date>
-><dcdate>0S-29-2012</dcdate>
</record >

<record>

<tite>Part of Amsterdamairport evacuated after suspected WorldWar II bomb discovered</tirJe>


<link>http://feed5.foOTievvs.com/M7'fox^^

<desc>Sit;pSgt;Amsterdam s Schiphol Airport has been evacuated after workersunearthed a suspected World War II bom
<date>Wed, 29 Aug 2012 03:17:07 GMT</date>
<dcdate>03-29-2012</dcdate >
</record >
<record >

<titie>Navy SEAL'sbook raises questions about bm Laden's death, report says</titie>


<link>http://feeds.foxnew,s.com/M'/fxnews/world/^3/02301AVRsM/</1ink>
<desc>SJt;p&gt;Firsthand account of the Navy SEAL raid that killedUsama bin Laden reportedy contradicts previous accou
<date>Wed, 29 Aug 2012 06:53:22 GMT</date>
<dcdate>08-29-2012</dcdate>
</record>
<record>

<title>Once-detained Australian journaltst can now leave Egypt</titie>


<link>http://feeds.fbxnev.com/M-/foxnews/world/^3/OB3J8NFsyqc/<j1ink>

r
-

Formatting the Response and Results

kony

Both the response and the results can be formatted using the Format option.
- Response window (right-click to get the Format option)
Request Response

screen" href-7~d/styies/rss2fjj

<'xml-stylesheet type*
e'xml-styfesheet type=

screen' hre f=Tittp://feeds. fo>

<rss xmln5:content*Tit
<channel >

.O/moduies/content/" xmlnsdc1

<titie>FOXNews.cor

<link>httjr^/vww,fi.
<desCTipon3^px N

undo

c/Wt>
Report. You Deade. </desaipt

<language>en

<copynght>Copyn$|
<pubDate>Wed, 29lS

Network</copynght>
!4Gm</pubDate>

Results window (right-click to get the Format option)


HttpHeaders jnput Parameters OutputParameters ResJts
:testdota>
< collection d="channel'>
<record>

<tjrJe>Rus5ian pliceidentify femalesui


<link>http://feeds.foxnevvs.com/M-/fb>

<desc>Sdt;p&gt,Ru5$an pobce say the)


<date>Wed, 29 Aug2012 10:44:12GP

ilied HuritnleadermDagestan</b
30R6rR7OU/</Wt>

e female suiade bomber who kilec

<dcdate>03-29-2012</("
-

</record>
<record>

<tite>Partof Amsterdam airporte


<link>http://feeds.fo)news.com/'-r/f
<desc>SJt;pSa3t;Amsterdam"s Schiphoi/.
<date>Wed, 29 Aug2Q1203:17:07GMT</date>
<dcdate>03-29-2012</dcdate>

ed World War n bomb discovered

[rmz_ryXr0/</iJnk>
<acuated after workers unearthed

</reccrd>

r
219

Publishing Services

kony

Before we can test our services in our app, we now need to publish our services definition
to our Kony server.

There are 2 steps to this:

Genrate the services definition - this "packages" the services to be sent to the Kony
server.

Publishing the service - this puts it on the Kony server so your applicationcan cali it.

You'll need to do this every time you change anything about any service.
All services for the application are bundled for publishing.

Let usgo through this...

Publishing Services

kony

Inour training setup, we have a local copy ofthe Kony server available.
We'll be publishing to that server so we can have everything running locally.
To start up the Kony server do the following:

Start memcached first but running the memcachedi .bat file located at:
C: \KonyOne\KonyOne-Server \memcached

This will open a blank command window - minimize it (closing itstops it running).
Start Tomcat (Kony server) by running the startup.bat file located at:
C: \KonyOne\KonyOne-Server\tomcat-6 . 0 . 29\instancel\bin

This will open up a command window that will be your system consol type screen
for the server.

Toshut down tomcat, just cise this window (no need to run the shutdown.bat file).
To restart, just run the startup.bat file again.

220

Generating the Services Definition

kony

To genrate the services definition:

Make sure all your definitions are saved and working properly.

Make sure your definition has the focus and is open.


He Edit

Help

| |<k-J** J4I J
>Debug I " Kony
t

C-Newg... '

Dlickthis button
O
;

v:eb_modute(0)

,,_. Resource

P** ^
d

* resources (2)

3-i. services (0)

- SftJimIJO;

Service*

'i' ( RESTful Services (2)

a %other (2)
9

[ foxnews

UR1 :

| http://feeds.fb)oiews.crjm/fbxnev'/Sn

Http Method:

GET

-:

Preprocessor Class:

i_r SelectedSerI

*l

5 B. Libranes JI)

S H ebel (0)
+

Service ID":

bestbuysearch

fifr foxnews

ittj servicedef
[> (107 sap (0)

* Define Service

SearchServices: ]

+ . * 1)

'^ v\*bservice-soan (0)

ttL
* X a t

mainframe (0)

XML Service Defirttionfie is generated successfiJy

$ * java (0)

5 Sisn{0)
** SCTaper(0)
v* comoosite (0j

Jt>

Publishing the Service Definition

kony

Publishing the service definition moves the service HE3EL3Z33


to the Konyserver where it can be used by the
Application Properties
application - the JETTY server in the IDE will NOT

Jfll

Edit appkftton properties

work for service calis.

Apptcabon Kony Server DetatV Bud App Settings "s

Configure the application properties to identify the


Kony Server details (use the IPof your training

Server Name / IPAddress: | Domainr!ame/IP


HTTP Port:

l SOSO

machine on port 8080 for HTTP).

Right-click the project to bring up the main app


men and go to Publish -> Services

Note: You'll need admin credentials ("adftin" with


a password of "admin_1234"

Every time you make a change to a service, y


have to:
-

rebuild the service

(fjNeivApptatan
Open ServiceDefinirn
Copy

X Delete

Delete

Rename

F2

Refresh

F5

| RefreshWorkspace

>BuW
Change Development Language to la'

crate the service definition file

re-publish!

cune

Appkabon

Properties

221

Exercise - XML Web Service

kony

Objectives

Be able to crate and test an XML Service Definition.

Be able to specify Xpath output parameters in the Service Definition to get exactly the
data you want from the XML service.

Be able to successfully publish a Service Definition to a Kony server.

Concepts

A Kony app can access external XML services through a Service Definition that resides
on the Kony Server.

A Service Definition file is built and tested using the IDE.

Output parameters allow us to identify which pieces of the returned dataset we want to
return to the calling device.

Before we can test the services in our app, we must publish our services definition to
our Kony server.

Procedure

Crate a new XML service definition.

Add your FoxNews service.

Hardcode the URL (using "world" or one of the other vales).

Exercise - XML Web Service (cont.)

kony

Get Response and valdate you see the results.

Nowcrate an input parameter and insert your "variable" in the URL and provide a test
value.

Get response and valdate you see the results.

Now, let's add your output parameters for:


Copyright
Language

- . :':

-*

:t-"''e

Ji'i^'n.Ve''-

.; -rauda iciw"'**ft '> ltttlmmm\nt-l lirflwftwiimal


ruir^niflK. Ml. -l'millHUl''''*<

fr****^** >'y*

Collection of news articles where each


article has:

Title

Description

Publish date

Check the Results tab to check your work (note: you only need to Get Response once

to get the data, now all your work figuring out your output parameters can be tested by
just checkingthe Results tab - that will always work on the latest result set).

222

Exercise - XML Web Service (cont.)

kony

Ok, so let's continu to play along...


-

Start up your server (memcached first and then tomcat).

Configure your server details in your application properties.

Genrate your service definition file.

Publish your services. (CredentialS login: admin & password: admin_1234 )


Browse to the server's admin page: http://<!P Address>:8080/admin
login using the same credentialS used to publish.

Find your application ID, look under services and you should see ypur service
definition.

Click the input and output tabs to see your configuration.


K"i>v
-

Wnte Once. Run 5vcrvwhe.e. AllCtionnels.

Kony

Management

Con

Acolicat.ons

.."- SBmcleApp
...

Application: 5n.el.app

>

Service

>lo

Services

g] bestbursea.

"

223

Network - Synchronous Vs Asynchronous

kony

Synchronous services:

are invoked over the existing web protocols (http or https) when you have to wait for a
response to proceed further with the execution of the application.

blocks the user-interface and does not allow you to perform any other action while you
wait for a response.

are used when you do NOT have any long running tasks.

Asynchronous services:

are invoked over the existing web protocols (http or https) when you don't have to wait
for a response to proceed further with the application execution.

expects a response at a later point of time during application execution and can be
handled by defining a cali back.

does not block the user-interface there by allows you to perform other actions while
you wait for a response.

are used when you have any long running tasks.

Network API - Overview

kony

The network APIs below are used for making synchronous/asynchronous calis from Kony
application to the Kony Middleware.

Invoking a Synchronous Service.


*

appmiddlewareinvoker

appmiddlewaresecureinvoker

Invoking an Asynchronous Service.

appmiddlewareinvokerasync

appmiddlewaresecureinvokerasync or kony-net.invokeServiceAsync

Cancel Asynchronous Service.

kony.net.cancel

Note: All the above appmiddleware APIS are built OVer a net. invokeservice API.

These helper methods do some work "under the covers" such as sending some
additional parameters like metrics, channel, appid etc. to each service cali.

224

r
Network API - Overview

kony

You can see the definition of these "helper" methods in the application.js file that can be
found in the <workspace>/<app ID>/jssrc/<device>/generated folder.
Note: application.js file will be the same for all devices.
mJ2
" ^ *i |b.1c)C(1-ib. :..._: ^.I.i.-.

II

lili

'
-r.ccc: '

lili I I

..:

|] .

., t.MMPI 1

epp_:.--i:.?er"e::r - !"
ipp "enf i g . sel wt!|i i

epcircr.r ce urreca.t "/"

I tcPCi.efla.*llMleieC-.c,t-.

ecc

cc-levicercrcexc

WSacfTl

B/WcPPfVl1

inc_*.larPK.PFp:[i twTftnfu.tOTIti
crccccFpcPB.pricTer -

p^cCccclg.PCpVerp,

cr.p'j:rri;:*;r.c.r.e_" :

":;".

cr.j _crecen'*f'.e. t

-r;.-",

.rtj,e.ie;-i :

r.-j

11

"

^.."K":

ir.pc-.tacn3,:-c.-.3iCtcr-!

UaUMta

nlaaVHtectUplunrlir
ir

<.GC_cFexu*:*r.ccpr.ec;ecn":

cr.p.cacecr.r.ccpr.eeciera cecoeReacii-cs icr.pccfpcncc.r.cccr.eecieu. cicfcair.ccpr.eeclec!


rti.l[1ilci-.

,:

i .:-..-,

pccrececc.

csSlcc

r
r

Network - Synchronous Services

kony

appmiddlewareinvoker is used to invoke a synchronous call over the non-secure network


appmiddlewaresecureinvoker is used to invoke a synchronous cali over the secure
network

Syntax: appmiddlewareinvoker(inputParams, isBlocking [.indicator] )


appmiddlewaresecureinvoker(inputParams, isBlocking, indicator)

inputParams is a JS Array object: "serviceiD" and any input parameters


isBlocking is set to true, further clicks or actions on the form are blocked. If set

to faise, the user can scroll through the Ul but cannot perform any actions. If this
is set to true than an network progress bar will be shown in Phone non native
applications.

r
r

indicator: If set to true, a default network progress indicator will be displayed


(applicable only for iPhone native application).

Return Value:

result: It will return the JS Array object containing the data and up to 3 system
Vales: opstatus, erreode and errmsg.

r
225

Network - Synchronous Services

kony

opstatus will be returned as 0 if there were no errors. Any non-0 value is


considered a failure

errcode will be returned if opstatus is non-0. This will contain one of the
following codes:

1000 - Unknown Error while connecting


1011 - Device has no WIFI or mobile connectivity. Please try the operation
after establishing connectivity.
1012 - Request Failed (If the platform cannot differentiate between the
various kinds of network errors, the platform reports this error code by
default)

1013 - Middleware returned invalid JSON string


1014 - Request Timed out

1015 - Cannot find host

1016 - Cannot connect to host

1200 - SSL Certifcate related error codes.

errmsg: will be returned if opstatus is non-0. This will contain the text error
message associated with the errcode

Note: For all middieware error code please refer "Application Server Error Codes" module
of Kony Server Installation guide.

HP

Network - Synchronous Services

kony

Example:
var inputParams = {serviceID:"GetCustomerData", CustomerID:"KH04"}
myResult = appmiddlewareinvoker(inputParams, true, true)

if(myResult.opstatus != 0) {
//notify user that an error has occurred
}

else{
//code for processing the result
}

Remember, if the data returned is in the form of a collection, you'll access that collection as
myResult.<coiiection name> and individual data elements in the collection will be
accessed as myResult.<collection name>.<item name>

Data returned outside of a collection will be accessed with myResult.<item name>

226

"

Network - Asynchronous Services

kony

appmiddiewareinvokerasync is used when you want to invoke a service in the background


/ mltiple functions in parallel over non secure network
appmiddiewaresecureinvokerasync is used when you want to invoke a service in the
background / mltiple functions in parallel over secure network
" Syntax: appmiddiewareinvokerasync(inputParams, callbackFunction)
appmiddlewaresecureinvokerasync(inputParams, callbackFunction)

inputParams is a JS Array object table that has these vales:


serviceiD and an input parameter (can be nuil if no input parameters
are used)
callbackFunction: s the JS function to cali when the service call has

completed.

Return value:

connHandie: a handle to the connection that can be used to cancel the network
call

Network - Asynchronous Services (cont.)

kony

The callback function will fire when the service call is completed (whether it errors out or is
successful)

Syntax: callbackFunction (status, result) where:


m

status: an integer value - indicating the status of service as soon as the service is
initiated till it is completed.
100 - network call initiated successfully
200 - network is in progress
300 - network call canceled - result will not be available and it is nuil.

400 - network call is finished (gets called in both success and failure scenarios actual state can be queried using opstatus in the result)

result: the service result if it is a success. Just like the synchronous calis, this will
return the JS Array object containing the data and up to 3 system vales: opstatus,
errcode and errmsg.

Note: The callback will be called 3 times for a successful call - once that will return

status=100, again for status=200 and then finally for status=400. Your code should
check for that 400 status and THEN process the results.

227

Network - Asynchronous Services

kony

Example:
var inputParams = {serviceID:"getupdates", userName:"user", password:"pwd" }
myAsyncConnectionHandle = appmiddiewareinvokerasync(inputParams, myCallback)

function myCallback (status, results) {


if(status == 400 && myAsyncConnectionHandle != nuil
&& myAsyncConnectionHandle = "") {
if(results.opstatus ==0) {
//code for processing the result table
} else {
kony-print("Service failed")
}
}

Network - Cancel Asynchronous Network

Kony. net. cancel is used to cancel asynchronous network calis.

Syntax: kony.net.cancel(connHandle) where:

connHandle: is the returned handle from the asynchronous network call

There is no return value

kony

Note: synchronous calis will have a platform specific cancellation provided by the platform
(platform to platform - it may vary)
Loading ... please stand by

228

XA

Event Editor

kony

These same methods can be invoked using the Event Editor as follows
Synchronous calis:
Even I. t lito r

Sequence

|n|*l

Code

DefineAcbonSequence

InvokeService (Syrxrronous)
+

B 3; ActionSequence

T BockUI

ti. Syndironous Service: foxnews

Secure

Open MappingEditor

Asynchronous calis:
JHl*!

HBHIBHHHH
Sequence

Code

De fine Action Sequence

Invofce Servtce (Asynchronous) -

SelectService: (None

"3

<.

Action Sequence

Ba.aBBMtBB.BB
ealtbacfc sequence

Add Custom Http Headers

To change ALL your Service actions to either be Secure or not Secure, you can right-click
the application and in the popup men use:
Change/Replace property -> Make All Services Calis -> Secure or Unsecure

JA

Event Editor

kony

In event editor, response of the service is available in the expression editor from the next
action item for synchronous service invocation.

Whereas for asynchronous servicecall response is available in the expression editorfor


any action item defined in callback sequence as displayed below:
fonctiot perr:n,.'CC.er"iri

iT:rei.-.:!-.!-;;:.-,--

..-. .i..:.-

("iJSaStniSI " - lutjoi;

i ' :..

il :

_..

;,.; .;;., i .
.

-r*-...

. .,,... .. , r -r .... , .*.;._.,

i . >

:.-'

:": * -

"

r*pent+rremii+ti

Forasynchronous servicecall, status variable would be populated as part of variables


section in expression editor.

229

XA

Secure External Calis

kony

In the case where the service URLs use the HTTPS protocol then you must ensure that the
certificate for these URLs are installed onto the keystore of the server.
This must be done for all the external URLs using the HTTPS protocol.
If the certificates are not installed, then you will get security validator exceptions once the
call to the service is invoked.

Example: using this HTTPS URL:


https: //login.yahoo.com/config/login verify2? intl=us& .src=ym

O! Yahoo! Mail: The best web-baced email! ! +J


https://lcgin.yahoo.com/config.uogin_vetify2:.intl=us&.src=

Click here to view the certificate

information (this example is


shown in FireFox)

You are connected to

yahoo.com
which is ron by
(unknown)

Verifiedby. DigiCertInc
Your connection te this web site is encrypted to

preven! eavesdropping.
More Information...

Secure External Calis (cont.)

kony

You can click on the More information button and follow the steps:

o U
Contri!

-Wdj

>m.in.

MA Aa

ina^a/arltAa.-

Oanwr

Tha-.iai4iu.rilp

V*4 br"

[>ynlU.
' , CkHhMi

lU-tiu.tdw,

lOmM

I'mm***mfm .ypfrdMgh S*t*r \ N .ypti.| *. nl.Wl.firi.


!'' ;;-.

..-.,.

-i.| ..i-", 'r.. ',-'.! ln'i . F -r-j\-f

ITr r . :-

t*,tn rt*e pm p9 i

t-M- ""'-

Once the certificate is available, it must be placed at the keystore of the server

ForTomcat, the path for the certificates is generally at /usr/java/jdk1.6.0_ 13/jre/iib/security

230

Network -

.konyA'-

Best Practices

For all the all services it is a best practice to check the opstatus value
If opstatus is zero, consider the service as a success

If opstatus is non zero, then it is a failure. The reason for the failure will be present in
errmsg in the results

If the service is a success, it is again best practice to check whether a particular key is
present or not in the service before mapping or reading the data from it.
For example:
results = appmiddlewareinvoker(inputParams, true,

true)

if(results-opstatus = 0) {
//service call failed.

var msg = myResultTable.errmsg

kony.ui.Alert(msg, nuil, "error", nuil, nuil,"Service call error")


} else {
//

service call is a

success

if (results.mycollection = nuil
&& results.mycollection.length > 0) {
myForm.mySegment.setData(results.mycollection)
}

}
-

"

231

Creating the "Home" Screen

kony

The first screen is with a combo box and a segment with a label.

Combo box should load with the listof news types, and that has been populated using the
Master Data property in the IDE:

Master Data for ComboBox


Click on column name to sort

P Use belovv data for previevv meo


Display Vaiue

Key

Select News Type

I18NKev
true

None

World

faise

None

Sports

rafee

None

Tech

fatee

None

Pobcs

rafee

None

Health

faise

None

Travel

fafee

None

Lifestyfe

fafee

None

Opinin

fafee

None

When you select a news type hit the service and poplate the segment with news titles.

XA

Creating the "Home" Screen (cont.)

kony

Here is an example of the code behind the home screen's combo box ondone event:

function fetchNews

(coirioSoxSver-tCb^ecT.)

var r.ewsType

["Select Hews Type", "world", "sports", "scitech", "politics", "health", "travel",


"leisure",

"opinin"];

if (parselr.t (coixbo3oxZver.tCbject.seiectedKeyValue [0]) 0)


i

var basicConf - {ir.essace: "Flease select a news type", alertType :consLar.ts.AlERT_TYPE_I!lFC,


alertTitlel"" yesLabel:"OK", noLabel:"", alertHandler:nall>;
var pspConf - {};
var infoAXert - kony. -i. Alert (basicConf, pspConf);
retorn;

per fcrirX^ServiceCallToFetchNewsCfType [noraTjjflpe [carsslr.t [corrtccxIver.tCbject.selectedKey"alu*[0]) ]) ;

fanction per forrrIMLServiceCallTcFetchHewsCf Type

(Ir.ewsType)

try
i

var service:nputPararr.eters - appID: "5FAJ5Exercise", serviceID: "getFoxHews", r.ewsT-j-pe:Ir.ewsType)


appiraddlewareir.volferasj-nc (serv ceInputParair.eters, FrocessHespcr.seFrcixSe FoxNews);
caten

(err)

alert ("Error"--err)

232

XA

.
-i '
kony

Code Behind the Results Screen

There is similar code in the Results screen to take the selected news title and show the

details on the Details screen.

The following code is in the Result screen segment's onclick event:


function displayNewsDetails () {
var focusedltem = frmHome.segNews.selectedltems[0];
frmNewsSummary.lblTitle.text = focusedltem.lblTitle:
frmNewsSummary.lblPubDate.text = focusedltem.pubDate;
frmNewsSummary .rtxtDesc. text = focusedltem.desc;
frmNewsSummary.lblLink.text = focusedltem.link;

frmNewsSummary.show ();

An example of how the selectedltems contains more than just what is displayed

the

Results form only showed the Title

Services Tab

kony

Don't forget - the Services View lists out all your defined services.

Input parameters

Output parameters

Parameter datatypes

Z Widget... -^.Sampl... 3

/Scrap...

..mmm

-A.

DataStore Keys

H & xml services (2)

~_, bestbuysearch
~ik foxnews

VERY useful when working in code

l"4tH Input Parameters


''n newstype [string}
Output Parameters

'n opstatus [number}


'2 errmsg [string}

^n

httpStatusCode [number}

r_5_P channel [collection}


* webservice-soap services (0)

'

** java services (0)


** scraper services (0)
& json services(0)

*> tmplate services (0)


-

i^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^B

233

Services - Testing Considerations

kony

Let's review:

Services are DEFINED in the IDE.

Services are RUN on the server.

Any time you need to change a service, you MUST republish!

Let's say that you messed up the Xpath for an output parameter and you need to fix that

Change the service definition.

Re-generate the service definition file.

Re-publish.

Restart the app? NO! You don't need to, right? Unless something changed in your
code, you can just re-try that service in your app and it should now bhng the right data
back.

If you changed an output parameter name or added/removed vales then you will have
to change the app and re-launch.

Services - Testing Considerations (cont.)

kony

Common mistakes to look for:

Incorrectly setting up the input parameters for your service call (forexample, the key is
"serviceID" and not "ServiceID" or "serviceid").

Trying to work with the results in code when the results are not there.
Immediately print out your results to the log or put a breakpoint.

VALDATE you're getting the right data back before trying to do any code
manipulating the results.

In your code, always put some IFcondition around the results checking if they are
there are not.

TYPOS...ugh!
Use code assist whenever possible.

Use your services tab to see the service definition input and output parameter
ames as you type in your code or work with the event editor.
Use logical widget ames and variable ames.

234

Exercise - Fox News Service App

kony

Objectives
Be able to invoke services from your app
Be able to manage the output returned from a service call
Concepts
Services can be invoked from JS code (using the appmiddiewareinvokerasync
method) or from the Event Editor

r
-

The results will be a Array object where the keys are the output parameters specified in
the service definition
Procedure

Crate the 3 screen app described in the course notes:


- First screen lists news feed topics

- On selection of particular news feed lists titles in to a segment in the same


screen from the selected topic

- Second screen shows the title, publish date, linkand description of the
selected news item.

On click of link show the third screen

This work should all be done in code

On the second screen, start out using a Label for both the title and description. After
you get it working, switch to a RichText widget to display the description
Use the debugger for this exercise!

Exercise - Fox News Service App

ic

kony

Your app should look something likethis:

S*Jr<t NfWt Typt .

SriVci Nrwt 1,?

ttarf.toi
l-f.bfj't

...

<<t.t-,~***fw

***" IwtZhtemtfM0***tHnt1^

^-'--'-'

After you get itworking in code, then achieve the same functionality using only the Event Editor.

235

Table of Contents Day 2

kony

L^^H rjfihunging/Troubleshootlng

| Module - JavaScript

1 Kony Studio APIs


| Dynamic Widgets

| Kony Studio APIs


| Module - Event Editor
1 Module - Selection Widgets (Self Study)

^^^^^^^^^l^^^lj^^^J^^^^^.^^,^^^,-^!^^!

236

kony

Introduction to

Application Components

XA

Copyright Information

i,kony*C

Copyright Information

Copyright 2012 Kony Solutions, Inc. CONFIDENTIAL

This publication is n copyright. No part of this content may be copied, reproduced, or translated
in any form or mdium without the prior written consent of Kony Solutions Inc.

To obtain permission to reproduce the information (text or graphics) contained in this course
material for any purpose, submit the specifics of your request in writing to Kony via the e-mail
address training@konv.com

Table of Contents Day 4


Module - SAP Connector

Module - Image Widgets

Module - Camera Widget


Module - Map Widget
Module - Mobile Web Widgets

Module - Menus

Module - Tab Widget (Self Study)

Module - Other Widgets (Self Study)

kony

XA

SAP Connector - Overview

-i*

kony

To interact with SAP system, Kony has provided SAP Java Connector
(JCO), which enables communication between SAP Server and Java

SAP system consumes and returns JCO data structure, which is


converted into Data Objects in the middieware and vice versa.

Applications.

Kony SAP connector can execute BAPI (Business Application


Programming Interfaces) functions only.

BAPIs are defined as API methods of SAP business object types. BAPIs
are described and stored in the (BOR).
The Business Object Repository (BOR) is the object-oriented repository
in the R/3 System containing SAP business object types and SAP
interface types & other components, such as methods, attributes and
events.

SAP JCO jar and dll is to be purchased / provided by Customer.

SAP Connector - Architecture

kony

KonyOne Server
Connection

Management
l

18

"

Repository

Loader

c
*

ID

Service
Executor

0
Data Structure
Converter

0.
<

XA

SAP Connector- Architecture (cont.)

kony

SAP Connector architecture provides an interface with Connection


Management, BOR Repository Loader, BAPI Class and Function
Management and Data Structure Converter.
Connection Management: Manages connection pool to SAP system.
Connection pool & Debug parameters can be configured here.
BOR Repository Loader: Performs lazy loading of SAP repository.

BAPI Class and Function Management: Loads BAPI Classes and their
respective operations. Class and functions are stored in the cache. BAPI

Functions are stored in function cache for performance. BAPI functions are
executed by passing appropriate input data.
Data Structure Converter: Basically converts the data received from device
to JCO data structure and JCO structures to data consumable by device.

44
.i *

SAP Connector - Configurations

kony

Steps to follow :

1. Copy sapjco3.dll and sapjco3.jarto


<JDK_lnstallation_Path>/jre/lib/extdirectory

2. Proceed to Enterprise Explorer window,

3. Right Click and Add SAP Server to crate SAP Server instance.

: Outline

i Enterprise Explorer 3

; SAP Serv

^ Siebel Se

,,,

'> Add Server

, JMS/MQ Servers(0)

Vi urO

U*wN*h- 'I'-:

tW

U-"1*- Nvmi*.
Wl"l

_> Web Services (0)


\r SharePoint Servers (1}
p , - RESTful Services (2)
S, JSON Services (0)
l, XMLServices (2)

MP Vene MtMi
Serv*. 1luul

-'-:

>

jww.tt
jd

i...-<:.

r,.:.,
""'*"

CMV.
.*.,...,,,

NO

IftfMft

oc

<M

XA

SAP Connector - Configurations

kony

After creation of SAP Server instance, enable a live connection by


making right click and selecting Connect.
S Outline , | Enterprise Explorer S
_ Outline i, Enterprise Explorer ti

& SAP Servers (1)

*m MySecondSAP

SAP Servers (1)

EES MySecondSAP

__r Siebel Servers (1) >>

Connect

L__-- Business Object P.epositcr/

L>- Remote Function Modules

Web Services (0) j Edit


j L>- SharePoint Server w

& ALE(IDOCS)

Oeiete

(__? Siebel Serven; (1)

r":;j myKOny5harfcrwrc-\i_.j

Q Web Services (0)

.. U>- RESTful Services (56)

C2- JSON Services (0)

A 13 XML Services (56)

SharePoint Servers (1)

c_, myKOnySharePoint (21)

other (56)

& RESTfulServices (56)


& JSON Services (0)

Gfr XML Services (55)

$ other (56)

Currently we are exposed to use Business Object Repositories


and their underiying Business Application Interfaces (BAPIs).

"

Crate SAP service, in services section of the App.


Q Applications 3 c__ Navigator

Right click to crate


a new SAP Service.

l75 ConnectorsExertise

IB IQ forms (6)
C5 popups (0)

B "Jl templates (2)


B fc modules (3)

webjnodule (0)
B"" resources (14)

-i. services (10)

H ^ xml (2)
51 -3j!> webservice-soap (2)

sieb

Di

i*

SAP Connector - Configurations (cont.)

kony

To add desired exposed SAP service, expand corresponding Business


Object Repository.

13 w>vi/v.^.yuw

_L_ _:

Select the exposed


service, and right
click so as to get the
service selected by

BAFI.AMK.fiTlKTDt-iih

i/tfim

OtfUP
i-cr.iinTing Ctfnrrtt

y) MAX_Kgm

ApflkltK*. PlKfcnH
Auto-ID WrjrtrucluM
l*ni: Coenoentnti

l": .i-.LlH'qHliieiH:

selecting

LfitjLuttttr.t (.rou AppbUrtnm


fontrnllinr)
fr ApplifMmn f HmpnnnM
i*te*-t.ot reccrinj

Add to Selected.

ISJrtdtlJJil

Au-Jil Mnjyei'iii.-.

* UUJUMCJMn

* opi ftu ccTorri<


- 4 8APJ CiMfc. CETUST
t

irput -* :-n.

g) BAW..I..K
O) MAXJKWS
-

fnnI.qtH.inrn

' -p-' r 'Mn"

i>miu.r.vi-. i

O BANKUST
* cap D-t savehpuca
Q nv\NIlfiltiiiirbur.,e*i*AiLijiiH'(uniL

Af

SAP Service - Configurations

konyi%

After adding desired service, it appears under Selected BAPI Functions


category, which indicates that the service is available for current App.
tO> CcnnteteinfitinurVJ' ^tvirr Oefin*t>n '

APSrrvpf plrwrf

_!. _1

RVI.RANK.fMI KT Dmj*

. - MPSwvwi,

I..W
,__-rV.-m^MOhjr-tSrprwtn'y

| .Ar

. -~ Re"*e *um.tMi HjtUn

$1 UMc_rntr

ik

C t Eifencdfjv1;Fuvnfint;:; ~^)J
i_

Unei(_ic)|epw'i

__ Cr; '*w* :;>- Ccr-oo^-a


i^-fcit*

4 IW HA"* KTUS1

i-eoroCMW Llau |

IHxtfrv-rMfr c**i 1

[emfeZi|
1 Copyright 2012 Kony Solution

, Inc. CONFIDENTIAL

12

i'

SAP Service - Configurations

kony* *

Provide Input parameters and click Execute to get the services results.

In this example our goal is to find the list of Banks in certain Country with
specific number of rows in count.
5> CommlantgunySAf ^ct>nr ttrmm .
'.Ar'..(...i.1-..rr.

i./.r; i';w r,iii'.t i

B3 M.VKDnCJW

C-jotmi OOjKI Basovari

BHtWttnMMRMMilM

iwt PM sm W

--

dnV

f-r;ij.nw nm j
NnmMi qm I

Copyright2012KonySoliJions, Inc. CONFIDENTIAL

13

SAP Service -

Configurations (cont.)

kony

LW (.onnectorsfcxercise'SAP Service Definition j i

* IPI_BAIIK_GETL15T Details

i i

SAP Server

SAPServers (1)

rtnte
H B RETURN

UJ MySecondSAP
Gr BustnessObject Repoatory
l 3 Remote Function (Modules

TYPE

irr- ALE(IDOCS)

@ ID
NUMBER
MESSAGE

.._ Selected BAPIFuncbons (1)

Eg MySecondSAP (l)

ti?- Busness Object Repositcry


Lr Ooss-Appication Components
, Bank

Bank
Ht BAPI BANK GETUST

a. xo;

LOG.NO
LOG_MSG_NO
MESSAGEJ/1
MESSAGE_V2
MESSAGE.V3
MESSAG_V4

| Uakje
TYPE. IP,NLr-SER. MESSi

000

000000

(Ti dadamittto
<

BANK CTRY

| BANK KEr-

| BANK NAME

| CTTY

US

021000039

Otfcarc

US

043000261

Mellon Bank

Philadelphia

L!S

033000108

First Union Bank Trust

Chicago

US

083000315

US

113109673

NabonsBank

HOUStOn

US

121000353

Chase Manhattan Bank

New York

US

123123123

Gbbank

New York

US

123445673

Chase Manhattan Bank

US

234S673

Commerce Bank

PhdacteipkBa

US

123456780

PNC

Marlton

US

123456764

Chase Manahattan

New York

US

123456783

MekmBank

PhiaddpHa

US

123456789

FidelitvBsnk

Los Anodes

Nm York

Union Bank of Caifaria

New York Otv

npul Paranwt^ Result 1J)

- -

__

_|

AA

SAP Service - Configurations (cont.)

k-i *

SAP Services can render mltiple Collections as of output on the call of a


cpr\/ifo
OCI
VILvC.

E? 'Connecto(sExercise;SAP Seruke Defirtion 3

SAPServer

^ ^

tlAPlJJAJIK_GtTDETAIL DctoU

L_f-SAP 5ervers (1}

lian*

CJ MySecondSAP

{Valu

- ~ B4I#:_AD0RESS
5) BANK_NAME
J) REGIN
f3> STREET
CITY
5) swiFT_ccce

~ Setected 8API FuncDons (2)

EJ MySecondSAP(2)
L-1-Business Object Repository
3' Ooss-Appteabon Componenls
i^-Bank

O-Bank

[EArjKJiAME. REGIN, ST...


Otfcank
NY
ParkAvenue
Me"York
cmusxx

Q>bat#;_group

* EAPI_BAt#I_GETDTAIL

5) POBK_CURAC

.-.j inputParams

@ BANKCOUNTR
5> BANKKEY

&BAf*,_NO
{$> POST_BAMC

5) password |

j) BANK_BRAMCH

S ADDR_N0
E 5 BANK_DETAD.

flB m a

^^^ Output Params^J

021000089
Manhattan

(CREATJWTE. CREATOR,.,.

> CREATJJATE

FnMar1100:00:00 IST2005

> ADDR_l

Q> CREATOR

CS03184S

0 BANK_BRANCH | 1

>BANK.NAME [*:!'

J)SETHOO
,5) FORMATTTNG
5 6Ar*_DBTE

> BANKHO
S> CTTY

Q>TYPE

S 8At*_GR0UP

RETURN

pYPE. ID, NUMBER. MESS...

G> ID

(5) POBK.OJRAC
g> P0ST_BANK i:-.

S> NUMBER
>MESSAGE
LOGJJO
LOG_MSG_NO
& MSSAGE_V1
>SSAGE_V2

& REGIN . 1 "


S> STRJ^T
!? i'Trrrrr :

^" B BAWJ)ETAIlS
Vw - CRIC -^^

* BAPIJArJKJXTUST

000

000000

nput Pramelos RmJt j

Copyright 2012 Kony Solut ora, Inc. CONFIDENTIAL

15

SAP Service - Properties

kony

After creation of a SAP Service, its properties can edited from


sap_ServiceName.properties file.
O Applniticni

.7. UjJMjJrter

* 0 1
"

SAPSenllSAPP
j ,~ lormt i5j
4 k\ mobile 3)

[~]fc'ie.'.-.Srr. :Fc"'i!
[~].imSAPServiceTr'.lOnt
hmSh.rePo.nt
[J 1'mSnbetSenrice]

tblt (0)

.:

. .

Clier.^.inrj-E
ciier.t .taas-ac

elier.t-uaer-

ci;er.i.3r.;_r.;declie.iic. jyar.r-;:

clier.i.poawd*
clier.. trace-:
cHe=c.clier.c-:-::

cier.t.sr.c_qoF-:

* deifctopOj
T pepupt (0)
V iemplM*i(3j
* module--B)

C/ .vrb_modu. (0)
. Krvif.es (9j
.*; ,'.tb;nvice-10p (1)

tefv.cel (2]

BAPt.BANk.GETDETAH

> 3API.BANK.GETUST
O Censle

_ p.M7SAP.p.0(!,rt,f-."^>

Kony Studio Contole

V. npj.lj.jtitnai-l' ptcpfrtrr-,
evicnfH

Bbtll5,

r
-

XA

SAP Service : Sample Exercise

kony

Objectives:
r

To be able to pul the list of banks in certain country using SAP service.

..,,!
't.1;W

su^
1 US

Cri&inH tsts

K4*tonBnk

071000089

NraVork

0430002b t

PMedelph

2HC* O*3**08
Ur..wtB*rlt

rjooo,,.

Naboi.tBa.nk

U3i09Vn)

Chicago

Houston

rt......

SAP Service : Sample Exercise (cont.)

kony

Concepts:
Configure the SAP Server instance in Enterprise Explorer.

Identify and add services from the exposed BAPI under BOR

Procedure:

E7

SAP Server Explorer

Crate a new SAP service

Expand required BAPI under BOR .

Add BAPI_BANK_GETLIST

Provide Input parameters as Country name and


Row Counts.

B 13- SAPServers (1)


5 __2 MySecondSAP

F+l & Business ObjectRepository


S -fij> RemoteFunctionModules
S _r- ALE (IDOCS)
B Ir- Selected BAPI Funcoons (1)
E=3 DZg MySecondSAP (1)
B Lr- BusinessObject Repository
E ir- Cross-ApplicationComponents
B tr-Bank

B - Bank
ffl BAPI_BANK_GETUST
B

Ib (0)

SAP Service : Sample Exercise (cont.)

kony

Let us assume , the following form layout is designed for puiling the list of
banks from SAP Server.
Outline 23 ;

grjr

i Enterprise Explorer!

IH i

E {^j Form -frmSAPServices


B HBox - hbxOne
;_._, Image2 -imgSAP

tbxCity

Get Bank Lists

ibr Label - btFormTitie

H EJ HBox - hbxTwo
<5p TextBox2 - tbxCity
O

IblBankName

IblBanktXey

Button btnHJtSAPServices

B 3 Seoment2 -segSAPBanksts

IbIBankCity

S 3HBox - hbxThree
U Label - IbBantf-Jame

*t Label -IWBankKey
^

LabeJ - IWBankCitY

I Men Container

Menu

SAP Service invocation by Code

kony

Following pseudo-code would suffice the Service invocation and mapping


service results.

frmSAPServiceTestOneFunction(): TO invoke SAP Service


s

BAPI_BANK_GETUST

function frmSAPServiceTestOneFunction ( eventobject )

var Service_InputParam = {};

Service_InputParam[ "serviceID" ]

Input Params

g)
<)
B
<J)

BANK.CTRY il
MAX^ROWS [numbe
password '_::
username [string]

"BAPI_BANK_GETLIST";

Service_InputParam["username"]

******

"

Service_InputParam[ "password" ]

******

"

Service_InputParam["BANK_CTRY"] = frmSAPServiceTestOne.tbxCity.text;
Service_InputParam["MAX_ROWS"] = 20;

BAPI_BANK_GETLIST =

appmiddiewareinvokerasync (Service_InputParam , functionMapValues );


};

10

SAP Service invocation by Code (cont.)

kony

functionMapValuesO : To map Service results on Form's Ul elements.


i

BAP1_BANK_GETUST

a _ j Input Params

function functionMapValues(status,

g)

Q)

BAPI_BANK_GETLIST)

{
var my_temp =

for

[];

(var il in BAPI_BANK_GETLIST ["BANK_LIST"]

BANK_CTRY ;.-
MAX_ROWSnumber]
password [stnngj
username [stnng]

. Output Params
a n BANKJJST IColledion)

BANK.CTRY Islnngl

$ BANK_KEY

<

S> BANK.NAME .
OTYIitnng]

my temp.push(
-

RETUP.N

"lblBnkName": BAPI_BANK_GETLIST["BANK_LIST"][il]["BANK_NAME' ],
"IblBankKey": BAPI_BANK_GETLIST["BANK_LIST"][il]["BANK_KEY"] ' 3 Segm*nt2 - segOne
"IbIBankCity": BAPI_BANK_GETLIST["BANK_LIST"][il]["CITY"]
}

4 *

Common

4 P maiteidfllamap iccllccticnl
4 A, Label - IblBankKey

4 9

Common
*>text ltnng

1= .I8n-.r3Ct.Ctnr.13l
na visible bcolean)

frmSAPServiceTestOne.segOne.setData(my temp);
4

.si

Label- lblBnkName

9 Common
4 .b. Label - IbIBankCity

};

** Common

B^SS.^.^381

SAP Service : Sample Exercise (cont.)

kony

As expected, the outcomes are

The list of banks in US.

r
Cltibank

021000089

New York

MellonBank 043000261

k&Trust 0B30D010a

Philadelphia

Chicago

lu. 083000315
NationsBank 113109678

Houston

11

K*

Image Widget - Introduction

kony

Image widget is a non-interactive widget that you can use to display a graphic from local or
remote source.

Supports only PNG and JPEG images.

If you drag and drop the Image widget onto a Form, image occupies the complete available
width.

If you want to resize the Image widget in the horizontal direction, place an HBox on the
Form and drag and drop the Image inside the HBox and resize accordingly.
If you want to resize the Image widget inthe vertical direction, drag and drop the Image
inside the VBox and resize accordingly.

You can set the image URL or the name of the image inthe local resources folderin the
IDE under the data property in the properties pallet.

12

'

Image Widget - Introduction (cont.)

kony

Naming considerations for a local image:

The file name must contain only lowercase characters.

The file name must start only with an alphabet.

The file name can contain numbers.

Do not use any reserved words or keywords (Java or JavaScript) as the file ames for
the images.

"

Image Widget - How to Add a Resource

There are two ways to add an image to the resources folder.

From IDE:

kony

Right-click on the resources tab inthe applications view add resource.


Browse the image to any one of the platforms.

Default image is a must.

From Workspace:

Go to the application in the workspace and place the images under the
resources/common or specific platform folder.

We can have platform specific images; but their name should always be the same.

If you want to use platform specific images for screen resolutions of240, 320and 480,
you can use mages240, images320 and mages480 subfolders ofdifferent platform
folders. Otherwise, by default, the images placed inside subfolders under common
-

folder will be picked up.

13

Image Widget - Properties

kony

ImageWhenFailed: Specifiesthe image to indcate that the image (that is being


downloaded) is not available.

ImageWhileDownloading :Specifiesthe image to indcate that the download is taking place


over a network connection.

Scale Mode: Specifies the scale mode of the downloaded image.

IMAGE__SCALE__MODE_MAINTAIN_ASPECT__RATIO : This mode resizes the source

image to fit in the Image Widget dimensions while it preserves its native aspect ratio.
This is the default option.

IMAGE_SCALE_MODE_CROP : This scale mode preserves the original size of the


Source Image.

IMAGE_SCALE_MODE_FIT_TO_DIMENSIONS : The source image is resized to fill


the Image Widget dimensions. The aspect ratio is not preserved.

src : Specifies the location of the image to be displayed on the application screen.

You can specify an image from the resources folder or specify a URL of the image.
Example:
Local resources:

myForm.myImage.src = "imagel.png"

URL based:

myForm.myImage.src = "http://www.google.com/imagel.png"

Image Widget - Properties

kony

Raw Bytes : Returns the handle to the raw bytes (usually the image captured from the
camera).

Example: The following code snippet takesthe raw bytes from the image captured from the
camera and gives it to an image widget
function customHandler(cameraWidget)

myForm.mylmage.rawBytes = cameraWidget.rawBytes
>

To store rawbytes or to send itover a network, we need to convel it into a base64


encoded string.
To COnvert tO base64, Use theAPI - var base64Img = kony.convertToBase64
(rawbytes);

14

r
r

Image Widget - Properties (cont.)

base64: Returns the handle to base64 encoded string of the image.

We can set the image by using the base64 property use:


myForm.myImage.base64 =

kony

< the base 64 versin of our image>

We can get the base64 encoded string from an image.


var img = myForm.mylmage.base64

r
r

Image Gallery - Overview

JA

.
A
kony

Image Gallery represents a set of images adjacent to each other.


r

Used to crate a grid of images to display to the user.


If the images exceed the row size, they are pushed to the next line.

Shows the selected image by drawing a colored borderaround the image.


Scroll will be downwards and will show image in default size.

All images should be of same size; otherwise, it can cause layout issues.

Use the data property to specify howto poplate the images.

selectedltem property that can be used to determine which image was selected.

Like most selection widgets, the Image Galleryexposes a selectedlndex and

15

Image Gallery - Methods, Objects, &Tables kon aI'

Poplate the gallery using the following method:

Syntax: frmOne.galleryOne. setData(array_of_data) Where:


array_of_data is a JavaScript array containing, at a minimum, the image

information (URL or image file name) with a key value (e.g. [{img="bwmcar.png"> n
Note: You can pass more data intothe array_of_data image array. Like most other
selection widgets, you will have access to the "extra" data when you select an image.

Retrieve the selected data using the selectedltem (to return all the data for the selected

item) or selectedlndex (to return the index into the array_of_data array).
Exposes onSelection event that is invoked by the platform when an Image is selected in
ImageGallery.
preonciickjs and postonciickjs events specific only to Mobile Web (Advanced) and SPA
platform allows the developer to execute custom JavaScript function before & after the
onSelection callback of the ImageGallery is invoked.

Sample code to poplate a Gallery:


galleryOne.setData([ {img="alfal.png"},

{img="audi1.png"},

{img="audi2.png"},

{img="audia4.png"},
{img="audia6.png"},
{img="audia8-png"},
{img="bmw3.png"},
{img="bmw5.png"},

{img="bmw6.png"},
{img="bmw7.png"},
{img="lexusl.png"},
{img="lexus gs.png"},
{img="lexusis.png"},
{img="opell.png"},
{img="skodal.png"},

{img="toyotal.png"}],"img")

16

kkony*

Image Gallery - Properties

Space Between Images: Specifies the space between the images in the Image Gallery.

tems per Row: Itemization in terms of number of rows can be configured for Mobile Web,
there by identifying the number of rows in which the images are supposed to be restricted.
Specified images can be aligned on top or bottom, using Navigation Bar Position.
Reference width/height: These are device independent Pixeis specified against 163 dpi.

Property: [~

Value
referenceWidth
referenceHeh
13 Skin
skin

Skin Defaults

focusSkin

Skin Defaults

l_t- Event
onSelection

Not Defined

i3 Mobile Web

preOndidcJS
-

postOndidS
itemsPerRow

"^2

avigationBarPositioi
SO-~-6ot

Horizontal Image Strip

kony

It is used when we want to display scrollable imageslike a film-strip with some events
attached to it.

If the Images exceed the size of row, those will get arrow marks but won'tcome to the next
Une. All images should be of the same size to get a good look.
-

The images can be static (resources folder) or dynamic (URL Based). Supports the PNG
format.

For a better user experience, use only one Image strip in a page, henee notadvisable to
use more than one image strip in a form.

If the images are dynamic, it isbetter to use a placeholder image till the image gets
downloaded by using either (Image Shown when downloadable image is not available).
j

Padding is not used but instead there is a Space Between


Images property that allows you to set this value for each

platform. It is accessible though IDE but not though code.

z~.
~

z..

17

Horizontal Image Strip - Behavior

If showArrows property is set to true, showConfig property will allow to configure arrows to
the left and right to indcate that there are more images and you can scroll through the
images.

Along with showArrows, showScrollbars property is available.

Will scroll left/right off the screen with the focused image with a colored border around it.

Same code as Image Gallery except the use of imgstripiD.setData, instead of


galleryID.setData...

selectedltem and selectedlndex are still used to know what was selected (including any
extra data set for each item).

Horizontal Image Strip - Properties

kony

Platform specific properties -

leftArrowlmage and rightArrowlmage allow you to configure the arrows for all platforms
except mobile web.

leftArrowFocusImage and rightArrowFocusImage accepts the image to be set as left


and right arrow when in focus.

Both of these widgets (Image Gallery and Image Strip)share the following properties:
ImageWhenFailed
ImageWhileDownloading

Space Between Images (%)


onSelection : the function that handles this event has no arguments. Use the

selectedltem property to retrieve the info about the selected image.


preonciickjs and postonciickjs events specific only to Mobile Web
(Advanced) and SPA platform allows the developer to execute custom JavaScript
function before & after the onSelection callback of the HzImageStrip is invoked.

topyright 2012 Kony Sol

18

Horizontal Image Strip - Views

kony

HORIZONTAL_IMAGESTRIP_ VIEW_ TYPE_STRIPVIEW:

In this view the images are placed side by side and looks as if the images are placed in a
strip. You can scroll through the images and view the desired image.

HORIZONTAL_IMAGESTRIP_ VIEW_TYPE_SLOTVIEW:

In this view the images are displayed one at a time. The images change with the left or right
gesture.

This view is useful when you want to present a 360 degree view of an object (for example,
a car or device).

Android specific Slot View properties:

For Android platforms, if you select slotview, the following properties are enabled:

flingVelocity:Accepts a number (in density independent pixeis) representing the


velocity at which user flings the imagestrip in order to actvate auto-flippng the images.

fliplnterval: Accepts a number in milliseconds representing the time interval to wait


before flipping to the next image. This is applicable when auto-flipping is activated

when user flings.

scrollDistance: Accepts a number (in density independent pixel) representing the touch
scroll distance to travel to consider for navigation between imaqes.

Hz Image Strip/lmage Gallery - Data methods kon A'*

Both the Hz Image Strip and Image Gallery widgets support the following methods for
setting data.

The Widget reference guide has good info on all of these

imagestripiD.addAii/gaiieryD.addAii: used to add the specified images by

appending them to any images already in the widget

imageStripID.setData/galleryID.setData: USed to Set the data for the Widget.


This replace all the data.

imageStripID.setDataAt/gallerylD.setDataAt: USed to add data tO the widget at a


certain location in the collection

imageStripID.removeAll/gallerylD.removeAll: USed to remove all the images


from the widget

"

imagestripID.removeAt/gallerylD.removeAt: USed to remove the Specified


image(s) from the collection

19

'

Exercise - Hz Image Strip

kony

Objectives:

Use a HorizontallmageStrip widget in an application.

> Simlate animation by displaying a series of similar images in slotview display mode.

Concepts:

HorizontallmageStrip widget is used when we want to display scrollable images like a


film-strip with some events attached to it.

Retrieve the selected data using the selectedltem (to return all the data for the selected
item) or selectedlndex (to return the index).

Procedure:

Let's crate a spinning car app!

Crate a 1 screen app with an HZ Image Strip widget.

Exercise - Hz Image Strip (cont.)


Use the dafa property to show the 35
car spin images (audispinl.png through
audispin35.png in order)
For both iPhone and Android, set the

.
A
kony

rfPL^ 7.7 ru

V^LaS,

View to slot view and set the Alignment


to middle-center

Adjust the margin on the Phone to


keep it from stretching (try about 100px
right and left)
Play with the flingVelocity and
scrollDistance parameters for Android

When you run, sliding your finger back


and forth will "spin" the car.

20

r
r

Camera Widget - Overview

i
A
kony

Camera widget can be used in any of such scenario like :


Automobile Insurance - To capture the scene of an accident for claims

To capture VIN (Vehicle Identification Number)

The Camera widget is used to invoke the native camera of the device.

The Camera widget is used like a Button.

The basic Properties like text, text i18n key, skin, alignment, expand etc. that are supported
for the Button are also supported for the Camera widget.
"

On invokingthe Camera widget, the native camera of the device s opened for capturing the
picture.

The standard camera features such as preview, save or discard for the captured picture are
device-specific.

Note: Native camera cannot be invoked using an API through the code. It can only be done
using the Camera widget as part of the Ul.

21

AA

Camera Widget - Overview (cont.)

kony

Example: camera flow on a BB Storm device:

On pressing "Discard" button or the device back key, the application is returned to the
previous screen.

On successful capturing of the image, the captured data is returned to the application by
native camera.

"Use" and "Discard" naming may change from one platform to another.

Camera Widget - Overview (cont.)

kkony*

Once the image is captured, the device's camera will store the image in memory.

When using the Camera widget, the captured image is returned as an image handle.
This image handle, consisting of the raw content of the captured image, can be retrieved
using the rawBytes property of the Camera widget.
For example, to retrieve the captured rawbytes:
var capturedRawContent = myForm.myCamera.rawBytes

Once we have the handle to the data, the application can use it in variety of ways like
displaying the captured image to the user through image widget or send the image n an email.

Platform releases the reference to the image handle after the first use. Calling above code
snippet for second time will return a nuil.
The Camera widget is not applicable for Mobile Web.

Note: Add some value to "text" property for the widget to be visible.

22

Camera - onCapture Event

kony

The Camera widget also exposes an onCapture event.


On successful capturing of an image, platform invokes this event (if configured), after
updating the rawBytes in the image handle.
The onCapture event can be used to show a preview screen for the platforms that don't
support the same as native functionality.

Do not make any costly operations like service calis during the upioad action event handiing
as the platform holds the camera resources till the event is complete.

Memory Optimization:

It is a best practice to store the image handle (rawBytes) to a local variable for memory
optimization.

Ifthe captured data has to be used globally, then store it on the device and use it
accordingly through localstorage APIs (kony.store.setltem & kony. store, getltem).

Captured data can also be stored in a global variable but we should ensure memory
optimizations. Memory of the global variable should be released immediately after its
usage.

Not clearing global variables results in high memory utilization which will in turn result in
bad performance of the application.

Camera Widget Options & Form Factors

kkony*

Managing the user experience and camera options:

The Camera options are controlled from native camera options (resolution, for example)

All these options need to be set in the native camera options.

For a Blackberry device, capture an image always with the high resolution property
(setting) for better picture quality.

r
-

23

AA

Camera - Using rawbytes

kony

Here are a few examples of ways of using the rawBytes property through onCapture event.

Captured raw bytes can be assigned to an image widget using this function:
function imageTaken (camera)-{
var ICapturedData = camera.rawBytes
myForm.mylmageWidget.rawBytes = ICapturedData
}

Captured raw bytes can be used dynamically to set the background of a button with the
following function:
function imageTaken(camera){
var ICapturedData = camera.rawBytes
myForm.myButton.rawBytes = ICapturedData
}

Camera-APIs

kony

kony.convertToBase64

This API provides you the ability to convel rawbytes to a base64 encoded string.

Raw content of an image cannot be sent directly over a network as part of a


string or can it be saved to the device. So rawbytes data should be converted before
using t.

The syntax is: kony.convertToBase64(rawData) where:


rawData is the data in rawbytes format

"nuil" is returned if raw data cannot be converted to Base64 encoded format.

Note: Base64 data can be sent as part of service call using String parameter and can
be converted to a JPEG/PNG image format using Java APIs.
kony.convertToRawBytes

This API is used to read rawbytes from a base 64 encoded string.

The syntax is: kony.convertToRawBvtes(base64data) where:

base64data is the data in base64 format

"nuil" is returned if raw data cannot be converted to Base64 encoded format.

24

"

Camera - Properties

kony

Capture Orientation (iPhone and iPad)

Specifies the orientation of the captured image.

The orientation of the captured image can be set to: default, portrait or landscape.

Native User Interface (iPhone and Pad)

Specifies if the camera must have an interface with the default Phone controls.

iPhone controls for a camera can be customized by setting this property to faise.

enableOverlay
camera is launched with capability of over-lay a Form Ul over the camera view.
If set to true, the Camera preview is overlaid on the form default is faise.
Available only on Phone, Pad, Android/Android Tablet, Windows Phone

accessMode (Phone, Pad, Android/Android Tablet, Windows Phone )

Specifies how the captured image must be stored. This property is enabled when the
launchMode is overlayform for Android and Windows Phone 7.

Camera - Properties (cont.)

kony

CAMERA_IMAGE_ACCESS_MODE_PUBLIC:
captured image is stored on the device as a Image and is accessible to all the applications on the
device. For example, the captured images are accessible in ImageGallery.

CAMERAJMAGE_ACCESS_MODE_PRIVATE:

captured image is stored as an Image on the device and will not be accessible to any other
application on the device and remain prvate to the application.

CAMERAJMAGE_ACCESS_MODE_INMEMORY:

captured camera image is stored in memory and is never written to the disk.

overlayConfig

The following controls can be enabled by mentioning the corresponding keys in


Info.plst file of the project during building the installable n Xcode:
tapanywhere:Used to capture an image with a tap on the camera preview screen.

overlayForm: Specifies the reference of the form to be rendered over the camera view.

referencelmageToCrop : Specifies the reference of the Image widget in the overlayForm which
guides the camera to crop the captured image to the referencelmage dimensions.

The above features can also be selected or unselected by usingthe custom settings men inthe
image capture screen.

r
r

25

Camera Widget - Image Format Property

XA

kony

Image Format:

The Camera widget supports the following two image formats:


CAMERA_IMAGE_FORMAT_PNG :

On choosing this type, the captured image would be stored in memory in


PNG format.

The original size of the image is retained and has high resolution
This is the default property.
CAMERA_IMAGE_FORMAT_JPEG :

On choosing this type, the captured image would be stored in memory in


JPEG format.

A Compression Level property is enabled after selecting this image type. Vales are
between 0 (no compression - highest quality) and 100 (lowest quality)

Note: The Image Type property is only supported for Phone and iPad. For rest of the
platforms, the data gets stored as raw content.

Camera Widget - Cropping Image

kony

Sometime you may want to store only portion of the image captured.

enablePhotoCropFeature (For Windows Phone (mango) & Android only):

If set true enables you to crop the captured image manually. Default is faise.

26

Camera Widget- Memory Management

kony

The rawbytes of the captured image are available to an application until the application
closes or until the rawbytes are manually deleted.
It is always advisable to relase the captured data after its usage. The captured raw data
can be released from memory using the reieaseRawBytes method.

Syntax: camera. reieaseRawBytes (rawBytes) where:

rawBytes: Specifies the rawbytes of the captured image from the camera which are to
be released.

Note: camera. reieaseRawBytes (rawBytes ) is implemented for OS and Andriod.

Note: Always do a "nuil" check on the raw bytes being passed to this method as releasing a
raw bytes which is already released results in exception.
If mltiple handles (variables pointing) to the same rawbytes exist, and if you relase the
rawbytes using any one of those handles, the other handles become obsolete.

If you store the rawbytes of the captured image in some location on the device by using the
kony.store.setltem API; and you call this method, the rawbytes are deleted from the disk or
n-memory, but the image stored in the specific location remains intact (you must delete the
stored image manually).

r
r

Camera Widget - Emulators

ikonyA

Both the Android and WP(mango) emulators don't provide a way to test the camera.

Blackberry does provide a way as follows:

In the Simlate men, go to Camera Image...

Select a jpg file that you'll use as your simulated camera image.
Once set up, the simulator will use that image for all camera shots.
Typical use of camera is to rotate it to take picture...play with this to see the results...

ForiPhone right click on

| icn and then navigate to - Devices - USB - Apple

Face Time HD Camera

27

Exercise - Camera Widget

kony

Objective

Be able to retrieve the rawbytes from a Camera widget and use this data in an Image
widget

Concepts

The Camera widget is used to invoke the native camera of the device

The rawbytes of the captured image are available to an application until the application
closes or until the rawbytes are manually deleted

Procedure

Let's write a simple app that we can test using emulators.

Crate a one screen app with a camera widget and an image widget - configure the
camera widget with text and skin (optional)

On the camera click event, take the image and show it on the image widget (set the
rawbytes property)

28

Mobile Maps - Overview

kony

The Kony Platform provides a widget to display location(s) on a map.


Locations are defined by their latitude and longitude, along with identifying details like name
and pin image.

At least one location must be defined prior to rendering a map.

The Map widget renders a map using the service(s)

-i

provided by the platform:


Platform

r
r

Mapping Provider |

iPhone

Google Maps

Android (Native Apps)

Google Maps

BlackBerry OS v4.5 and later


(Native Apps)

BlackBerry Maps

Windows Phone 7 (Native Apps)

Bing Maps

Other (BB OS pre-v4.5, J2ME,Thin

Google Static Maps

Best Buy - Seattle-Northgate

F7

Client)

H
Kuiared

Hospial Seflttfe
lnn*igale
M :-. It-:

IGooale

29

Mobile Maps - Overview (cont.)

XA

kony

A location must be defined in code as a JS object and passed into the Map widget via the
locationData property. (can't be configured via the IDE).

There are 3 types of interactions with maps available:


Pan (move around the mapped rea - left/right/up/down).

Zoom (zoom in to magnify / get more detail, zoom out to expand the mapped rea).
Location Selection (display more info or call a function).

On OS, Android, and BlackBerry touch screen devices, users can interact with the map via
actions like:

Swipe to Pan.

Poke / Stretch to Zoom In or Multi-poke / Pinch to Zoom Out.

On Blackberry non-touch devices, users can employ the trackball or track pad to Pan, and
the "+" and "-" icons or "i" and "o" keys respectively to Zoom In and Zoom Out.

---"

Mobile Maps - Overview (cont.)

kony

Platforms like BlackBerry, Phone, and Android provide a native map widget which can be
launched using the openmaps API.

On platforms where a native map widget is not available, the Kony Map widget integrates
with Google Maps and displays the static image with zoom and pan controls.

30

Mobile Maps - Platform Concepts

kony

On non-touch BlackBerry devices, the Map widget has certain limitations:

On non-touch devices, when the trackpad or trackball sets the map widget in focus,
you will not be able to move the focus away from the map to other widgets.

Ensure that there are no widgets requiring focus above the map.

For example, Labels, Images are fine, but a Button or TextBox would be inaccessible
once the map has focus, until the form is exited and reloaded.

No widgets of any kind can be placed below the Map on any BlackBerry device.
There is an interoperability probiem when trying to introduce a Kony widget below the
rendering of a native BB OS widget.
This limitation applies to the browser widget in BB OS as well.

Note: This limitation doesn't apply to footers placed below map widget.

Mobile Maps - Platform Concepts

kony

In general, the Map widget consumes a lot of memory


- only one map per form is recommended.

C3rrief

There is no way to change the default appearance of


the popup that appears when a map pin is clicked by
the user.

The popup cannot be skinned (i.e., choose a


different font or background color).
Best Buy - East Colonial
1601 East Colonia! Prive

fSg)

ECotana, Dr

r
Google

i"

31

Mobile Maps - Requirements for Android


You need a seprate Google Maps API Key for
Android in order to use the Map widget in
applications you develop for the Android OS.

To obtain an Android Map Key from Google,

Go gk

kony

SoogMMipiAPtr.mtly
Sicjii Up loi Ihe Google Maps API

follow the instructions seen here:

https://developers.aoogle.com/maps/docum
entation/android/mapkev

Save the API Key string in a place where


you will be able to cut and paste it into your
projects.

Specify this key by cutting and pasting the key


string into the Android map widget key
properties for the Map widget - and google map
key in the Static Map widget Key property.
Wtlfll
^Static map widget key: j \
od map widget key:

Bing mapwidget key:

i TJns key wflbe used as mapkey for aBmap widgetski appkabon

Note - You will need to do this for every Map widget in your projects.

Mobile Maps - Common Properties

kony

Map Provider: Default is 'google', no other options for now.

defaultPinlmage:Specify an image to use to pinpoint locations on the map.


> A default image for all platforms may be selected.

Platform-specific images may be provided.

Screen Level Widget: Specifies ifthe widget must occupy a major portion of the screen.

Useful in scenarios where you have widgets like the Map that tend to occupy a major
portion of the screen.

Headers and Footers will still appear if this option is chosen.

calloutTemplate : reference to a box widget which represents a Ul tmplate for a custom


callout.

widgetDataMapForCallout: The map must contain all widget data map referred across
mltiple templates, including the dynamic templates for each map location, if any.

32

L-kony^

Mobile Maps - Platform Specific Properties


>

Zoom Level: For Phone ,iPad and Android native apps, zoom level can be set using this
property. Zoom level can be set in code as follows:

r
myForm.myMap.zoomLevel=20

Phone range from 0 to 28, Android range from 0 to 21 and so on.

showZoomControl: (Boolean) This property can be used to enable native zoom capabilities
on Android and Android Tablet platforms.
Show Current Location: For iPhone & pad, Indicates the current location on map as a pin,
circle or none .

map_view_show^current_location_none

mapj/iew_showj_:urrent_location_as_pin

map_view_showjdurrent_location_as_circle

To set current location dynamically from the JS code use.


myform.mymap.showCurrentLocation =
constants. MAJ?_VIEW_SHOW_CURRENT_LOCATION_AS_PIN

I
r

navControlsImageConfig : (Mobile Web (Advanced) and SPA(Phone/Android/ BlackBerry/


Windows NTH ) /Playbook ) images required to configure the zoom (in and out) and
navigation (left, right, top, and bottom) controls on static map view.

Mobile Maps - Platform Properties

kony

Mode: Specifies the map viewing mode. Possible vales are Normal, Satellite, Hybrid,
Street, Polygon, Traffic, Terrain.

This property can also be set through code as follows:


frml.mapl.mode = constants. MAP_VIEW_MODE_STREET

Possible vales for mode availabilities changes from


Platform to Platform as follows:

r
r

i
IOS

Yes

Windows PI,one7

Yes

Android

Yes

SPA

Yes

BlackBerry

Yes

Mobile Web (basic)

Yes

Mobile Web (BJS)

Yes

Mobile Web

(Advanced)

Yes

Symbian

No

'<

I I Washington
DC

G3

r
r

33

Mobile Maps - Coding for the Map Widget

kony

In code, define ocationData as a JS Object

A good place to do this is in the preshow event of the parent Form

> If you are plotting points on the Map widget as part of a function called by some other
event, call formid.show after setting the widget's ocationData property
The required vales that need to be set for ocationData are:

lat: to specify the latitude

ion: to specify the longitude

name: to set the value shown in the pin

Campus 1
My Collego Campus

desc: to set the location description in the pin

image: to specify a pin image

meta: a table for Thin Client/iPhone marker data. Specify: color and abei.

showcalloutjOptional): Shows the callout popup. Default value is true.


calloutData.JSObject][Optional]

Speoifies the widget data for a given tmplate for a

particular location.

Following is a sample code snippet to set one point on the map:


myForm.myMap.ocationData = [{lat:"43.47591", Ion:"-80.53964"
name:"Campusl",desc:"My College Campus", image:"gpin.png",
meta:{color:"green", label :"C" }}]

Copyright 2012 Kony Solurti

Mobile Maps - Coding for the Map Widget

kony

Mltiple points may be plotted on the Map widget by creating an n-dimensional JS Objects
array of pinpoint settings for ocationData:
myForm.myMap.ocationData = [{lat:"43.47591",lon:"-80.53964" ,name:"Campus
1",desc:"My College Campus", image: "gpin.png", meta:{color:"green",

label:"C"}},

{lat: "43.4762",lon:"-80.5403",name:"House 1"ydesc:"My House"

image:"pin.png", meta:{color:"red", label:"A"}}]

Mltiple points
plotted on a map
BEST
PRACTICE: Use

a distinct pin
image if
indicating the
user's current or

starting location
in relation to

other points on
the map

The information

popujrthat displays
in response to
selecting a pin
location

NOTE: The map


popup is not
skinnable; the

appearance of the
popup is controlled
by each mobile OS
vendor

34

Mobile Maps - Other Coding Methods

kony

ocationData can contain more information other than the required vales.

Add other key-value pairs to the object.

Example (extra meta-data highlighted in red):


myForm.myMap.locationData=

{lat: "41. 8771136", Ion: "-87. 6287982", name: "namel",


desc:"descl",image:"a.png", meta:{color:"green", label:"A"}, addr:"123
Sesame St.", city:"New York", phone:"212-555-1212" },
{lat:"41.8782136", Ion:"-87.6298982", name:"name2",

desc:"desc2",

image:"b.png", meta:{color:"green", label:"B"},


addr:"100 Wall St." city:"New York", phone:"212-555-1313" }
I

When a map point is clicked, the additional information provided is made available along
with all the data for that point.

"

Mobile Maps - Events

kony

The onSelectionevent is fired when the user further clicks in the information popup that
appears when a pin is clicked.

The onPinClick An event callback that is invoked by the platform when a map pin is clicked

The ocationData JSObject for the pin that is clickedis returned as an argument for
this event.

> For example, call a function to open a form with detailed data for the selected location
or to provide turn-by-turn directions for a destination from this location.

r
r

r
35

A A

Mobile Maps - Events (Cont.)

kon-i *

Below is an example of a function for this event:

function pointSelected (locations){


for (var store in locations){
var temp Data = {

lat:locations[store]["lat"],
Ion:locations[store]["Ion"],

lat:
Ion

41.8771136
:

-87.6287982

name

namel

name:locations[store]["name"],

desc

descl

desc:locations[store]["desc"],

image : red.png
meta :{color="green",label="A"}

phone:locations[store]["phone"],

city : New York

addr

image:"red.png",

phone

123

Sesame St.

212-555-1212

kony.print(temp Data);
>

>

locations is location data array for the pin that was selected. It includes the additional meta into
configured for this pin.

Note: The same data can be accessed through eventobject property in the event editor.

Copyright2012K any Solut ms, Inc. CONFIDENTIAL

Mobile Maps-APIs

71

kony

map. navigateTo - This method allows you to navigate programmatically from one index
to other ndex in the given list of pins shown on the map.

Example: map.navigateTo(2,true); Where 2 is the index of the pin.

> map. navigateToLocation - This method allows you to navigate programmatically to


the specified location on the map.
Example: map. navigateToLocation (
{

lat:"43.47591",
lon:"-80.53964",

name:"Campus 1",

desc:"My College Campus",


image:"gpin.png",
showcallout:true,

meta: {color: "green",label:"C"}


},true,true);

36

XA

Mobile Maps - Other Coding Methods

A*

kony

SPA and Advanced Thin Clients can plot an rea on a map.

This capability is not currently available for any Native Apps platforms or weaker Thin
Clients.

Define the plotted rea by seeding ocationData with a JS object of 3 or more pinpoints
and setting some platform specific properties:

View: set to poiygon

w/* /

Source: set to non-native

Secauaj

"=" Widget Pro... 3 -r_.SampleCa.. ! / So-aper Wew;

;Property; j
I valu
5

Lr- Genef al
map5-133065Q957
true

iPtione:tTue,Androic:tTije,Bac...

Google map key is not defined...


MAPJ*0VTDERJQOeie

MAR /El!. MODE POLVGON IWimHVMKKai&liUi

MAP_SOURC_NONJJATTVE

Imap view mooe_polygon


MAP_VIEW_HODE_SATBirTt
MAP_\TEWJ40DE_HYBRID
MAP VIEVV MODE TERRAIN

^__H

Mobile Maps - Consideration

XA

kony

On BlackBerry platform (Versin 4.5 and above), you must ensure the following:

There is no focusable widget above the Map widget. This is because, on non-touch devices, when

the map widget is infocus, you will not be able to move the focus away from the map (thisis done to
ensure that the trackball movements will result in panning of the map).

The Map widget should be the last widget on the form. You must ensure this for a good user
experience.

The Map widget should be the last widget on the form. You must ensure thisfora good user
experience.

Setup the MDS - You requireadministrator rights to perform this operation.

Go to MDS location, forexample C:\Program Files\Research In Motion\BlackBerry JDE


X.V.ZVWDS and find for the file rimpublic.property.
" Open rimpublic.property fue in a text editor.

Find and replace the stringlocaihost in the same file rimpublic.property with your system ipaddress[use ipconfig in yourcommandprompt to find yoursystem ip-address].
-

Save the file and start the MDS.

Inthe simulator ensure that the "Network Mode" in "Mobile Network" settings is set to 2G or 3G
& 2G

Make sure the BlackBerry simulatoris not runningbefore starting the MDS.

37

Exercise - Mobile Maps

XA

kony

Objectives

Be able to define an XMLservice and publish the service definition.

Be able to get input from Ul to use as an input parameter for the XML service.

Be able to set a Map widget locationdata data programmatically.

Concepts

The Map widget renders a map using the service provided by the platform.

The locationdata property, which is defined as a table in code, is used to pass the Map
the data for the points to be mapped.

Procedure

The Best Buy Remix API has an XML service that returns store locations for a city.

The API call will look like:

http://api.remix.bestbuv.com/v1 /stores(citv=$citv)?apiKev=Skev

Forthe apiKey, you can use: qmb9dnkg569rgs5za36camq5

Exercise - Mobile Maps

kony

Let's build a 2 screen app as follows:

Screen 1: have the ability to enter a city name and a button to click to trigger the
search for stores in that city.

Screen 2: have a map that shows the returned store locations.

Make sure that the map has an appropriate starting zoom level and make sure that the
data for each pin shows the name of the store and the store address.

tmgmameaitilaammmkm

38

"

r
p

Video Widget

kony

Under Advanced Mobile Web category , we have

Video widget

..- Palette

>

Container Widgets

[3H]Form
___HBox

Purpose:

ScrollBox

Video widget enables developer to play a video

Tab

QTabPane
T VBox

Use cases:

To play an advertisement

To display product feature with a video

Basic Widgets
$ Advanced Widgets
*

Windows Mobile 6jc

^ Mobile Web Adv...

Video

39

Video Widget (cont.)

-i*

kony

Video widget can be rendered only for Mobile-Web and Hybrid based applications.
jpj

Video supported formats are -

i--^-i

Video Widget Source URLs

mp4

Provide source URLs for different video formis

webm

Format

Source Uri

mp4

http://wivw.yo titube.com/watchrfeature= player_detai!page&v...

webm

ogv

ogv

\
\

To poplate video stream, use


Source Property.

0frmTwc ;_i

Hitf.T.kmgTcmVid.

0<

j O P.e,^,.. ] .

Properties K

Cancel

-l. HelloWorld Services _/Scraper View

Property

IValue

Visible

tlue

Render

HTML 5 SPA iPhone:true,HT...

Data
Tt

Source

\
Villeo

^rnpJ I http://www.youtube.c..._Jj

Appearance

Alignment
middle-center
Expand (Applicable to Mobile 1 .hfctrue, vt.false)
Margin (%)
Edit
Padding'%)
Edit
Location

(1.51)

AA

Video Widget (cont.)

kony

By code,
frmScreenVid. videoPlan . source

[{mp4:"mp4 url" , webm :" webm url", ogv:" ogv url"}]

For example: http://localhost:8080/demo.mp4

Poster property can be used to specify an image which is to be displayed as a poster or as


a starting image for the video.

The image location must be an external URL.

For example : http://www.kony.com/sites/all/themes/konv/loqo.pnq

"

40

"

r
-

r
-

Men Options

kony

There are 3 lypesot menus available:

The App Men - created n the project properties and acts like a central navigation
men lor the application.

The Form Men - contains men tems specific to that torm

The Context Men - is speciticto a focused widget on the form.

On any form you can enable/disable the App Men through the form's ShowApp Leve!
Men property.

ForAndroid and Blackberry, if BOTH App and Fotm Menus are turned on, then you'll see
fhe tems in the men together n their native formar

On BlackBerry and J2ME platforms, App Men is also supported on a Popup

41

XA

App Men

kony

The Application Men (App Men) contains features that apply to the application as a
whole, rather than to a specific application form.
The app men acts like central navigation for the whole app.

For example - for a mobile banking application, the application features can include
Accounts, Payments, Transfers, ATM Locations, and Services, placed under App Men as
illustrated in the image below:

I..J

12:46 PM

Br-r,

App men should not be used to perform


application functions like "submit".

01/05/2009
WNnisraHKoan juroion.Kx

01/05/2O09

App men is a very OS specific


paradigm - caution using it on other
platforms for it might not yield the look
you want for a non-iOS device.

-52.00

BILL PAYMEtJT JfiOS 05 3SJ 7441

01/OS/2009
BILL

-300 00

PArUEMT Jan04 05.24* 2441

150.00

01*472009
BU PAVMENT Jn03 06SS* 2443

01/0372009
OUUm .

-30O0 00

IMJJ.Sfttl FROH ttlipu J.-v :.- 1 1 1

App

01*2/2009
OTHER 0ECREASE

Men

J*n 02 06 O

01/02/2009

70 04

2Q

kony>r

App Men: Configuration


The App Men is configured as a project level item.

Right-click the project (in Applications window) and select App Men:
_JD|X]
Application Features
ConfigureAppkabon Features. Click on columnname to sort
tdit llnifnrm ilpecrtic itnpeft.es

FooisSkJn:

"3
"3

No Skin

kJMteem,

<.ytMr

(7 i* -,-.

Mobile

Ti te

TaWet Desktoptoost'. Palm View

[ Icn

| Render | i!3nKey
iphon... None

Event
MotDefined

| Ptetform Spedfa Propef'


ue.
bb: needs_separator"frue

'

_J

CZ

<x

"1

o, |

Controls to add, remove and

move tems up/down in the list.


J

_tJ

Fintsh

Cancel

Men tems MUST have an

con and event specified.

42

App Menu: Icons

kony

Format: PNG

An icn that has visible and transparent pixeis like this

as :

I (not focused) and

and labeled "News" will show up

I (focused) on the Phone.

It is important to set transparencies for desired effect


The same icn for Android looks like this:

Typical menu icons should be 32x32 pixeis or less


Platforms that use icons include:

iPhone, Android, WP7 and Thin Clients

Blackberry lists menu tems in text only

Default Back Button

Default more menu

App Menu in Symbian Platform

Dynamic Menus

kony

You can manage the app menu dynamically with the following methods of kony.application
namespace:

createAppMenu: creates the app menu - must be called n the application pre-appinit.
Syntax: kony.application.createAppMenu(appMenuId,appMenu,skinID,
onFocusskiniD) where:

appMenu \ is the collection, in an array or app menu tems. tems are


configured as
[menuitemID,menuitemName,menuitemlmage,menuitemClosure,menuItemSepa
rator]

skinm: is the normal skin.


onFocusskiniD: is the focus skin.

addAppMenuitemAt: usedto remove an app menu tem.

Syntax: kony. application. addAppMenuIteinAt( index, appMenuItem) Where:

index : at which the menu tem must be added.

appMenuItem [array of arrays] '. Configured as


[menuitemID,menuitemName,menuitemlmage,menuitemClosure,menuitemSepa
rator,menuitemVisibility]

menuitemSeparator & menuitemVisibility is applicable only for BB

43

Dynamic Menus (Contd.)

kony

setAppMenuFocusByiD: used to put focus on a specific app menu item

Syntax: kony.application.setAppMenuFocusBylD(appMenuitemld) where:


appMenuitemiD: is the ID of the menu item to receive focus.

setcurrentAppMenu: uses the unique identifier which represents the App Menu and
sets it as current app menu.
Syntax: kony.application.setcurrentAppMenu( appMenuId ) where:
appMenuid: ID of the menu item to be set as current menu.

getcurrentAppMenu: returns the unique identifier of the current app menu that is set
through setcurrentAppMenu.
Syntax: kony .application. getcurrentAppMenu () Where:
> method returns appMenuid as string. Incase of app menu is not set, nu//is returned.

removeAppMenuitemAt: used to remove the specified App Menu item..


Syntax: kony. application. removeAppMenuItemAt (index) where:

index : at which the menu item must be removed.

For example: kony.application.removeAppMenuItemAtl 1)

Note: all function calis on menu click events can have a signature of:
function onClickClosure(appmenuID, appmenuTitle)

App Menu by Platform

kony

Further App Menu features are classified as follows:


Platform

pkk33

Max Size

Max tems

Overflow Menu

Image

Icons

Shown

tems to "More"

Formats

(pixeis)
iPhone

50x32

Yes

PNG

Android

105x32

Yes

PNG

Blackberry

Not Used

10

No

PNG

WP7

32x32

Yes

PNG

Thin Client

32x32

Yes

PNG

Symbian

NA

Yes

PNG

SPA

32x32

Yes

PNG

I
1

Note: There is no such recommended size for app menu con. Symbian platform scales
down the app con and fits into an oval background.
"

Note: Menu tems displayed on clicking "more" menu item are always displayed without
icons on Android, Symbian and Windows 7 platforms.

1
1
44

r
Slide 88

I could not find the below mentioned details such as max item shown , max sizes icn in the
documentation. Please check the doc once if its available or not then put it as TBD nd update
TrainingContentPreparation-Clarifications-Dependencies.xls
Pavan Kutnar Kurella, 9/10/2012

'

1
1
Form Menu

Each form has a built in menu and the Menultem widget is used poplate menu tems to
that menu.

Follow below steps to add menu tems to the form:

Click on the form menu to expand it.

Drag a Menultem widget onto the menu on the form.

Following are the properties for menu item:

Title: The text that appears on the menu.

Image/Focus Image: Images that will appear on the menu.


Note: careful with image sizes. This is another example where you might want
different sized images for different devices.

Type: Set to ok, back or exit. ok is the default for all devices and back and exit map to
the J2ME devices' phone buttons.

onclick: Used to define the action sequence for the menu item.

Render. Specifies which devices/platforms to show this item - typical to turn off on OS.

Context Menu

kony

A Context menu for a widget can only be defined through code and can be activated on the
Ul by clicking on an item for a prolonged time (extended press).

Context Menus are only supported for Blackberry and Android platforms.

Syntax: myForm.myWidget.contextmenu = [menuiteml, menuitem2,...] where:

Each menuitem is a JavaScript array with following vales:


[id, title, icn, closure, separator, submenu] where:

id: a unique ID for each menu item.

title: the text shown for menu item.

icn: an image resource (Supported only Blackberry JDE 6.0 and above)

closure: a JavaScript function called when item is clicked.

separator:

submenu: a list of submenu items to be displayed (Only for Blackberry).

indicates a separator line after this item (Only for Blackberry).

Note: Android platform does not support icn and submenu - set to nuil.

45

'

aa
-

Context Menu (cont.)

kony

Following is the sample code snippet for adding a context menu for Android platform:
-

myForm.myButton.contextMenu = [["menul","Add",null,loadAccount,nullJ,
["menu2","Delete",null,deleteAccount,null]]

Following is the sample code snippet for adding a context menu for Blackberry platform:
myForm.myButton.contextMenu =

["menul","Add","icon.png",loadAccount,{separator = true]]
["menu2","Delete","icon2-png",deleteAccount,[separator = true]]]

,1ftMp.,1.

IM.M

.<

mj

Menu -Alternative approach

kony

Following table displays the menu types supported by different platforms:

Platform

App Menu

Form Menu

Context Menu

iPhone

Yes

No

No

Android

Yes

Yes

Yes

Blackberry

Yes

Yes

Yes

WP7

Yes

No

No

Thin Client

Yes

No

No

Symbian

Yes

Yes

No

SPA

Yes

No

No

Alternatively, popup with Segment can be used to display form/context Menu for an
application. Aspecificbutton on the form can be rendered to crate the popup menu.
This alternative approach can be used to display menu in thin client (Basic and BJS) to
avoid scrolling issues.

r
r

46

XA

Menu - Considerations

, .V
kony

The behavior of the app menu for thin client is as follows:

On Mobile Web platforms, if you add more than four App Menu tems, the menu tems
beyond the fourth App Menu item are grouped under the Menu item More

In Mobile Web (Advanced) versions, the App Menu is displayed at the bottom of the
screen and is visible even when you scroll the form.

In Mobile Web (Basic and BJS) platforms, the App Menu is available at the bottom of

the form and you must scroll to the bottom of the form to see the App Menu.

Note: For better Ul, app menu should be designed consdering the content present n
the forms for these devices.

Normal or focus skin properties set for the app menu tems doesn't get applied for iPhone,
Blackberry and Android.

The text describing the app menu icons are always in a lowercase in Windows 7 platform.

For thin client applications, only the icons in the list are clickable and not the text.

iPhone and Windows 7 platform doesn't support form menu tems. So render the menu
tems added for a form to faise for these platforms.
On BlackBerry and J2ME platforms, App Menu is also supported on a Popup.

Exercise - Menus

kony

Objective

Be able to use the three types of menus (App, Form and Context) in an application.

Concepts

The Application Menu (App Menu) contains features that apply to the application as a
whole, rather than to a specific application Form.

Each Form has a built in menu and the Menultem widget is used poplate menu tems
to that menu.

A Context menu for a widget can only be defined through code and can be activated on
the Ul by clicking on an item for a prolonged time (extended press).
Procedure

Crate a 3 screen app where one screen is the "home" screen.

Crate an app menu with:

3 options allowing you to navigate home, to screen 2 and to screen 3 (call them
whatever you want).

This app menu should be available only on the home screen and on screen 2 - no
conlinued...

app menu on screen 3.

47

XA

Exercise - Menus (cont.)

item go "home".

kony

0n screens 2 and 3, also add a form level menu item. On screen 3, make that menu

On screen 2, make it do whatever you want.

On screen 2, add a button and add a context menu with 2 tems. One context menu

item will go "home" and one will go to screen 3. Actually clicking the button will display
an alert (to make sure you actvate the context menu and not the click event).
Note: context menu is only available on Android and BlackBerry. What happens on

Phone when you run your code?


mi

Han*- Srr*n

ConteilManu

On long pru&s you wfl qq contoxi


moru

'-

i#

kony

Module - Tab Widget


(Self Study)

48

TabPane - Overview

kony

TabPane widget acts as a container representing horizontally/vertically placed Tab widgets.


Tabs are used to represent different types of data on the same form - for example, an
nsurance app may have seprate tabs for each type of coverage: car, home, life, etc.

Tabs are typically NOT used for steps in a flow.

By default, a TabPane will contain one Tab widget.

A TabPane widget occupies 100% of the screen's width.

Tabs are containers so a Tab widget can contain other widgets.

TabPane - Views

kony

TabPane widget is available in the several different


views.

Using the dialog for the View property (on the


TabPane), you have the following options:

collapsibleview. In this view, the tabs are stacked


vertically and will expand/collapse to show/hide
the contents. This view is commonly used view
for mobile devices considering the width of the
devices.

tabview: Tabs are placed horizontally across the


top - the traditional tab view.

pageview. (iPhone only) Tabs are individual


pages and you move from one tab to the next by
swiping right/left

panoramicview: (Windows Phone 7 only) is like


the pageview but allows for a title image that
spans all the pages.

[tab
fSaoBefrv:
Windows Phone:
WnMobfc 6.x:

Android:

tabvie,',

Palm Pre:

|tabview

J3ne:

jtabview

Symbian:

]tabview

d
d
d

Mobile Web:

jtabview

SPA:

Itabview

zl

|fWsh|

49

"

TabPane - collapsibleview

kony

Using this view, the Tab widgets will be placed vertically.

The Tab widget's name and image are displayed as a clickable header occupying the entire
screen length.

Clicking the header will cause the contents of the Tab to expand or collapse.

r
Tab 1 header -

Tab 1 contents

Click to expand
or collapse

TabPane - collapsibleview (cont.)

Irkony^

If you select this view, the following additional properties are enabled:

Active Tabs:Specifies the Tabs that will be shown as active. By default, Tabs that you
specify in this property are shown expanded.

Expanded Image: Specifies the image that must be displayed when the Tab is
expanded. Something like: O

Collapsible Image:Specifies the image that must be displayed when the Tab is
collapsed. Something like: w

Image Position: Specifies the position of the image on the Tab. The image can be
aligned to the right (default) or left side of the Tab.

Tab Name Alignment: Specifies the content alignment of the Tab Name. The Name can
be aligned to the left (default), center, or right side of the Tab.

Toggle Tabs: Specifies whether the content of a tab will still be displayed ifyou clickon
some other tab.

Ensure not to keep the same alignments for Image position and Tab Name alignment
properties as it will result in overlapping of image with text.

50

A*

TabPane - tabview

kony

Using this view, the Tabs will show one at a time with the
tab titles shown across the top.

Using skins, you can configure the tabs to have the look you
want.

You can view only one tab widget at a time. To view the
content of another Tab widget, you must select that Tab
widget.
Allthe tabs will be placed at the top of the screen.

For Windows Phone 7, the tabs reorganize to always put


the current/clicked tab first in the list.

es

_*tflDl43 11:48 AM

Ht Wekom. Iti K

[_

.__

TabPane - pageview (iPhone only)

kony>c

Using this view, the Tab widgets are placed on seprate pages.
There is the "dot" indicator showing what Tab you are on.

Use the swipe gesture to navigate right/left to other tabs.

Indication of the number of tabs and the present tab is mentioned at the bottom of the

widget using bullets with the present tab's bullet highlighted.

I
swipe

51

TabPane - panoramicview (Windows 7 only)

AA

k*<

Used to support Windows Phone 7 Standard panoramic view for a home screen.
The complete content of the active tab is shown initially in this view.

Navigation is similar to iPhone where you swipe left/right to navigate between tabs.
You can specify an image that will span the entire width of all the tabs side by side.

mHHBHMB

9m999999^^K.9999^9^.9999W

ij^L-^l

i^L^^B

TabPane - panoramicview (cont.)

kony

Following are the additional properties once panoramicview is used:


-

Panorama Image:

Specifies the image to be used for the panorama view.


The content of the tabs is displayed over this image.

The image size should be between 800 x 480 and 800 x 1024 pixeis (height x
width) to ensure good performance, minimal load time and no scaling.
Space above tabs is 173 pixeis is displaying the panorama title, the rest of the
image is behind the tabs (so if your tab skin is transparent, you'll see the whole
image).

Panorama Title:

Specifies the text that must be displayed on the Panorama Image.

This is the title of the overall panoramic view.

Panorama Title Image:

Specifies the title image that must be placed over the Panorama Image.
If both Panorama Title and Panorama Title Image are provided, then the text
specified is placed next to the Panorama TitleImage.

52

TabPane - Navigation on Non-touch Devices ko

AA

On non-touch devices which have a navigation key, the following are applicable:

You can navigate within the TabPane using only the down key.

If you press the down key, the focus shifts to the next widget in the Tab.

If you press the down key while you are on the last widget in the Tab, you are taken to
the top most widget in the Tab.

If you press the right or the left arrow keys, you move to next or previous Tabs.

Tab cycling is supported (i.e., if you are on the last Tab and you press the right arrow,
you move to the first Tab).

Tab remembers the control on which there was focus.

For example, if a button of Tab2 is in focus, and you navigate to Tab1, when you
navigate back to Tab2, that button will still be in focus and not the first item in the
Tab.

Always consider the experience on non-touch devices ifthey are in your target outputs.

TabPane -Skinning

kony

A tab widget can be in active, focus and inactive states in terms of Ul representation. So
TabPane widget supports following three skin properties:
Active: This property specifies the skin that gets applied to a Tab widget which is in
active state.

Active Focus: This property specifies the skin that gets applied to a Tab widget which is
in focus state. This skin property typically gets applicable to non-touch devices where
focusing of a widget plays a significant role in Ul representation.

InActive:This property specifies the skin that gets applied to a Tab widget which is in
inactive state.

All these skins can also be applied dynamically using the following code snippet:
formld.tabPaneWidgetld.inactiveSkin = sklnactive
formld.tabPaneWidgetld.activeSkin = skActive
formld.tabPaneWidgetld.activeFocusSkin = skActiveFocus

Note: any skin referenced must already exist.

53

XA

TabPane - Properties

kony

You can set the active tab with the Active Tab property in the IDE.

You can also set this in javascript with the following code snippet:
myForm. myTabPane. activeTabs = 2

If you've selected collapsibleview, then you can optionally set more than one tab as active
using the Active Tabs property.
al

Opens a dialog to identify the active tabs.

Selected tabs will be expanded by default.

In code use the activeTabs property .

For example:

Tabs List:

TabCar

tabfe

myForm.myTabPane.activeTabs = {2,3}

Active Tac*

TabHome

.~J

Though its possible to add mltiple active


tabs in any view but in all the remaining
views, activeTabs always respects only one
selected item i.e. first element in the array.

nsh

Cancel

r
aa^
TabPane Event

kony

onTabClick

This event is available only when the view of the TabPane is set to collapsibleview.
This event is triggered when you click a Tab to collapse or expand it.
The function you specify can have this signature:
onTabClick (tabPane, tablndex) where:

tabPane: is a reference to the TabPane widget that raised the event.


tablndex : is the Index number of a tab in the tabPane.

"

Following code snippet of implementing the above callback will ensure functionality
achieved using "toggle tabs" property:
function onTabClickCalIBack (tabPane, tablndex) {
tabPane.activeTabs = {tablndex};
}

54

TabPane Events - Cont.

kony

preOnclickJS

This event is available only for Mobile Web channel.

This event allows you to execute custom JavaScript function before


onTabClickCalIBack function is executed.

The function you specify can have this signature:


preOnclickJSCallBack()

postOnclickJS

This event is available only for Mobile Web channel.

This event allows you to execute custom JavaScript function after onTabClickCalIBack
function is executed.

The function you specify can have this signature:


preOnclickJSCalIBackO

Note: These callback function must exist in a JavaScript file under project>module>js
folder

TabPane - onlnit event for Tab

kony

This event is triggered when a Tab is accessed for the first time.
This is triggered only once in Tab life cycle.
You specify functions/action sequences for each Tab.
This event can be used to initialize the static content of the widgets present inside the Tab.

55

XA
-

Considerations

-V

kony

For Blackberry, avoid using long content or more widgets above the TabPane widgets.
Otherwise, it results in bad user interface like jumping while scrolling the page. To avoid it,
set the widgets above the TabPane widget as non-scrollable using the blackberry platform
specific Fixed tems from Topproperty on the form. This will ensure the number of tems as
non-scrollable.

Dynamic access to the widgets on a Tab requires specifying the TabPane container.
For example, if my form (myForm) has a TabPane (myTabPane) that has a certain Tab with
a label (IbIMyLabel), then accessing that label's text property is done as follows:

myForm. myTabPane. lblMyLabe 1. text

To avoid jumping effect on BlackBerry and J2ME, we suggest that you not to place lengthy

textual content above the tab bar while you switch the Tabs.

kony

Module - Other Widgets


(Self Study)

56

AA

Calendar - Overview

kony

The Calendar widget is used as a user friendly way to select the date.

Generally, Calendar widget appears as a label with a small calendar icn and displays the
date or the date format specified by developer.
'USAD 2:41 pm
t e

dd/mm/yyyy

Android

A graphical user interface is displayed on clicking the

Monday, September 3,
2012

Calendar widget to select a date.


The Calendar widget can use both native controls as

well as calendar controls provided by Kony for specific platforr]

TT"

-;-

Sep

03

Set

Calendar - Appearance

* 1

2012 1
Cancel

kony

Blackberry

: BlackBerry

I i^Bi

dd/mm/yyyy

Select Date:

3 Sep 2010

] Done j

iPhone
Carrier "5"

2:48 PM

I
dd/mm/yyyy

B-

57

"

Calendar-Appearance (cont.)

kony

Mobile Web

Windows 7

Calendar - Properties

i**

kony

Date Format:

Specifies the format in which the date must appear

Date can be specified in one of the following formats:


dd/MM/yyyy (Default)

MM/dd/yyyy, MM/dd/yy
Dafe:

This property can be used to specify the default date to be displayed on the Calendar
widget.

The Format will be displayed on the Calendar widget if no date is specified.

Date Component property can also be used to set a date(24th May 2011 04:30:55)
using code as follows:

frmCalander.calendar1.dateComponents = [24,05,2011,04,30,55];

An array object with six elements in [dd, mm, yyyy.hh, mm, ss] format should be
assigned to dateComponents property.

Calendar will remain unchanged on providing invalid parameters to data property.


Note: It is best practice to set a default date to Calendar Widget.

58

Calendar - Setting and Retrieving Date

XA

kony

Date components property can also be used to retrieve the selected date by user as
follows:

var IDate = myForm.myCalendar.dateComponents

Selected date will be returned as a String in the selected Format.

Day, month and year of the selected date can be retrieved using following properties:
var IDay = myForm.myCalendar.day
var lMonth = myForm.myCalendar.month
var lYear = myForm.myCalendar.year

var lHour = myForm.myCalendar.hour

var IMinuteS = myForm.myCalendar.minutes


var lSeconda = myForm.myCalendar.seconds

nuil will be returned of no date is selected by user.

Calendar - View Property (cont.)

kony

Mobile Web BJS: The available views are normal, collapse and inline.

Before Collapse

j show |

1/1/1950
After Collapse

1/1/1951)

| show ]

1/1/1950

Januory

1 Joriuoiy

*i|l950

1950 -

| Done | [ Cancel

Following properties are enabled on selecting viewas inline. LISTBOXES_ONSCREEN


Month Format: Specifies the appearance of the Month as full name, number, or 3-letter.
CALENDAR_VIEWJTPE_DEFAULT
CALENDAR VIEW TYPE LISTBOXES ONSCREEII
CALENDAR VIEW TYPE LISTBOXES COLLAPSIELE

Cancel Button skin and Done Button Skin properties can be provided on selecting view as
"collapse".

59

XA

Calendar - View Property (cont.)

kony

Mobile Web Advanced: The available views are LISTBOXES_ONSCREEN,

LISTBOXES_COLLAPSIBLE, LISTBOXES_POPUP, GRIDJ3NSCREEN and GRID_POPUP.

Properties and Ul look andfeel remain same as Mobile Web BJS for list box onscreen and
list box collapsible views.

Additionally Placeholder, titleOnPopup, and weekdays properties can be specified for list box
Popup View.

The following properties are


available for popup view:

Placeholder: Specifies the


temporary or substituto text that
must be displayed until the

September2010
S

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

actual value is entered.

Title: Specifies a general or


descriptive text for the calendar.
Weekdays: Specifies the
weekdays to be used according
to the lcale.

r
r

Calendar- onSelection

[pise

kony

The onSelection event will be fired once the User has selected a Date in the Calendar.

Syntax: onSelectionCallBck(calendar) where:


calendar - is the reference to the calendar object clicked.

Following code snippet implements the above callback . Itwill ensure that user enters only
valid date.

function onSelectionCallBck(calendar)
{

var mydate =calendar.day;

kony.print ("date is " + mydate);

var basicConf = {message:"The selected date is" + mydate,


alertType:constants.ALERT_TYPE_INFO, alertTitle:"", yesLabel:"OK",
noLabel:"", alertHandler:nuil};
var pspConf = {};

var infoAlert = kony.ui.Alert(basicConf,pspConf);


return;

60

Calendar - Platform Specific Properties

ikony*4

StartDate and End Date (iPhone, Android, Mobile Web):


These two properties can be used to specify the range from which an User can select a
date.

These properties can also be set through code as follows:


Wheel Calendar with mode as both date and time (iPhone only):
myForm. myCalendar. validEndDate = "dd/mm/yyyy, hh:MM: ss"
myForm.myCalendar.validStartDate = "dd/mm/yyyy,hh:MM:ss"

Wheel Calendar with mode as only time (Phone only):


myForm.myCalendar.validEndDate = "hh:mm:ss"
myForm. myCalendar. validStartDate = "hh:mm:ss"

Wheel Calendar with mode as only Date (Phone only) and Grid Calendar:
myForm.myCalendar.validEndDate = "mm/dd/yyyy"
myForm.myCalendar.validStartDate = "mm/dd/yyyy"

Note: The order of the digits entered in the above code snippet is not dependent on the
display format. You can only enter the date in the dd/mm/yyyy format.

A{

Calendar - Platform Specific Properties

kony

Native Look (Android):

On setting this property, the calendar widget appearance will be similar to the
appearance of the calendar on the underiying platform.

View Config: You can specify configuration


for different viewtypes.

\^.9999999999999999999999999999999999M

Calendar View Style

Bid

zl'

San Defaults

gridCdGdecttdSlan:

E>jn Defaults

_d

grldCeTocusSUri:

Skin Defaults

zi\
d

yidCelTodaySIan:

Sten Defaults

z\

Stan Defaults

gridCdEnscbveDflysSkri:

z
E.TOJ.... | X

Sta Defaults

leftNavigabofiImage:

Brame... | * \

i rjh Ca .-.gaton Imagc:


dooefiuttonSlgn:

Stan Defaults

ancArttonSUfu

Stan Defaults

zl
z

v almWKkerriSeJectabte

OK

Canoa

61

Calendar-Clear API

kony

calendar .clear method can be used to clear the date set in a calendar.

On using this API, the calendar widget will display the selected format.
*

Dafe property will return nuil after using this method until the next user selection on the
Calendar widget.
Syntax: calendar.clear(myform.calendar);

If you clear the date set in the calendar using calendar.clearQ API, the calendar label will
display the value set in the "Format" field and the date will be reset to nuil.

This API does not have any return vales.

xa

Calendar - Enable Dates API

kony

calendar.setEnabied method can be used to enable/disable a list of dates that fall

between the validStartDate and validEndDate configured in IDE/Code.


Syntax: calendar.setEnabled(dates, skin, enable) where:

dates is JS table consisting of dates which follows {dd.mm.yyyy} convention.

skin specifies the skin to be used to represent the enabled or disabled dates.

enable specifies the boolean value that indicates if the dates listed must be enabled or
disabled.

This API does not have any return vales.


Usage:

myform.calendar1.setEnabied( {{28,05,2012},{04,07,2012},{25,12,2012}},
skinl,

faise)

62

A'

Calendar - Enable Dates API (cont.)

kony

calendar.setEnabieAii method can be used to enable all the dates that fall between the

validStartDate and validEndDate configured in IDE/Code.


Syntax: calendar. setEnabieAii() where:

This API does not have any return vales.


Usage:
myf orm.calendar 1. setEnableAll ( )

enabieRangeof Dates method allows you to enable/disable the range of dates that fall
between the startdate and enddate and disables/enables the rest of the dates.

Syntax :enableRangeofDates(startDate, enddate, skin, enable)

"

Usage :Calendar.enableRangeOfDates([07,04,2012],[21,04,2012],skin:"si",true);

Calendar - Enable Dates API

kony

calendar.setDateskin method can be used to set the skin and control the look and feel of
each cell in calendar.

Syntax: calendar.setDateSkin(dates, skin) where:

dates is table consisting of dates which follows {dd.mm.yyyy} convention.

skin specifies the skin to be used to represent the enabled or disabled dates.

This API does not have any return vales.


Usage:
calendar.setDateSkin({{28,05,2012}, {04,07,2012}, {25,12,2012}}, skinl)

63

Line - Overview

kony

Line can be horizontal or vertical and is used to seprate page sections.


Line in a HBox (vertical line) always takes the height of its HBox.
Line in an VBox (horizontal line) always takes the width of a VBox.
Use margins to control the alignment of the Line.

Use the Thickness property to set the line thickness in pixeis.


Use a skin to set the color of the line.

%M<M 7:32 PM

VarlosvW
V Une

Inside hbox

Horlzantal Line placed In a form or a hbox

'

Phone widget - Overview

kony

The Phone widget is a Button widget that is hardwired into the kony.phone.dial method.

The Phone widget can be skinned just like a Button.

The Phone widget also has an Image property that can be used to set the image outside of

a skin.

Clicking the widget launches the native phone dialer app.

depending on device, control MAY be returned to the app. For example:


devices retuming to app : Phone4, Andriod 2.1 onwards.

device requiring app restart: Phone 3, Blackberry.

In some devices there may be an alert warning user about leaving the application
and switching to the dialer application.

When the Phone widget is clicked, ALLthe specified text will be sent to the dialer - there is
no event to change the value.

Chars like "+" or"(" or ")" appear on the widget text and will be passed on to the dialer app
on the device.

Note : Available on all platforms except on all Mobile Web platforms.

64

\A

Phone Widget - Some Views

kony

as a button with text


3:02 PM

as an image

lu

flfflje 10:53 AM

/B^

Phone Widget - Properties

kony

Phone widget properties are accessible in code and via the event editor.

To set text dynamically which is the phone number use the text property just like a label.

For example: myForm.myPhone.text = "1-888-323-9630"

Considerations:

Unlike other platforms (for example Android, BlackBerry etc.) you will not be able to
simlate a Phone widget behavior on an J2ME emulator.

Many times you want to display a number as a link.

Use a link widget with the click event calling the phone.dial method
Note: advantage is that you can dial something other than the link text - unlike the
widget.
"

In some devices, like OS, you can have the OS automatically identify phone numbers

in text and provide the click to call automatically (example, the Browser widget with the
detect TeINumber property set to true).

65

Table of Contents - -Day 5

JA
kony

1 Single Page Application (SPA)


-

1 Hybrid Application

1 Mixed Mode Application

1 Module-Services (contd.)
1 JSON Service

Module - Internationalization

Module-JS Custom Widgets

66

HTML5 - Overview

kony

HTML5 is the latest standard from W3C defining markup for the browsers.

Represents a significant leap on the previous markup standards of HTML4 and XHTML.
Broadly HTML5 family comprises of:

HTML5 Markup

CSS 3 Specification

JS Libraries

67

r
r
HTML5 - Features

kony

Local Storage

Web Storage

Web SQL Storage

Oflline package installations

Persisten! and Session storage

Persistent SQLite Storage

Geolocation

Geolocation & Tracking using GPS,


Cells or wi-f

Multimedia

Videos and Audio player

Canvas API
2D Drawing API

Web Workers

Server-Sent Events
Event Source pattern to maintain the

Web Sockets
New bidirectional protocol over

Threading and background process

connection to server open

HTTP

Communications

SVG

Motion Sensors

HTML5 Form Keyboard

Scalable Vector Graphics

Accelerometer, Gyroscope,

Text inputs with different keyboard

Magnetometer
Touch Events

CCS 3 Basic

Touchstart, touchend,
touchmove,
touchcancel

Opacity, backgrounds, text effects,

Rotate, transate, scale, skew,

CSS 3 Transforms 3D
Scale3D, translate3D, perspective,

rounded corners

matrix

backface

CSS 3 Transitions

CSS 3 Animations
Animated with keyrames

Meta tag support

Animation between two states

CSS 3 Transforms 2D

Viewport Definition

Position: fixed support


Maintain an element fixed in the

viewport while scrolling / zooming


Remote

XMLHttpRequest

Navigation Timing API

Notification API

Debugging

2.0

Performance events for WPO

Background alert notificatons

Attach a remote debugger,


such as a web inspector

AJAX2.0: Upioad files, progress

CORS
Cross origin resource sharing, or

Taking pictures, record video and

cross domain AJAX

audio from an input file type

Network Information API

File API

Connection Type: 2G, 3G, 4G,

Opening local files through input lype

WiFi

HTML Media Capture

request

Indexed DB

Agnostic datbase system


(replacement for web SQL

Best Source of information on HTML5 - HTML5 Rocks

Overview of SPA

kony

ASingle Page Application (SPA) represents a special type of the web applications

In SPA, all the application screens are expressed as a JavaScript model/CSS (unlike JSP,
ASPX in a typical Mobile Web application).

JavaScript model/CSS are downloaded to the client-side with the first page download and
resides on the client for the lifetime of the session.

Completely client side execution model (a.k.a) rich client in browser


Dynamic construction of forms and widgets

Each form and its widget hierarchyis represented as a JSON object. This model is then
populated at runtime with the data that drives construction of the resulting DOM.
The application requires server interaction only for data retrieval

Supports only HTML5 compliant browsers. If the Browser does not support the HTML 5
then it will fall back to the XHTML or BJS or Adv.

68

AA

SPA Supported Platforms

kony

Phone 4.x and 5.x

Android 2.2 & above

BlackBerry 6.0 and 7.0 (Touch Devices) and Non Touch HTML5 6.0

iPad and Android 3.0 tablets

Windows Mango 7.5

Thin client (Basic, BJS and Adv) vs. SPA

kon-i%

Thin client (Basic, BJS and Adv)

SPA

Every action would require a server call to execute

All execution happens on the client side

Widgets are rendered on the server and mark up is


given to the browser

Widgets are dynamicallyconstructed on the client


side using JavaScript and CSS

Supported across devices

Supportedon Phone4.x, 5.x Android 2.2, and


above, BlackBerry 6.0 and 7.0 (Touch Devices) and
6.0 (Non -Touch) devices.

Cannot leverage HTML5 teatures like

Leverages all the HTML5 features

localstorage, WebSQL APIs)

Does not support screen transitions, animations.

1 Copyright 2012 Kony Solu llons. Inc.

CONFIDENTIAL

Supports screen transitions and animations

138

69

Thin client (Basic, BJS and Adv) vs. SPA

4'
kony

Traditional Mobile Web Application Work flow

Application Code
JSP/JS/CSS Logic
Services/Data Connectors

Mobile Browser

Enterprise

Kony Aplication Server

Single Page Application Work Flow

Application Code
-

JS/CSS/Loglc

Services/Data Connectors

Enterprise

Mobile Browser

Kony Aplication Server

HTML5 Features in SPA

kkony.V-

HTML5 Application Caching


(AppCache) support

Allows for caching of JS/CSS/JSON resources on the client - Mximum limit


of 5 MB.

HTML5 Local Storage &


Session Storage

Allows for cross-session and single-session local data storage with Web

Allows SPA to look like native applications.

HTML5 Input Elements

SQL.

Allows for new input types suchas number, range, e-mail, URL, data picker,
color and many more.

r
r

HTML5 Markup (Semantic)

Allows for improved structurewith section, header, footer, aside elements

Elements

and more.

HTML5 Video andAudio

Allows video andaudio objects to be presented through HTML5 with noplug-

elements

in.

Browser must support one of the supported formats of each and the source
media must be available.

70

CSS3 Features in SPA

CSS3 2D & 3D

kony

Allows forturning, spinning, stretching, scaling and moving form elements

Transformations -

predefined and custom


elements

CSS-targeted media
queries

Allows optimizing for target device's DPI

CSS3 Gradients, Rounded

Allows for dynamic gradients rather than static images and image UX effects

Corners, Shadows

CSS Selectors

Essentially these are rules that can be applied to specific widgets when they
satisfy a certain condition.

CSS Transitions

Allows for transitions of container elements like form, Pop-ups

CSS Background Sizing

Allows for sizing the background images when applied to container elements
like form, box, pop-up etc.

Handiing Touch Devices in SPA


Handle touch events in

kony

Resolve as tap, double-tap, long press and swipe events

HTML5-capable browser

Support for Gestures API

Action touch events raised through the browser

Third-party JavaScript

Functionality is expanded forthe developer to choose what they want to use,

mobile-optimized widgets

managed through a single codebase.

from vendors such as

JQuery, SproutCore, Sencha


and Dojo can be easily
leveraged

Geolocation APIs,
LocalStorage APIs, WebSQL

Mobile browser is now able to lcate user withpermission granted for one or
mltiple sessions.

APIs

History APIs

Enables cross-browser functionality for URL history which otherwisewould


not be added on a hash change.

Native JSON Parsing

JSON is used for browser communication as native applicationscurrentlydo

71

r
r

kkony.Y-

Additional SPA Features

Image Assets based on Dots Per Inch (DPI)/Form Factors

Gestures using DPI

Supports form and pop-up transitions.

Ability to launch the app in full view mode in iPhone (by using "Add to Home screen"
option).

SPA- Design - Build - Deployment


Design & Develop the
Application in IDE

kony

Application is packaged
>

as a part of Thin Client

i*

App Deployed on Server

war

i r

Serves SPA or Traditional


tyiobi eWeb

Device Detection

(Check if orowser
Suppc>rt SPA)

can

72

SPA- Design - Build - Deployment

kony

All the JS files content is copied to one file i.e app.js and can be found at <wor/cspace>/n/eft
apps/<app name>/spaandriod/appjs/.

Each form will be converted into a JSON object and added in the app.js file
At the run time, in the production, the browser will cache the app.js along with the other java
script libraries.
The konymanifestfile lists all the files that are to be cached
The kony.manifestt'e will be available in the production and not in the local environment

The SPA application will check the time stamp and versin present in the konymanifest and
will download the new versin only if there is a change.

SPA - Development Guidelines

kony

Since browser implementation of JavaScript is single threaded, all the network calis must
be asynchronous i.e kony.net.invokeServiceAsync.

For writing any SPA specific code using preprocessor (ifdef) statements, use the
preprocessor keys in eventeditor.

73

Debugging SPA

kony

Using FireFox add-on's FireBug and UserAgentSwitcher we can see all the pnnts in the
consol.

i
4-

iij^W^BB
-.

w^"^

MM^.^MMM.

lj-;

'1

<"

MalM

<
<h

( M . MM
L* MM M M
M* ; M l-*i *f> M> MnWi

Exercise - Fox News Service App

RSS

kony

Objectives
-

Be able to understand the execution of SPAapplication

Be ableto observe the difference in screentransitions when executing tradition mobile


-

web application and SPA application.


Concepts

All the Ul gets generated on the client side in case of SPA application whereasthe
same happens on the server fortraditional mobile web application.
Procedure

' Remember the fox news exercise we have created. Nowbuildthis exercise for Mobile
web including SPA platform.

" First run this application on Mozilla firefox browser

In middleware's Device DB Mozilla's user agent is mapped to "Basic devices" versin


of mobile web application. So you get traditional mobile web application.
Test the entire flowof the fox news application

You will observe thatthe Ul is getting generated onthe server as even for simple
screen navigation from form 2 to form 3 it involves a network call.

r
74

Exercise - Fox News Service App (cont.)

kon'1 *

Nowchange the user agent of the Firefox browser to pointto iPhone 4 user agent. Use
"User Agent Switcher" add on installed on your Firefox.

iPhone 4 User Agent:

"Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9


(KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7'

Clear the cache

Now again access the fox news application. As we have changed the user agent, SPA
application will be sent to browser.

Test the entire flow of the fox news application again. Now you will observe that the Ul
is getting generated on the Client.

Assignment

kony

Import SampleSPAFormAnimationsApp intoyourworkspace. This application is available


at http://developer.kony.com/PlatformApps.

This application showcases different transition effects on the forms

10.10 18.82 8888.SPA.

I 10 18.82:8888SPA.

-S, Kony
*

<'.

Kony

Empowetmg Everywhere

75

r
Hybrid Application

kony

Hybrid application is a versin of the native application

But unlike native applications, entire layout rendering is done through the UlWebView
(iPhone), WebView (Android) or BrowserField (BlackBerry) instead of the native SDK
widgets.

Hybrid application contains only SPA forms.

The hybrid mode, enables the developer to take full advantage of the native features
without loosing the comfort of having an HTML5 compliant application.

Hybrid application CANNOT utilize native Ul widgets such as Title Bar, Application Menu,
ListView, TableView, Searchbar, native animations and so on.

The native SDK is invoked only for native devicefeatures like GPS ,Camera, Contacts,

Accelerometer and so on. This invocation is donethrough JavaScript blndings.

As the application runs inside the native shell, it savailable as natively deployable package
(.app, .apk, .cod and so on) and can be distributed through app stores.

r
r

76

, '4

Hybrid Application (cont.)

kony

Hybrid application can be represented using the following diagram


Native context

Native shell (UWcoVicw / WcfaVicw /


Browscrfietd) (SPA context)
executefuncl jnrTiaiiveOi.lKX,.,

Go to native context :o
invoke native device

features / perform
native operations

SPA (HTMLS7CSS/JS)

executetum tioninspaconlext
Go lo SPA context to

pass the data back

All the coding guidelines of creating a SPA application are applicable to hybrid application
as well.

Hybrid Application - Considerations

kony

Youcan crate hybrid application using regular forms (Native forms). The build process
ensures that they are converted to Static forms (i.e. SPA based forms).

All the native , static and dynamic forms are converted to JS.

You can use the following two APIs in a hybrid application to share the data between SPA
context and native context.

kony.hybrid.executeFunctionlnNativeContext
("functionName",paramsList)

- To invoke the native device features or to perform native operations


kony.hybrid.executeFunctionlnSPAContext
("functionName",paramsList)

- To pass the data back to the SPA context

1
77

Hybrid Application - Considerations

kony

JS function called from kony .hybrid. executeFunctionlnNativeContext API must


not have any reference to the form elements.
You must restrict the code in native context only for invoking/performing native functionality

Hybrid Application -APIs

4'
kony

Let us take a quick look at the APIs syntax


kony.hybrid.executeFunctionlnNativeContext

kony.hybrid.executeFunctionlnNativeContext ("nativeFunction",
paramsList)

This API provides the ability to send data from the SPA context to native context.
; nativeFunction - Specifies the function that needs to be executed

paramsList - Specifies the list of parameters that function needs to execute

"

No return vales for this API.

Usage -

kony.hybrid.executFunctionlnNativeContext("sampleNativeFunction",
{"Surya",true,{"ATL", "Permanent"}});

function sampleNativeFunction)name, isEmp, empTbl)

// Business Logic
}

78

Hybrid Application -APIs (cont.)

XA

kony

kony.hybrid.executeFunctionlnSPAcontext

kony.hybrid.executeFunctionlnSPAcontext("spaFunction",
paramsList)

This API provides the ability to send data from the native context to SPA context.

spaFunction - Specifies the function that needs to be executed

paramsList - Specifies the list of parameters that function needs to execute.

No return vales for this API

Usage kony.hybrid.executeFunctionlnSPAcontext("spafunthree",{"mahesh
",2012,faise});
function spafunthree(name, birthYear, isValid)
{

// Business Logic
}

Simple Hybrid Application

J4
kony

Here is a simple hybrid applicationwith a single form showcasing the build steps and API
usage.
~ Kony - WrapperJSExenise/fonns/inDUe/hinllativeJd - KonyOne Studio
File Edit Navigate Search Project Run Wicbw Hete"

i-

| <i | / | 9 411

__ I a Kony .,_,Resource
'HAppt.... Z ' tr.Navig..

WrapperJSExerase

13 forms (!)
Ei M mobile (1)
frmNative

J tablet (0)

v desktop (0)

Q popups (0)
*.. templates (0)
<.. modules(2)

f/ web_module (0}
resources (2)

-_. services(0)

Assume string concatenation is only possible in Native context. Let us pass "Helio" and
"World" as two strings to the native context, which concatenates the string and updated
string it sent back to the SPA context.

79

Simple Hybrid Application (cont.)

kony

Here is the code behind the button click -

function callNativeContext(){

kony.hybrid.executeFunctionlnNativeContext("nativeFunction",
{"Helio",

"World"});

}
function nativeFunction(datal, data2){
var concatData= datal + " " + data2

kony.hybrid.executeFunctionlnSPAcontext("backToSPA",
{concatData});
}

function backToSPA(msg){
frmNative.lblNative.text = msg;
frmNative.show();
}

Notice that form element is accessed in the SPA context

Native context function is used only for achieving the functionality (concatenating the
strings) and passing the control and data back to SPA context.

Simple Hybrid Application - Build

Since hybrid application is created as a native binary, you will notice that Native
channel and Mixed Mode build options are disabled on selecting hybrid channel

4 L

kony
app

Phones - Mixed Channel -

h7 (o Hybrid

1* J Phor*.
W

Android

W v- IJiadcbory .O andabovei
Cf Mreed
I-

' iPhone

l~ Q. Android
IBlackberry 6.0 andabove

Mutually Exclusive

- Phones - Native App Channel

aii

r ; iPhone _fe|
T Android J|j
r

g Mango(7.5)

Copyright 2012 KonySolutions,Inc. CONFIDENTIAL

160

80

Simple Hybrid Application - Build

kony

Code is converted to SPA structure during that buiidtime just ike a SPA application build
process:
Computer NewVrjJume (G:) Kony5 - KonyOne - KonySampleWorkSpace temp - WrapperJSExercise - jsoutput Indude m brary

Share with

Bum

New folder
Date modified

Type

js

8/29/2012 3:51 PM

Fe folder

jsvvrapper

8/29/20123:51PM

File folder

spaandroidvvrapper

8/29/2012 3:51 PM

File folder

spacss

8/29/2012 3:51 PM

Filefoder

. themes

8/29/2012 3:51 PM

Fe folder

fi frmftotrve.xml

8/29/20123:51PM

SafanDocument

,_ htrrrfkeys. properties

3/29/2012 3:51 PM

PROPERTIES Fue

_ rmnifVspafiies.properties

8/29/2012 3:51 PM

PROPERTIES File

H Settings.properties.xrnl

8/29/2012 3:51 PM

SararDocument

j WrapperJSExeroseapplication.xm.

8/29/20123:51PM

SafanDocument

5KB

^, WrapperJSExeraseglobalsequences.xrnJ

8/29/2012 3:51 PM

Safan Document

1KB

Name

Simple Hybrid Application

*.

kony

Here is how it looks in iPhone and Android!

..riiCarrier 9

5:18 PM

"i

Chck lo invoke nativo context

Mello Woild

Ensure that Android SDK is 2.3 or above and iPhone is 4 and above

81

Mixed Mode Application

kony

Mixed Mode application is a versin of the native application where some forms of the
application are rendered in the WebViewwhile others are rendered using the native SDK

In a Mixed Mode application, forms can be of the following nature:

Native - These forms are rendered inthe native context using the native layout and
components.

Static- These forms are rendered using native web view. All the HTMLAJS/CSS

required for the form will be packaged STATICALLY along with deployable binary (just
like SPA).

Dynamic - These forms are also rendered using the web view by loading the URL of
the form dynamically.

The advantage of Mixed Mode application over Hybrid application is the possibility of
utilizing all the native Ul widgets (in the Native forms).

82

"

XA

Mixed Mode Application - Data Sharing

kony

Mixed mode application can be represented using the following diagram


JS Execution Context

I Browser/JS Widget Execution

(Native)

Context (HTMLS Static)

execute

natjvecontext

+
executemtccont ?xt

TC

execiAfpwispaca/itext
:-

HTML5/JS/CSS

Native Forms

Device

For native and static forms, the context resides on the device. But for the dynamic forms,
the execution context resides on the server.

Mixed Mode Application - Data Sharing (cont. J.-1*

You can use the following three APIs in a Mixed Mode application to share the data
between the three different contexts.

kony.hybrid.executeFunctionlnNativeContext("functionName",params
List})

To invoke the native device features or to perform native operations

kony.hybrid.executeFunctionlnSPAcontext("functionName",paramsLis
t)

To pass the data to the SPAcontext (browserwidget context wrapped inside native
shell)

kony.hybrid.executeFunctionlnTCContext("functionName",paramsList
)

To pass the data to the thin client context (forms which are loaded from a URL)

83

r
r

X-

Simple Mixed Mode Application

kony

Here is a simple Mixed Mode application with three forms (one each for native, static and
dynamic) showcasing the build steps and API usage.

-,- Kony - Hi3(etUStxt_*rctsc/fi)rii5/iiiobtk'/frniHativi:.kI - KonyOne Studio

File Edit Navigate Search Project Run Window Help

i-,-

;-.-

sffi x

Kony ._,RSOurce
-

"Apote... 3 tr-Novig... = Q| qp frmNative


- :V- J3
| &UfijMixedJSExerctse.

153

E^J MixedJSExerase ^ forms | mobile V frmNfltive.kl

tfl3 forms (3)

- K mobe(3)

t[| frmDvnamic
v

frniNative

^3 frmStaec
& tablet(0)

...

SI <T# popups (0}

11V templates (0)


-

\"/

web_module (0)
i resources (2)
_ services (0)

The idea is to pass data between each of these forms

r
Simple Mixed Mode Application (cont.)

kony

Here is the code to reach Dynamic form from Native or Static form:
function callDynamicForm(invokerlden){
var dataToDynamic = "Helio from " + invokerlden;

kony.hybrid.executeFunctionlnTCContext("passDataToDynamic",

{dataToDynamic};)
}

function passDataToDynamic (inputData){

c ~

,,_.,

~~i

Dynamic form's Ul elements

I (including

frmDynamic.lblDynamic.text = inputData; KrmDynamic .show) are


frmDynamic . show();

' accessed only inthe


referenced function

84

Simple Mixed Mode Application (cont.)

XA

kony

Similarly, here is the code to reach Static form from Native or Dynamic form:
function callStaticForm(invokerlden){
var dataToStatic = "Helio from " + invokerlden;

kony.hybrid.executeFunctionlnSPAcontext!"passDataToStatic",
{dataToStatic};)
}

function passDataToStatic(inputData){
frmStatic.lblStatic.text = inputData;

Static form's Ul elements

(including f rmStatic. show)


are accessed only in the

frmStatic.showf);

referenced function

Simple Mixed Mode Application (cont.)

kony

Finally, the code to reach Native form from Static or Dynamic for:
function callNativeForm(invokerlden){
var dataToNative =

"Helio from " + invokerlden;

kony.hybrid.executeFunctionlnNativeContext("passDataToNative",
{dataToNative});

function passDataToNative(inputData) {

Natjve form,s U| e,ements (nc|udng

frmNative.lblNative.text = inputData;k-formNative. show) are accessed


only in the referenced function
formNative.show();

85

r
r

Simple Mixed Mode Application - Build

-i

kony

Since Mixed Mode applicalion is created as a native binary, you will notice that Native app
channel and Hybrid build options are disabled on selecting hybrid channel.

r
Phones - Mixed Channel

rd
Phone

"^v

p ti
w

Hxed

.Phone

Android

p
w

-;: BJadberry 6.0 and above

Mutually Exclusive
Phones - Native App Channel

All

Phone j

r O1 android f|]

Mango(7.5)

"

Simple Mixed Mode Application - Build

kony

Ifthe Mixed Mode application consists of dynamic forms, we must provide the server details
where the dynamicforms are hosted (as a war file similar to a thin client application).
-Jfll.il
Application Properties

Q"

Edit aopkat.on properoes

.^^^.i^y^^^^^.B^^^^i^Qs ;tohveApp.Sph5aema.Vt)v^
Shortcut icons

Desktop Web Push Nobficobon


-

, Phone Shortcut(apple-tcuch-KO(..png) onmain menu: |

Browse | Oear |

' Web Browser (fsvicon.Ko}:

Browse

Oear I

r
GcnwaliBa^l^tsiAppMcrMr^e

Import JS rWstode Server Detais " "spaV"

Folowng detafe w*be used to forma URL, wUd ts used fbr dynarmc forrosn rmxedmode.

If itis local testing, Jettyweb containers IPand port can be given. However, the IP and port

need to change accordingly ifthe war has to be deployed to a middieware.

86

Simple Mixed Mode Application

Build

kony

Thin client and SPA structure after the build :


- Computer New Vokjme (G:) - Kony5 - KonyOne ~ KonySarnpeWorkSpace temp Mixed-JSExerase - jsoutput ~
Induce in ibrary

Share with

Bum

Name -

^wfolder

jDate mofied

android

8/29/2012 4:40 PM

| Type

1-

Fuefolder

js

8/29/2012 4:40 PM

File folder

jshybrid

8/29/2012 4:40 PM

Refolder

spaandroidmixed

8/29/2012 4:40 PM

Filefolder

spacss

8/29/2012 4:40 PM

Fe folder

themes

8/29/2012 4:40 PM

Re folder

(3 frrnDynamic.xml

8/29/2012 4:40 PM

Safan Document

50 KB

*frmNative.xrrJ

8/29/2012 4:40PM

Sarar Document

50 KB
50 KB

i frmStatic.xml

8/29/2012 4:40 W

Sarar Document

^ htmftreys.properbes

8/29/2012 4:40 PM

PROPERTIES File

j? minifyspafiles.pToperbes
(*] WxtJSExerdseappicabon.xrrtl
[^jMixedJSExerasegiobalsequences.xml
j**j Setbngs.properbes.xml

8/29/2012 4:40 PM
8/29/2012 4:40 PM
8/29/2012 4:40 PM
8/29/2012 4:40 PM

PROPERTIES Re
Safan Document
Sarar Document
Safan Document

1KB
25 KB
5KB
1KB

2KB

i^J^^^^^^^^^^?^^^K^^^i^^^^^^^^^^^^M

Simple Mixed Mode Application

kony

Here's the output in Android

0otoDyn4m.c

GotoN*tiw

Gola itMc

-Helio from rifltive

Since the execution context of different forms is different, the logs also have to be picked
from different places!

87

Simple Mixed Mode Application - Logs

kony

For Native and Static forms, the logs are printed in the Native consol. Here is the output in
Android:
-

I/Web Console(

874): kony.hybrid.executeFunctionlnNativeContext

< at file:///andr

id_asset/web/jslib/konycore.js:55
I/Web Consol)

874):

invoked internal.

executeFunctionlnNativeContext at file://

/android_asset/web/jslib/konycore.js:55
D/KonyHybridJSInterface(

874): executeFunctionlnNativeContext()::

methodName=pa

ssDataToNative params=[nuil,"Helio from Static")

D/VM Function(

874):

D/VM Functionf

874): Executing the Javascript Function

D/VM Function(

874): Dispathcing the function

I/Web Consol)

874): kony.hybrid.executeFunctionlnNativeContext -

>

Non Synchronized Function.execute called.

at file:///androi

d_asset/web/jslib/konycore.js:55
D/WindowsLib(

874): Executing the method index : 1

XA

Simple Mixed Mode Application - Logs (cont.)kon*i

The logs for dynamic forms are printed in the middleware.log (similar to thin client
application)

09 Jan 2012/15:57:22 DEBUG common.KHttpServletRequestWrapper Param Name:khybrid Param value:true

09 Jan 2012/15:57:22 DEBUG common.KHttpServletRequestWrapper Param Name:hybridfunction Param value:passDataToDynamic

09 Jan 2012/15:57:22 DEBUG common.KHttpServletRequestWrapper Param Name:hybridparams Param value:["Helio from Static"]

88

Mixed Mode Application - Guidelines

kony

Though it is possible to invoke the respective contexts for data sharing, itcan lead to
performance issues as the application size grows.
It is recommended to have an entire functional module to be web-based or native module.

For example, the forms in the payment module can be marked as Static, while the forms in
the Remote Check Deposit modules can be marked as Native.

These modules should be independent pieces of functionality and have clear entry and exit
points.

lopyright 2012 Kony Solutions, Inc. CONFIDENTIAL

Exercise - Simple Mixed Mode (Self study)

kony

Objectives

Be able to understand the execution of Mixed mode application

Be able to understand the usage of Hybrid APIs

Concepts

One single application can be created using Forms of different nature (Native, Static
and Dynamic) in which Ul can be created either using native widgets or HTML5 Ul
Components.
Procedure

Crate a New Application with three Forms. Set nature of one Form to native, another
one to Static and third one to Dynamic.

Place two buttons and a label on each Form

Navigate to Forms of different nature on clickof buttons on the current Form


On Label, display the Nature of Form from which you have navigated (Ex: "Helio from
Native" on navigating from Native Form) .

89

'

kony*

Module - Services (cont.)

r
-

r
r

SOAP Web Services

kony

For SOAP Web Services, we'll provide a WSDLand then pick/configure the services we
want to connect to

Let's use an example and walk through it:

The National Weather service has a publicweb service. On their home page

(http://graphical.weather.gov/xmlf) they show this WSDL:


http://qraphical.weather.qov/xml/DWMLqen/wsdl/ndfdXIVIL.wsdl

To crate a new SOAP Web service, Go to webservice-soap present under


services in your application and right-click and select Web Services (SOAP).
, :W

<w.v

" *

'

""

T, ' mL
"

m m

"~

QM

=f*W

i
--

-*!.
IM
X1

Erwrt

-J

r
90

XA

SOAP Web Services (cont.)

kony

Right click on Web Services and select Add Web Service WSDL and give the WSDL URL
and click on OK.
$'SoapSile:W-b-erace(SOP)l>Miori 3
Services

wl

Search Services: \
"J

E=JZ
*

WSDLURLis loaded Guccessfuly

SOAP Web Services (cont.)

kony

The list of available services will be populated

Right-clickthe service you want (LatLonListZipCode in our example) and select Add

to add

that definition.
*; SoapSarrujple;Web Service(SOAP) Defrttjor. U ;
Service*

Define Srvice

'

Search Services: |

B WebServices(1)

GmLatLonst

0
0
9
0

| LatLonListZipCode

JRL*;

| http://grapical,v.eather.go ^/xml/SOAP_5.

oap Action:

| WealherServiees
r CornerPanls
9

.erviceID":

| hito:-' griptvcal.'.'.eather.go

7xml,,D'.VMgt
BroiTOe,..

*reprocessof Class:
JRL Provider Class:

Browse...

GmTimeSeries
LatLonstCityNames

3a ta Provider Class:

Browse...

LarionLstijrie
LatLonL.stSquare

sOS(processor Class:

| Browse...

0 LaJjrtr^tSufeorKP^-v^

nmeout [.ms):

3 Cachable

Cache Duration see); j

ff &MK C NTLM
w

fC)H>oeriLalLoriijst

Selected Services (0)

eV Librarles (0)

User ID: [
NTLMHost: |

Pass.vord:

rm.MDomam: j

_d

Response encodiny:

3 Enayptpasswords whiegenerabng service definitionfue


A Escape embedded xmltn

esportse

1Get Response

91

"

SOAP Web Services (cont.)

kony

Now select LatLonListZipCode service available in Selected Services


Since this service returns a lat/long value for a zip code, we know there is an input

parameter

In the Request rea, we can look for how that value is entered:

lequest

Response

<soapenv:EnvelDpe xmlns:ndf-Tittp://graphical.v\eather.c<)v/xml/D',WLgen/wsdl/ndfdXML.v.sdl' Hnhs:soapenv"http://sdTemas.xmlsoap.org/soap/et


<soapenv:Header/>

<soapenv:Body>

<jidLal-c^st2icodesoapenv:encodingSt>le=Titcp://5clieinas. wnisoap.org/soap/encodHig/*>

<zipCodeUstOTlns;ck\'mU'http://graphical.weather. gov/xml/DWMLoen/sdremaWML.xsd'K5i:type'd'ATnl:iipCodeListT\Pe'>'<^!ipCodeList>

</ndf:Latt.on-islZcCode>
</soapenv:Body>
</soapenv;Envelope >

In this case we can see the ? Indicating that it needs a value there

To test this we can replace the "?" with "98033", save it and click the Get Response button

We can then see results in Response rea and the value are 47.6727.--122.18
Enter that into Google maps and you see that zip code on the map

r
r

SOAP Web Services (cont.)

kony

Now that we know what data to put there, we can crate an Input Parameter with a test
value and use that:

HttpHeaders Input Parameters

Output Parameters | Results

Add

ID

| Testvabe

.apcode^

lequest

98033

Response

<soapenv:Envelope xmJrB:ndf-Titlp://graphic.v.-eather.gov/xrf

I Datatype
strng

|P

Encode

Desaiption

true

'

xrfrB;soape-^ttp./,KrWfw^

xrfns-xs

<soapenv:Header/>
<swpenv:Body>

<r>vdfUatLorUst2jpCode sc>ape;eTKDdingStyle->.ttp://.Kher^
<zirX:ode|jst>mlris:dwml-Tittp://'grarjhial.weatrier.gov
:,'ndf:LatLonList2ipCode>

</5-oaper.v:Sodv >

</soapenv;Envelope >

Request,Response

MLSdiema -instance' 50APNV:encodingSvle=Titr4D://schemas.xTnsoap.org/soap/encodng/'>


//graphical.wearjher.gov/xml^

92

SOAP Web Services (cont.)

kony

The final step is to configure our Output Parameter to retrieve the data we want

In this case it's buried with other data so we'll have to parse ourresult string in codeto get
the actual vales
~"~-^

Http Headers Input Parameter^ Output Parameters^1

Results

To view the resuit of output, did onResults' tabT


Add

The ID field ts mandatory

Test

ID

| XPath

Lationg

1Scope

/AstLatLooOut

response

| Datatype

j CoBecton... | Record ID

string

1Format
None

Our results (click Get Response button and then the Results tab)
Http Headers Input Parameters "Output Parameterf Resiits
^Va^erT/sdTeiria/^

Generating the Services Definition

kony

Generating the service definition for SOAP services is similar to XMLservices

Make sure all your definitions are saved and working properly

Make sure your definition has the focus and is open

Use the tool bar button to genrate the services definition:

Seardi Services : |
.__ SharePomt 5ervers (0)

3 t_e- Web Services (1)

3 WeatherSerMces
0 CwnerPomts
0 Gmi.BtLoni.ist
0 GmlTiroeSeneS
*

LatLor4.statti.ame5

S LatLonstUne

9 LanonstSquare
0 LattonListSubgrid
0 LatLonLoLZipCode
0 tOFDgen

WebServte (Soap) Definibori fueis generated successfully

> tJDFDgenSyDay
0

troFDaenBiOovLatloriit

tC^DoenLatLonUst

= ^Selected Services [1)

a. Librarles (0)

93

Assignment - SOAP Services

kony

Objective

Be able to configure and use SOAP web services

Concepts

For SOAP Web Services, a WSDL is provided and then the desired services can be
selected and configured.

Generating the service definition for SOAP services is similar to XMLservices

Procedure

Use the following SOAP WSDL: http://msrmaps.com/TerraService2.asmx7wsdl

Let's use the GetPIacestlnRect service

You'll need 2 points to anchor the rectangle. For example you can use:
33.870416,-87.703857 as the upper left crner
31.709476,-84.957275 as the lower right crner

continued...

Assignment - SOAP Services

kony

- Use "CityTown" for the ptype in the service call and limit your results to something like

20.

Crate your services definition and test

Crate a small one screen app that has a "go" Button to call your service and listthe
resulting vales in a segment.
' Request/Response
Request

Response:

<soapenv:Envelopexmlns:msr=*htup://msrmaps,com/n xmlnsiSOi
<soapenv:Header/>
<soapenv:Body>
< msr :Ge tPlaces tlnRect >

<msr:upperleft>

<msr:Lon>-87.703357</msr:Lon>
<msr:Lat> 33.870416 </msr!at>
</msr:upper.eft>

<msr:lowernght>
<msr:Lon>-84.957275</msr:Lon>
<msr:Lat >31.709476 </msr: Lat >
</'msr:.o-.vernght>
<msr:ptype >CityTown</rrisr: ptype >
<msr:MaxItems> 10</rr.sr:MaxItems >
< /msr GetPIacestlnRect >
</soapenv:Body>

</soapenv:Envelope>

Copyright 2012 Kony

94

* i

kony

JSON Service

JSON Service - Overview

kony

A JSON service communicates with an external data source using JSON data connector

over the HTTP protocol and returns a response in JSON format.


Defining a JSON service is just similar to XML service

JSON response is generally returned as a JSON string consisting of JSON object

JSON Object is always represented by{ } in JSON response, whereas, JSON array s
represented by [ ] in JSON response.
Important Considerations

JSON Array will consist of an array of JSON Objects or a blank array


JSON Object is a key value pair. The key is a String and value can be a String,
number(int, float, double), JSON Object or JSON Array.

JSON string will not contain attributes

95

"

yA

JSON Service - Overview (cont.)

kony

For defining output parameters, we need to provide JSON path


Following rules should be used when defining a JSON path for an output parameter:

elementName - Selects all child elements of the named Element

// - Selects elements in the document from the current element that match the

selection no matter where they are.


We need to follow the same basic steps as we have done for XML service:

Identify the JSON service

Connect to the service and test

Configure inputs and outputs

Valdate our results

Publish our service

Test services from within an application

Here's the website we'll use as an example which takes a city name and returns the details:
http://ws.aeonames.org/searchJSON?a=Orlando

JA

JSON Service (cont)

kony

To crate a new JSON service, Go to json present under services in your application and
right-click and select JSON Services.
._. )1M-rt,.ac0.ww,ilrlf-aw

O flppfcabons 23 fe- Navigator;

'

5 LTJ5 JsonApp
E LJforms (0)
E ES popups (0)
E lC templates (0)
m, modules (!)

I
-

'

'

i^itoevid

_d

ftVMM 0m
.r. v

:_- OMl

ty ,.\ieb_module (0)
E m resources (2)
E -*. services (0)

WKttmm -

E ' xml(0)

rwsui [n ril

i*i -^ vvebservice-soap (0)

...

1
1
1

1
1
1

ruM^H)

W sap (O)

siebel (0)
ffi / ) mainframe (0)

~D

Na W

shhwa |

D
O

* too,
"! ten Refresh

3etty Web Server

'ntttnitv.ifr lj _.-:e-. .
nao* i"mw .*>vr} fi..

* RFQ*rM/kome

r
r
96

JSON Service (cont.)

kony

Right click on RESTful Services and select Add Service

Give the Service ID and specify the URL and click OK

$ JsonApp:JSON Service Definrban Z \


Services

'- REST/JSOH Service

vXii

REST/JSON Service Details

Search Services : j

Vabdconfigura on.

._- Selected Services : t3

Id":

R. Ubraries (0}

| SearcrforOty

URL": | http://vi,s.9eciames.rjfg/searchJSON?qOriando|

Group: |

(?)

JSON Service (cont.)

OK

Cancel

kony

Select HTTP method of service as GET

Click Get Response to test and view the results


% JwvtMFJUXiMt'MMDJrfnaen ..
l-c

tmmtm lm

|SM>vOb
_) i-n ^t pfryj-j v iwiiiiimiiH

i- ::

I
..

RUTU tanas tu
*

'-

tmatvtxt

mi. .f* r%H

.._-....

Q pj-

d
I'!

I_l

uCt, ").* Cm- -.*.

..

-.,...

l~--l

I--.-1

l
Duc

1 i w r* PrlUM

--*..:

'-"--' |
KMHi .- -. ; :-'.

IHUIB

|ir*i

xl

Our Results

97

H
i
kony

JSON Service (cont.)

'

Configure input parameters (if any) and test


In the example, city Name (value "orlando") is acting as an input parameter

Define an input parameter named "cityName" and test the service by configuring a value
-

Ort

e Sanio*

HttpHwdets , Input Pai ame ters

Outoui Parameters Results

\ :*,-. -.:

[K:f!**.Qe<r4rvt a s:ttmd^JO* K

ID

)fcV*^

Test Valu

dtyName

Iscope

I Datar/pe

request

Orlando

string

1-1

Corresponding results:
ftequcstj.Re.tpotise'

Request; Response
geonames : [

'adminCode 1": TL",


'admriNamer: Tlorida',

'countryCode': US",
'counyl lame": United States',

': y,
"fcIName": 'aty, vtlaoe,...",

"fcode': "PPLA2",
'fcodeName': "seat of a second-order administra uve divisin",
'geonameld": -4167H7,
Tat": 23.5333355,

Ing": -81.3792365.
"name': 'Orlando',

"popufaBon': 233300,

JSON Service (cont.)

kony

Configure the output parametersfor the data to be returned to the application


Retrieve the total countand each city detail from the current example

Include following as part ofcity details: cityName, State, Country, latitude, longitude,
population, geoNameld.
Test the results:
*esn"B

TBy.-v. vrr(t.fe.^*,f. rt.-S.ort Wrtta V*\ rt *T

^dd

ihtvMdntetorr

1Boif.o.

ts^Lflunt

r.VfCri

/tyetwm,

uivflm

MM

'espolie

J :*Uii}>e

lUKta..

vms

'Wne

rnrn~v

iwm

ww

**r?

...;..

Hw*

sima

CWLo

'tone

yOH

SUtC

ilrvfiw:

-;-:-.

ttkJtny

mjnirytMne

rrywn*

atituJc

Mmr

ttonr

oiv.r

Itig

uyGJ

Nor-C

krtg

n*Ww

mg

raryM

tnw

lwjuU'j-j-i

uuuUativi

eiivv:

l*ny

otCbI

'..-*

3tor**mtl

Q-tV-tentiC

resera

(T*ig

cM.<K

tttne

-.-.7-,-t.-

IlUOT

at*K*JrftiCount

Corresponding results:
-**".

llitPwjnrM iueutnviw

ratertar. s-'ctKar"

lr.HJ.

.41*71*7.

r
r

98

-*4

JSON Service (cont.)

kony

Right-click the service i.e searchForCity and select Add to add that definition to Selected
Services.
' "JsonApp:KON Service tefiniton 3

'^"J)rW^:-rSOKSvDefinibon S3

Search Services ; |

Search Services: |
B i^RESTM Services (1)

E -S Pther (1)
0 Ey27iwaw

E Lr- RESTfulServices (1)

E-^ other (1)


0 SearchForty

:e h_L.^.I
HE- Ubraries {0)
i^JEdit
X Dte te

Genrate the service definition for SOAP services is similar to XML services

11

Composite Services

kony

If you need to execute two or moreservices at the same time, then you can achieve that by
creating Composite Services.

Using Composite Services, you can combine two or more services web services, XML
services, or Java services.

For creating a Composite Service, you just haveto selectthe services from the existing
services that need to be combined together. You do NOT have to define the input and
output parameters as they are already defined!
There are two ways in which the composite services can be invoked:

Sequential: Indicates that the services will be invoked in the order you specify. Also, the
output of one service becomes an inputto the next service.

Concurrent Indicates that the services are invoked independent of each other.

Invoking and execution ofone service does not affect the execution of otherservices.
You can crate more than one composite service for your application

99

Composite Services - Creating the Service


-

kony

To crate a new Composite service, Go to composite present under services in your


application and double-click on it.

O Appfccabons U ' XT. Navigator

; Lj5 Corripo5iteServ.icexercise

uu

i* !3forms (1)

' !5 popups (0)


ffi*_' templates (0)

*i*modules (0)
O webjnodUa (0)
S

resources (1)

B -i. services (3)

ffi ^ xml (2)

S "5*-' webservice-soap (1)


> ^y :.: (0)

* Fi ebel (0)
ffiO mainframe (0)
SI * java (0)

ffi '& )son (0)


ffi ** scraper(0)

* * BBBSBBB
** loopng (0)

%*] tmplate [0)

Click on Crate

Composite Services - Configuration

kony

The Wizard let's you configure your composite service:


pUlll..MUJ.I.J.I .IIH

-IX

AiliJ Gumnatn Borneo

Give your service a name


Bi

Set Execution to Sequential or Concurrenr

J.iri,*-.HTV-.liS.,'

0m-Ctr_.VJe-.
(i-V<it:t--je!ieiVLrt:_ij,--!tjytE.:n

Identify the services to run

Alter the execution sequence

JJ

r
r

100

AA

Composite Services - Configuration

kony

The created composite service appears under the CompositeServices pane as shown
Below.
. CimposteSw*,ase:ConpoHi_ Service DefirtDcn _3
- Composite Service

1l__I.I

Total: 1

;- yeB'i*evei-f^tBuyStaesLiXat>orii::SeaAient^
oelGtyService
oelSett^yStorelixatioris

I v Oeste1

"Postprocesior fw ^ttfewEvBesffiuyS torea ocatrorts

| , . |
| XDtele |

1
1

1
1

You can also specify the Post-processor name for the selected composite service

Once you are done with creating the service, you can follow the same way of generating
the service definition file.

Composite Services - Sequential configuration ^^

When creating sequentialcomposite services,typically the outputsfrom one servicefeed


the inputs for the next service.

Since the services are being run on the server, you must configure your services to store
those outputs/inputs in session.

Here's an example:

We want to call a service that returns stores near our location

> That service accepts only city name

We want to do an "around me" function so I need another service to conven my lat/long


to a City.

I will crate a composite service to first convert my lat/long to a cityand then call the
second service to find stores around that city.

Let's see how to hook that up...

101

AA

Composite Services - Sequential configuration konV*


Here's the configuration for our first service:

t_on^teSi!rvlcef_xerci5e:>vML Service Definition 3

Search Services : |

X -il

w Define Service

Http Headers Input Parameters Output Parameters


QetOtYService

E,ervio-ID":
URL":

http://ivhere.yari

Htto Method:

GET

i To view the result of output. &. on 'Results' tab or Te


Add

TbelDffeMBrriarxfatory

* .._- RESTfijtServices (2)


Selected Services (2)

-3 <efp other(2)
# _oeQeblBjr&IoreLocations

Qi)

'reprocessor Class:
URL Provider Oess:

sv orane.
ata Provider Class:

Save the result city in


Postorocesscr Class:

session.
Timeout (nms):

J Cachable

Cache Dureton (se

Basic f~ NTLM

User ID:

Note: the output


parameter name "city".

Pas-Trvord:

imMHost: |

^ M Dorna

r
Composite Services - Sequential configuration kon'C*

Here's the configuration for our second service:

Seardi Services: f
RESTfU Services (2)

B __- SelectedServices(2)

a Mher 2)

Http Method:
Preprocessor Class:

9 getCityService
B

URL Provider Class:

Libraries (0)
Data Provider Class:

Postprocessor Class:

Tmeout m ms):

D Cachable

Server Au then tica don -

h ote: the input parameter name


"city" - this must match the output
from the other service.

P Bask r MTLM
User ID:

fJTLMHost: [~~

102

Composite Services - Sequential configuration

'O

Finally our configuration of our composite service:


Composite Services

H get-learBvBestBuyStoresLocaborts::Sequenhal
getCityService
getBestBuyStoreLocab'ons

In our code, we'd call the getNearByBestBuyStoreLocations using:


The inputs specified for getCityService
The outputs specified for getBestBuyStoreLocations

The server will run them sequentially.


Note: Any pre-/post-processors associated with each service will be run - you will probably
want to valdate the outputs before passing to the next service.

Exercise - Composite Services

kony

Objective

Be able to successfully configure and test a composite service using previously


configured services.
Concepts

Using Composite Services, you can combine two or more services web services, XML
services, or Java services.

There are two ways in which the composite services can be invoked:

Sequential: Indicates that the services will be invoked inthe order you specify.
Also, the output of one service becomes an input to the next service.
Concurrent: Indicates that the services are invoked independent of each other.

Invoking and execution of one servicedoes not affect the execution of other

services.

When creating sequential composite services, typically the outputs from one service
feed the inputs for the next service.
Procedure

Let's configure and test a composite service!


We'll use lat/long vales to find stores around "us"

Service for converting lat/long to a City:

103

Exercise - Composite Services (cont'd)

kony

http://where.vahooapis.com/aeocode?a=<lat>.+<lonq>&aflaqs=R&appid=d0vJmk9c25
DYTZ1YWhNcHqxJmQ9WVdrOVNrURaV3hQTkdVbWNHbzlNelUxTXpRd01 UWXkmc
z1 ib25zdW1 lcnNIY3JldCZ4PTII

Re-use your BestBuy store locator by city service

Hook them up so you can pass in lat/long and get the store locations
Test in a simple app - ok to hardcode inputs and print outputs to log

Note: make sure you use valid lat/long to get stores, if you use vales that represent a
city with no stores, you'll get no stores returned

r
-

r
r

104

Internationalization - Overview

kony

The processofdesigning or developing an application in sucha way that itsupports various


languages and regions is known as Internationalization.

For an application to support Internationalization, you do not needto make anychanges in


the application code or logic.
Internationalization is abbreviated as 18n

I18n supportfor an application has to be defined at the time of developing the application

Internationalization - Implementation

kony

118n for applications is supported by placing text and their associated keys in resource
bundles that are loaded into the application.

Benefits of an intemationalized application:

The same application can run on mltiple locales

Widgets'text is not hard-coded in the application. Instead localized keys are retrieved
dynamically.

Support for new locales does not require recompilation

Region-dependent data such as dates and currencies, appear in formats that confirm
to the end user's regin and language.

For example, we can add a key called currency and its Unicode value for each lcale
will be placed in their respective resource bundles.

105

A A

Internationalization - How it works

kony

When a Konyapp launches, one of the first things to happen is the device's lcale settings
are checked.

In order to display the correct vales, the developer must load the resource bundle
corresponding to that lcale.
-

When the resource bundle for a specific lcale is not available, then the application rolls
back to the default lcale (specified n Configure Internationalization).
Your Job, as a developer is to:

Know what the device lcale is set to

"Get" the appropriate resource bundle for the lcale


Load the appropriate resource bundle for the lcale
Manage resource bundles

Internationalization - Resource Bundle

kony

Aresource bundle is a properties file that contains all the 118n Keys along with their vales.
-

The resource bundle:

Is lcale specific - one resource bundle per lcale

Follows the naming convention of </angiuage_Counfry>.properties

Example:

English lcale inthe United States - en^US.properties


French lcale in Canad - fr_CA.properties

r
r

106

aa

Internationalization - Table

kony

Right-clickthe project in the Applications window and select Internationalization:


_.

~ior

UMEj

t'.smin [lili! Irili-Minlliiliuli.-iiliiH.

il8n

Aoflnrw i otif m rmtQrr ki-y.vni vm,w tw en* (nr

r" /Wd- to add a new key


XjJILol*.

|r-_-5
| fi_CA

Delete - to delete key

J*J*_

EtiVtd

..vd:

Matae^Mw.:

errwran

tvHngr.

i ogr>m.

m de f mvwn

| egn tn

11

'*:.;

f r

/mporf 118n

k*

-.'

---ri

'
.

Export 118n

. r

,*
mm

Internationalization -Adding 118n Content

Before you use the 118n data, you should add the content intothe application

You can add i18n content into the application in two ways:
1.

_j

kony

From the IDE:

You can add 118n keys one after the other manually

We can use the import option to browse to a properties file and load the resource
bundle.

2. Programmatically from the code using APIs

Note: You can add 118n keys only after you configure the locales

107

XA

Internationalization - Configuring Keys

kony

After adding the 118n Keys into the application, configure the 118n Key for all the widgets in
the application.
Below we are assigning 118n key for a label
^iojxj

E3,; -_. Compoa.,. j / Scraper... j =

z*-.

Property: [

Available 118n Keys fix THUserld'

l*_'None

Sltx0.ogin

\ Valu

Name
-

Search: |

VtxtPwd

Genera!
id

IblUserld

is Viable

true

renderer

iPhone: true, Android: true,

B __r

( text

Label\

Vjextil8nKey

Nong^/

E. _- Appearance
.vidgetAfignment

| ... J

'iVIDGET_AL]GN_CEUTER

conten^gnroent COtTH-'JT_.ALIGN_MIDDLE
wrapping
S

horizontal
vertical

WIDGET_TEXT_WORD_W

Expand (Appfcab (ht:tnje, vtrfalse)


true
faise

margin

Edkt

padding

Edit

Se (pixeis)

(448,26)

.Yidth

448

<\

Internationalization -API's

kony

18n APIs allow you to perform operations on the i18n Keys programmatically, rather than
from the IDE.
Use them to:

Get the current lcale of the application


Get the supported locales on the device
Get the current lcale of the device

Check if a specific resource bundle exists.


Check if a lcale is supported by the device

Get the localized string by specifying the 18n Key.


Delete a specific resource bundle.
Set the default lcale
Set the current lcale
Set the resource bundle.

Update the resource bundle.

108

Internationalization - 118n API's

kony

kony.iWn.getCurrentLocale

This API returns the lcale (string) that is currently being used by the application to
poplate the localized data.

This lcale might be different than the system lcale. The lcale follows the format
language_Country.
var lcale = kony.il8n.getCurrentLocale();

kony.H8n.getSupportedLocales:

This API provides you the ability to retrieve a list of all the supported locales of the
device.

It returns a object which contains with the key - value pairs


var list = kony.il8n.getSupportedLocales ()
Where list={{languag:"en", country:"US", name:"English
US"},{language:"en", country:"UK", name:"English UK"}}

Internationalization - 118n API's

kony

kony.H8n.getCurrentDeviceLocale:

This API provides you the ability to fetch the current lcale of the device

It returns an object with key - value pairs


var myLocaleDetails = kony.il8n.getCurrentDeviceLocale();

myLocaleDetails={language:"en", country:"US", name:"English


US"}

kony.i18n.sResourceBundlePresent

This API checks if a resource bundle exists for a given lcale or not

It returns a boolean value

var exists = kony.il8n.isResourceBundlePresent("en_US");

109

Internationalization - I18n API's

&.
kony

kony.H8n.isLocaleSupportedByDevice:

This API provides you the ability to view whether a lcale is supported by a device or
not.

It returns a boolean value

var isPresent= kony.il8n.isLocaleSupportedByDevice("en_US")

kony.H8n.getLocalizedString:

This API returns the localized string that corresponds to the specified i18n Key
var currentLocales = kony.il8n.getLocalizedString("1");

kony.H8n.deleteResourceBundle:

This API allows you to delete an existing resource bundle. If a resource bundle does
not exist, the API does not perform any operation.

It does not return any vales


kony.il8n.deleteResourceBundle("en_US");

"

Note:lf a lcale specific folder is empty , the application crashes on phone

Internationalization - 118n API's

2p

kony

kony.H8n.setDefaultLocaleAsync

This API allows you to set the specified lcale as the default lcale for the application
kony.il8n.setDefaultLocaleAsync(localeName, onSuccessCallback,
onFailureCalIback, info)

localename : Specifies the lcale that must be set as the default lcale of the
application.

onSuccessCallback: onsuccess callback is called by the platform after successfully


setting the specified lcale as default.
onSucessCallback(oldLocaleName, newLocaleName){
//code }

onFailureCalIback: onfailure callback will be called by the platform if the lcale is not
set successfully.
onFailureCalIback(errCode, errMsg){
//code }

r
110

Internationalization - 118n API's

kony

info (Optional):

A JavaScript object consisting of key value pairs


If info parameter is specified, it is passed to the callback function as a last
parameter. If the info parameter is not specified, the callback function receives the
info as nuil.

"info" is basically a user data where in the application developers will pass it to the
async API's and the platform returns this info object to the corresponding async
callback.

This parameter is helpful for developers to remember the context when the
methods are called in asynchronous fashion.

kony.H8n.setCurrentLocaleAsync:

This API allows you to set the specified lcale as the current lcale for the application.If
the lcale is not supported by the device junk characters will be displayed.
kony.il8n.setCurrentLocaleAsync(localeName, onSuccessCallback,
onFailureCalIback, info)

Description of the parameters is same as setDefaultLocaleAsync

Internationalization - 118n API's

kony

kony.H8n.setResourceBundle:

This API allows you to set the specified resource bundle for a given lcale

If the specified lcale has a resource bundle already set, it is overridden with the given
resource bundle.

You must set the resource bundle for a given lcale to have internationalization support
for that lcale.

If no resource bundle has been set previously, this API will crate a new resource
bundle.

kony.il8n.setResourceBundle(inputArray, lcale) where:

inputArray: Specifies the resource bundle that needs to be set for the given lcale
lcale: Specifies the lcale for which the resource bundle needs to be set

For example:
Kony.il8n.setResourceBundle({labell:"First Name",labe12:"Last
Name"},"en_US")

'

111

'

*4

Internationalization - I18n API's

kony

kony.iWn.updateResourceBundle:

This API allows you to append new key value pairs to the given resource bundle for a
specified lcale.

The key-value pairs you provide will be appended at the end of the resource bundle

If no resource bundle exists for the specified lcale, a new resource bundle is created.
updateResourceBundle( inputArray,

lcale) where:

inputArray-. Specifies the set of key value pairs that needs to added to the
resource bundle.

lcale: Specifies the lcale for which the resource bundle needs to be updated
with the given vales.

For example, to add the new key "Iabel3" with a value of "Middle Name" to the US
English bundle:
il8n.updateResourceBundle({labe13:"Middle Name"},

XA

Exercise - Internationalization

kony

Objective

Be able to build a localized application appiying the principies of Internationalization

Concepts

I18n for applications is supported by placing text and their associated keys in resource
bundles that are loaded into the application.

A resource bundle is a properties file that contains all the 118n Keys along with their
vales.
"

Procedure
SZZM

Ok, let's build a little localized

application

Setup 3 keys with at least


Germn, Spanish and
English locales set (right
click your application and

Configure Inlemationalization

il

Addnew lcale end configure key nd vales for each Lcale

Default Lcale: |en_US


fde_DE

hame

select Internationalization

112

Exercise - Internationalization (cont.)

XA

kony

Add 3 buttons to a form, leave the text as the default "Button" but set the 118N key to
one of the keys you've created above (the 3 buttons use all 3 keys)
In the application properties, configure the pre-appinit event to do the following (use the
snippet action or write a function):

Crate 3 local Javascript tables as resource bundles: one for Germn, one for
Spanish and one for English. For example:
var englishContent = {fname:"First Name",lname:"Last
Name",cont:"Continu"}

Note: you can make up or transate your text to crate your resource bundles for
the other languages
Check to see what lcale is currently running on the device
Based on the device lcale, load up the appropriate resource bundle. For example:
kony.il8n.setResourceBundle(englishContent,"en_US")

Now for the fun part - testing!

Use the Android emulator

In Settings, go to Lcale & Text and change the lcale to whatever you want

Exercise - Internationalization (cont'd)

kony

In Settings, go to Applications -> Manage Applications. Select your app - you can now
exit the app (Note: or put an exit button/menu item on your app to call
kony.application.exit()

Here are the results in 3 languages: English, Germn and Spanish:


inwnitjonal.ution Ixtttt*

initfnatiOfultiitionEiitfdM

Note: Since you didn't configure for all languages, setting the device to one of those languages
will cause the kony .il8n.getCurrentLocale( )method to return the default lcale
(set in App properties)

113

Custom Widget - Overview

kony

Custom Widgets are custom-built Ul elements which can

be used in an application to extend the capabilities of


KonyOne Studio.

.. Palette

jt Container Widgets

Kony Studio can import, manage, and use third-party

o Basic Widgets

widgets available from other libraries (such as Sencha or


Jquery etc) in Kony apps.

Advanced Widgets

Crate your own Custom Widgets by importing your

q iOS & Android UVUX

Windows Mobile 6 .

custom css and js files.

Custom Widgets can have properties (like standard


widgets) which can be set at design time to customize the
widgets behavior.

{J Mobile Web Advanced

tf Deprecated Widgets
{0 Custom Widgets

< customDatePkker
';' myTwitterUnk

Sample Custom Widgets

$*! dISlkle

"

114

XA

Custom Widget Creation Process

kony

Steps to crate Custom Widget

1. Import third party library (for e.g., Sencha , jQuery etc)


2. Crate Custom Widget JS File
3.

Import Custom Widget JS File (Optional)

4.

Intgrate Custom Widget

5. Custom Widget will be available in the palette

kony
c *

Import Third Party Library

You need to have the third-party JS library consisting of implemented functionalities for the
expected custom widget.
Steps to follow :

1.

Right click on Application (in Application view) and select Import

2.

Select Import Files...

0 Applications

- Navigator

i ^ SampleCustomWidgetApp
[Q forms (0)
Q| mobile (0)
\) tablet(0)

| desktop (0)

App Menu

Ser/ices...

Skin Defaults

.ntemationalzaton(18n)...

B>

Themes(Skins)...

Utilities

t\

Custom Librarles...

Intgrate Third Party

Custom Fcnts...

ti, modules (0)

f/ webjncdule (0)

Internationali:ation(18n)...

EL

. Jjj popups(0)
* templates(0)

resources (2)

-___ services (0)

(2

"ir

Import }

Custom Widgets...

Export

Import Files^-P

115

XA

Import Third Party Library - (cont.)

kony

Select the From Directory to identify the source directory where the thirdparty library files to be imported are located.
Provide the Into Folder location where the third-party library files should be
imported to.

The folder specification should be


<Workspace>/<App_Name>/resources/thirdpartywidgets

Filo system

LJ

Plp.lt -.pr <.fpldtr

Stiect * fclder to impcrt into.


S*mp teCu tt omVVid j O App ' fesource' th <rdpa rly-vidget

Ffomd-ttWj-. C'liim.H>03J tvnitpp.itnh

tj? mpleCurtom.Vidoet-pp

U091
J

Unchtte

medula
us

resources

build

de-iHop
rnebilerich client
mcb.letriindit.rit
t#bletri<hlient

C^^thtidpjrtyviidgeti
toMdM

ight2012 Kony Solutions. Inc. CONFIDENTIAL

Import Third Party Library - (cont.)


Click Finish

Refresh the application

kony

File system

EZ

Import tecutce from the local file system.

* [ Browse-,

From directory: C:\User5\KH203\0esli1cp\Sencha

cr- Sencha
J ,

SenchaLib

"

| Filter Types- j| Select All | Dese-ectAH |


Into folder

SampleCustomWidgetApp>'reo urces'thir dpartywidgets

Browse...

Options

Cver.'.ritt existingesources without tvaming


Crate complete folder structure
Advanced >> \

\_^

Ftnish

^y
Cancel

116

Import Third Party Library - (cont.)

kony

After the successful import, the Custom Widget library will be available
thirdpartywidgets folder as shown below.

under

* (f5 SampleCustomWidgetApp
IjT) forms (0)
;. 1J3 popups (0)
* templates (0)
.... modules (0)

^y webjmodule (0)
At

m resources (4)

build (0)

m common (0)

v desktop (0)
H mobilerichcient (2)

fjj mobilethinclient (0)


J tabletrichclient (0)
tabletthinclient (0)
i l___v thirdpartywidgets (2)

jB "iJHijetKiifijujffi)

\t L_r- SenchaLib (2) J


"~~ .

jliilIu Toch-deb g.js

{(_} sencha-touch.css

Crate Custom Widget JS File

kony

KonyOne defines an interface that must be implemented by all Custom Widgets. This
interface is referred to as a widget wrapper. The wrapper:

Enables KonyOne to initialize the widget when it is rendered in an application.

Notifies the Custom Widget when there is a change in its state

The change in state can be a change to one of the properties exposed by it or a


user driven event raised on the Custom Widget.
All such changes are notified to the Custom Widget via the modelChange
function.

The developer can make use of the modelChange call to make changes to the
Custom Widget state programmatically.

117

i.kony*

Crate Custom Widget JS File - (cont.)

The widget wrapper javascript interface requires these methods:


function initializeWidget (parentNode, widgetModel)

Use this function to initialize the widget before use


parentNode is a container where you place the Custom Widget. It is the
placeholder div that respects the layout of a Kony Widget.

The widgetModel parameter is a hashmap containing key-value pairs of the


widget's properties and corresponding vales.

function modelChange(widgetModel,
propertyValue)

propertyChanged,

Using the modelChange function any changes to the widget properties are
updated both in the Kony widget model and the widget itself.
The widgetModel is a hash map containing key-value pairs of the properties and
its corresponding vales.
propertyChanged is the key of the property being changed
propertyValue is the new value of the property

44

Crate Custom Widget JS File - (cont.)

kony

Custom Widget JS file can be created either in the application itself or outside the
application and can be imported.
Creating n Application: Switch to Navigator view and go to the widget wrapper folder in
the application as shown below.

^f__] Applications L. Navigator

le
4 \- SampleCustomWidgetApp

to bgimages
(5? customwidgets
i5 dialogs
to forms
jr:rc

modules

s to resources

to build
u common

Lir desktop
& 18n
. &

mobilerichclient

i>- mobilethinclient
-

ur- tabletrichclient
k._ tabletthinclient

4 ,_- thirdpartywidgets
,_ - SenchaLib

& widgetwrapperj

118

Crate Custom Widget JS File - (cont.)

kony

Right click on widgetwrapper folder and select New and then click on Other as shown
below.

O Applications *l Navigator '.-.

9j\ B^|

4} l3 SampleCustomWidgetApp
to bgimages
Lr customwidgets
dialogs

C_^_NewJ^>

to forms
jssrc

Golnto

to rnodules
d &

'

Open in New Window

Ccp-

Kony Application

i:,

Project...

resources

e- build

Example...

Otherl/)

Ctrl+N

common

to desktop

Delete

il8n

Move...

moblerichclient

_
Rename...

L3 mobilethinclient

tabletrichclient

^ Import...

tabletthinclient

^^

r- thirdpartywidgets
t_r Senchab

c<_r^widgetwrapptP^5
>

Refresh
VIIHX

Crate Custom Widget JS File - (cont.)

&+
kony

Expand General and select Folder and then click on Next as shown below.
Select a wiznrd
Crate a new folder resource

Wi:ards:

type filter text

& Class
G Interface

: JavaProject

j|f Java Project from Existing Ant Buildfile


: Plug-in Project

_ Foldei

'i_i Project
Untitled Text File

CVS
to Java

<Eack

119

Crate Custom Widget JS File - (cont.)

kon-*

Give some name to folder, lets say Folder name as DatePicker and the folder
specification should be
<Workspace>/<App_Name>/resources/thirdpartywicigets/widgetwrapper
nter or select the parent folder

SampteCustomWidgetApp/reiources/thirrJpartj-vvidgets/widgetvvapper

- tabletthinclient

;._ third partywJdgets


Senchab

^"widgetwrppj
servcl

templates
themes

w eb_.mo dule

( SampleDynamic Themes
UP SampleDynamicWirjgets

t~ ScrapeMeExercise

t_r ScraperAppExerc.se
-

P^
foldername:Vgat.eP'Ckcr^y
, Advenced >> 1

(2)

<Bc't

(J

Fimsh

J^|

Canee

i^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^B

Crate Custom Widget JS File - (cont.)

kony

DatePicker folder will be available under widgetwrapper as shown below.


GD Applications X...Navigator -'!

1=1

1B % |
s) \$ SampleCustomWidgetApp
i_r- bgimages
i^- customwidgets
lt dialogs
&

forms

& jssrc
& modules
L^' resources
build

common
desktop

i- 13n
mobilerichclient

mobilethnclient

i3 tabletrichclient
L_r tabletthinclient

4 l3 thirdpartywidgets
i_r- SenchaLib

j 3- widcietvvrapp-r

^DatePicker )

120

Crate Custom Widget JS File - (cont.)

kony

Right click on DatePicker folder and select New and then click on Other as shown below.

[3 Applications 'C. Navigator ':'.

*\B%\9
4 Iczi SampleCustomWidgetApp
bgimages
i customwidgets
l3 dialogs
forms

>- jssrc
-

<^"~ New ~^)

modules

!3 Kony Application

Golnto

4 13 resources

Project-

Open m New Window

L- build

BPcommon

B desktop

Example...

c0py

<^QtherS^>

p.n.

CtrkN

3 ilSn

& mobilerichclient

* Detete

i- mobilethinclient

Move...

Qfr tabletrichclient

Rename...

tabletthinclient

d fe thirdpartywidgets ii Import...
i_r- SenchaLib
^ Export...
4 [^w]rlg*hn_c^

C2^DatePkk^

Refrh

3 - services
Validar.

- tmplate!

Crate Custom Widget JS File - (cont.)

kony

Expand General and select File and then click on Next as shown below.
Select a wizard
Crate a new file resource

Wizards:

type filter text

Class
<> Interface

J_- Java Project


fc JavaProjectfrom Existing AntBuildfie
i Plug-in Project
5 & GenerjjL1

C Fifi ~^
__ Folder

l_j Project
Untitled Text File

e-cvs
1 L>. Java

<-~

LJ
'

UM

~">
| )

Cancel

'"

121

"

Crate Custom Widget JS File - (cont.)

kony

Give some name to file, lets say file name as tp-sencha-calendar.js and the file
specification should be
<Workspace>/<App_Name>/resources/thirdpartywidgets/widgetwrapper/DatePicker
nter o select the parent folder.
Samp eCustomWidgetApp/reiources/thirdparty,i/tdgets/widgetwrappe

/DatePicker

build
, _;- common

.__

desktop
(13 n
mobilerichclient

mobilethinclient
tabletrichclient

tabletthinclient

| / thirdpartyv.idgets
SenchaLib

witfjienvrflpp_er

(^DatePickerN
tirvn->

File nar

ne.Qp-sencha-calendar.js }

[ .dvanced >> |

f
(J

L_Li_ik_J

Fmish

) 1 c-"

Crate Custom Widget JS File - (cont.)

kony

tp-sencha-calendar.js file will be available under Datepicker as shown below.

Q Applications ..Navigator *3

1 m%\
4 \z? SampleCustomWidgetApp
13 bgimages
i- customwidgets

Q| dialogs
J3- foims
mi jssrc
lt- modules
4 L3 resources

mt build
L_f- common

desktop
l-r 18n
iz? mobilerichclient
^

mobilethinclient
tabletrichclient

i>. tabletthinclient

4 3 thirdpartywidgets
mt SenchaLib
4 m9 widgetwrapper
4 ,___.- DatePicker

C^^tp-sencha- :alendarjT^5
S& services

122

Crate Custom Widget JS File - (cont.)

kony

Open tp-sencha-calendar.js and implement the sample code


datepicker = {
datepicker: nuil,
/**

widgetModel : id, containerWeight,margins, paddings,


contentAlignment

*/

initializeWidget : function(parentNode, widgetModel)


{

var calTextbox = '<input type="text" id="'+widgetModel['id']4


style="border:lpx solid #444444; width:100%;">';
parentNode. innerHTML = calTextbox;
widgetModelJ"date"] = nuil;

var calTextbox = document.getElementByld(widgetModel['id']);

if(datepicker.datepicker) {
datepicker.datepicker = {};
}

datepicker.datePicker[widgetModel['id']] = new
Ext.DatePicker({useTitles:true>);

Crate Custom Widget JS File - (cont.)

kony

var senchaDatePicker = datepicker.datepicker[widgetModel['id']];

calTextbox.onfocus = function(e) { this.blur();


senchaDatePicker.show();
};

senchaDatePicker .on ('change ', function(me, date)


var dt

= date.getDate();

dt = (dt<10)

? '0'+dt : dt;

var mth = date.getMonth() + 1; mth = (mth<10) ? '0'+mth : mth;

var viewDateStr = dt + '/' + mth + '/' + date.getFullYear();


datepicker.modelChange(widgetModel,

"date", viewDateStr);

});
).
modelChange : function(widgetModel, propertyChanged, propertyValue)
{

if (propertyChanged === "date")


{

widgetModel["date"] = propertyValue;

var calTextbox = document.getElementById(widgetModel['id']);


var dateArr = propertyValue.split('/');
var dt = parseInt(dateArr(0],

10);

dt = (dt<10) ? 'O'+dt : dt;

123
"

Crate Custom Widget JS File - (cont.)

kony

var mth = parselnt(dateArr[1], 10); mth = (mth<10) ? '0'+mth : mth;


var yr = parselnt (dateArr [2 ], 10);

var viewDateStr = dt + '/' + mth + '/' + yr;


calTextbox.value = viewDateStr;

datepicker.datepicker[widgetModel['id']].setvalue(new Date(yr, mth-

1, dt),

faise);

AA

Import Custom Widget JS File (Optional)

kony

Ifthe JS file was created outside of Kony Studio, we will need to import it to the application
in the same way we did for a third party except Into Folder location should be
<Workspace>/<App_Name>/resources/thlrdpartywidgets/widgetwrapper

{3Applications V.

C Navigator

"^ 13 \

'4Ji
* f_js SampleCustomWidgetApp
a |3 forms (0)
l mobile(0)
J tablet (0)
f desktop (0)
fjj popups (0)
*_' templates (0)

App Menu

Internationalization(il8n)

Skin Defaults

j^

Services

Internationalization(18n)...

:.

Themes(Skins)...

Utilities

Intgrate Third Party

ai. modules (0)

(y web_module (0)
: resources (2)
-*, services (0)

^5

Import^/

1:

Export

i.
f

Custom Librarles...
Custom Fonts...

Custom Widgets...

i Cjmport FileTT>

124
-

Import Custom Widget JS File (Optional) - (cojqJ^kC


After the successful import, Custom Widget JS file would be available under
thirdpartywidgets/widgetwrapper as shown below.

.* CQ SampleCustomWidgetApp
10 forms (0)
Eny popups(0)
templates (0)
i modules (0)

{y web_module (0)
4) -m resources (5)

":; build (0)


a common (0)

v desktop (0)
| mobilerichclient (2)

OB mobilethinclient (0)
J tabletrichclient (0)
4 tabletthinclient (0)
s (3- thirdpartywidgets (3)
d & wjdflfifawwww* ni
-'jLr DatePicker (1)

tp-sencha-calendar.js^
Lr-^eTJiuLiL (3J-

Intgrate Custom Widget

kony

Next step is to intgrate the Custom Widget library in to the application


Steps to follow :

1. Right click the application name (in Application view) and select Intgrate Third Party.
2.

Select Manage Custom Widgets

Q Applications

- Navig

J^ SampleCustomWidgetApp
IQ forms (1)
a tQ mobile(1)
frmHome

-J tablet (0)

v desktop(0)
^J popups (0)
* templates(0)

Jetty Web Server


App Menu
Skm Defaults
lntemation_li.3tiorviJ.Sn l.

Utilities

_ modules (0)

(.y web_module (0)


s

resources (3)

-__. services (0)

Intgrate Third Party

y Import

'ffl Manage Custom Librares...


jT ManageCustom Fonts...

<3nageCustom WidgetsTT^

125
'

4'

Intgrate Custom Widget - (cont.)

kony

Manage Custom Widget Librahes dialog appears

Click on New...

Provide the Custom Widget library name i.e SenchaLib and press OK

Manage Custom Widqet Librarles

I.

I hit potje Hoia lo crtotr u-.n librify. Ihrt libr*ty ttn br Hrttxted for cuitcm widget.

Stietl PliHo-m

SPA

Im"m

g Add New Library

Please enter the name

of library

SenchaLib

CL

o>=

U>

Cancel

r
fm>ih

Cmcd

Intgrate Custom Widget - (cont.)

kony

Custom Widget library files would be displayed in Manage Custom Widget Librahes dialog.

Click on Next

Click on [*] icn

Manage Custom Widgets


Uer cn add.remove and edit custom widgets.

TM F*S*"c*) to t'*l* int<Ubtfy.TtwM

SdcitPUjtform SPA

Widget Library

Mnnoqn Custom Widgrt lbranos

7Sprt,vii.je!-. SenchiL*nthi-lejuih-itibuji
1 1h-u^rt,'Alli^p,,5<KlMl*,vt34^Kh*-uch.CM

Emish

Cincel

126

XA

Intgrate Custom Widget - (cont.)

kony

Add Custom Widget dialog box appears

Provide the name of the object defined in Custom Widget JS file as shown below.

Select the platform for deployment

Select the library i.e SenchaLib and select only required files from the library (in order).

Select Custom Widget JS file

by clicking on lj__j

VA Piofwrt)

WuB Prpt,

PiPpTrt-,1u<na

Vjh* Type

DttjuHV,

<D

',i tp-sencha-calendar.js 3
ftaropiflrnOs ! -^*-^
datePicker:

T-

......

'.-

nuil,
Mm Ha spcahc te CuOwn wigrt

/*
wicic^r^^i:.:

initializeWidget

:_.:. ......

function

l~SI'

Intgrate Custom Widget - (cont.)

44
kony

Add the Custom widget JS file and click OK


Sdect an item to open (? = any character, * = any string):

Matching item;:

El tp-sencha-calendar.js

L_r SampleCustomWidgetApp/resources/thirdpartywidgets/widgetwrapper/DatePicker

i^~jT

127

Intgrate Custom Widget - (cont.)


-

kony

In the SPA Property and Default Property tabs we can crate properties that can be set
by a developer at design time in Kony Studio. The default value will be used if no other
value is provided by the developer.

In the example below, date is the custom property for the Custom Widget.

Name:

ibatepicker

Platform:

SPA

SPAProperty

Seect Library; goutam

Default Property

Property Name

Value Type

date

String

SPA

v j thirdpartywidgetsVc
7 <} third partywidgetsXc

Selected Files

{gthirdpartywidgets\gc
;.J thrdpartywdgets\gc

'

Intgrate Custom Widget - (cont)

kony

Finally, conclude the Integration task by clicking on Finish


Manage Custom Widgets
Usercan add,remove and edit custom widgets.

Widget Name

Widget Library

datepicker

SenchaLib

128

XA

Custom Widget Listed in the Palette

kony

The added Custom Widget can now further be used in the current application, as a new Ul
element by the developer to implement fore-sighted functionality of the widget in the
application.
r frmHome

Propertie j

v home .

~J CW.dget ( i"; ornu

*Cmobile % home.kl cutoml4067 3055493

-^ CWidget Serv

Property:

[O P '

Nme

VahM

<y>Advanced Wi_

Adv ert iwnt m t

Sue (piwb)

(448,24)

v^idlh

448

he<ght

24

Siie(S)

a00.5)

height

HHM

Considerations

kony

JS based Custom Widgets are only usable in SPA & Desktop Web channel.
A Custom Widget cannot be used as a container widget such as HBox, VBox, etc.

The

widget

"id" properly

should

be

unique,

so

it

is

recommended

to

use

widgetModel [ ' id' ] instead of hardcoding this value.

modelChange function must be present in the Custom Widget JS file (but can be empty).
The value of a custom widget property cannot be a function. Invoking functions based on
the Custom Widget events can only be done through code.
Quick preview does not work for Custom Widgets

The render property for a Custom Widget lists all channels, but only SPA and Desktop Web
are applicable for Custom Widgets.

129

r
r

kkony.v-

Exercise - Custom Widget


Objectives:

Crate a form using the Double Slider jQuery widget as shown below

Crate two labels and update the vales whenever the user adjusts the Double Slider
Widget.

Crate two buttons with text "Disable Slider" and "Enable Slider" and configure them to
enable or disable the slider.

SO

S500

Mnimum Price Selected :2

Double Slider Custom Widget


Two labels

Mximum Price Selected :497

Two Buttons

niy Solutions, Inc. CONFIDEMTIAL

130

Exercise - Custom Widget (cont.)

XA

kony

Procedure:

Crate a new Kony Application with the name DoubleSlide

Import jQuery Library into the application

Right click on the application name and select Import > Import Files...
j *t- Import

_**,'

Export

'..

Debug A:

C,

Validate
Team

Compare With

lnternationalizaton(18n)...
Services...

Themes(Skins)...
Custom Libraries...

Custom Fonts...

CustomWidgets...

Import Files...

Lcate the Jquerybrary folder (provided by your instructor) and select it in the
"From Directory" field. Set "Into folder" to
DoubleSlider/resources/thirdpartywidgets and click Finish.

Fromdirectory: C:\Users\KH203\DesWopVlqueryLibrary
J - JqueryLibrary

j Fita Types... | Select All [j DeselectAII j


Into folder

DoubleSlider/reSources/thirdpartywidgetS

Exercise - Custom Widget (cont.)

kony

Go to thirdpartywidgets present under resources and make sure that you have jQuery
folder in it as shown below.

_. resources (417)

II build (0)
3 common (0)

* desktop (0)
l mobilerichclient (2)

{"fj} mobilethinclient (0)


^ tabletrichclient(0)
O tabletthinclient 0)
d cr- thirdpartywidgets (415)
i_r widgetwrapper (0)
Q) Jquery (415)

Crate a folder "CustomJsFiles" in your machine and place an empty javascript file
with
the
name
DoubleSlide.js
in
it.
Import
DoubleSlide.js
into
thirdpartywidgets/widgetwrapper as shown below.
Fromdirectory; C:\Users\KH203\Desktop\CustomJSFiles
J|Gj} CustomJSFiles

FilterTypes...
Into tolden

[2 B DoubleSlide.js

Select A

DoubleSlide/resources/thirdpartywidgets'v/idgerwrapper

131

Exercise - Custom Widget (cont.)

kony

Crate a dlSlide object in DoubleSlide.js and implement the following methods i.e
initializeWidget, modelChange , disableSlider and enableSlider in it as shown below.
dlSlide = {
initializeWidget : function(parentNode, widgetModel)

{
var

slide='<div class="demo">'+

1<p>'

'<label for="amount">Price range:</label>' +


'</p>'

'<div id="'+widgetModel['id']+'"></div>' +
</div>'

parentNode. innerHTML = slide;

priceValues=[0,500] ;
~

$( '#'+widgetModel[ 'id' ]+' ').slider({


range:

true,

min:

0,

max:

500,

vales:

[ 0, 500

],

Exercise - Custom Widget (cont.)

>%
kony

slide: function( event, ui ) {


var priceProperties=[ "MinimumValue", "MaximumValue" ]

if(priceValues[0]!=ui.vales[0]){
consol.log("Minimum value changed");
priceValues[0]=ui.vales[0]

dlSlide.modelChange(widgetModel, priceProperties[0],
ui.values[0] )
}
else{

consol.log("Mximum value changed");


priceValues[l]=ui.vales[1]

dlSlide. modelChange(widgetModel, priceProperties[1]


ui.vales[1])
}

});

},

modelChange : function(widgetModel, propertyChanged, propertyValue)


{

consol.log("In Model Change");

132

XA

Exercise - Custom Widget (cont.)


consol.log("propertyChanged
consol.log("propertyValue

-i*

kony

->" + propertyChanged);
->" + propertyValue);

setKnyLabelsMinMax(propertyChanged,propertyValue)
),

disableSlider : function(sliderlD){
consol.log("CstWdgtDbSlideFn ID is " + sliderID);

$(

r#'+sliderID+''

).slider("disable");

},

enableSlider : function(sliderID){
consol.log("CstWdgtDbSlideFn ID is

$( '#'+sliderID+''

" + sliderID);

).slider("enable");

Exercise - Custom Widget (cont.)

kony

Crate the Custom Widget with the name dlSlide


Right click on the application and navigate to Manage Custom Widgets and
click on it as shown below.
\ Manage Custom Librarles...
f Manage Custom Fonts...

Intgrate Third Party

Ja Import

<: ':.

Cj?

Export

Manage Custom Widgets...

Click on New and give the library name as jQuery and click on OK as shown
below.
VpKttMcm

SPA
..

jghUHn.l.tMi}

1 Pkrtitntn*mfif l*i*r,.

yt

LVX*

Click on Next

133

r
r

Exercise - Custom Widget (cont.)

kony

Click on \j icn as shown below

Widget Library

Give the name as dlSlide, platform as SPA and library as jQuery . Select the required
js files from the library and add DoubleSlide.js in "Select files specific to Custom

Widget" and click on OK and then Flnish.


SrAfeop-rt)

Dri-uiPiopwr,

Prepw1yh>r>

Select only those files


from the library that are
required for the double
slider widget

Vpfc-iT.p.

Drf.UPV.k-,

iipip.dpprt/H.a$tf' ....;."'.:

"

Exercise - Custom Widget (cont.)

kony

Crate a form with the name frmHome and add Custom Widget dlSlide, label and
buttons.

Givethe ID as "customDoubleSlider" to Custom Widget dlSlide


Give the ID as IbIMin to first label and IbIMax to the second label. Give the text
"Minimum Price Selected : 0" to IbIMin and "Mximum Price Selected : 500" to
IbIMax.

Crate two buttons i.e "Disable Slider" and "Enable Slider"


. Palette
c," basic logers
~

Button

W Advanced Wi...
Mnimum Pnce Selected i (

*
-

_5,AdvertHetnent
Windows Mo...

~^-

, Signatur eCapt_

Mximum Price 5lected ; 5-30

Q 05&Androi... o
:* 2D/3D Chwt

fjtMobile Web A... co


0

Video

9 Deptecated W... O
Image
1

;...:>-.,,..

\j Cuslcm Widg... i
dlSlide

134

Exercise - Custom Widget (cont.)

kony

Crate sliding.js under modules and implement the below functions and assign
disableSlide function to DisableSlider button and enableSlide function to Enable Slider
button.

function setKnyLabelsMinMax(propertyChanged,propertyValue){
if(propertyChanged=="MinimumValue"){
frmHome.IbIMin.text="Minimum Price Selected :" tpropertyValue;

}else{
frmHome.IbIMax.text="Mximum Price Selected :" +propertyValue;
>
}

function disableSlide(){
dlSlide.disableSlider("customDoubleSlider")
}

function enableSlide(){
dlSlide.enableSlider("customDoubleSlider")
>

Build and run the application

135

Você também pode gostar