Professional Documents
Culture Documents
Codename One Developers Guide
Codename One Developers Guide
Developers Guide
Authors
Shai Almog, Chen Fishbein, Eric Coolman
Table of contents
Table of contents Introduction History Limitations & Ca abilities Light!eight "I Installation Installing Codename #ne In $et%eans Installing Codename #ne In Ecli se &"I %uilder Hello 'orld (anual Hello 'orld %asics) Themes, Styles, Com onents & Layouts 'hat Is A Theme, 'hat Is A Style & 'hat Is a Com onent* Creating A $ati+e Theme Com onent,Container Heirarchy Layout (anagers Flo! Layout %o- Layout %order Layout &rid Layout Table Layout Layered Layout "nderstanding .referred Si/e Layout 0eflo! Layout Animations Theme %asics Ad+anced Theming "nderstanding Codename #ne Themes 'or1ing 'ith "II2 Colors %ac1grounds Fonts %orders Inheritance Theme Constants Ho! 2oes A Theme 'or1 'or1ing 'ith The &"I %uilder %asic Conce ts The Com onents #f Codename #ne
Codename One 2012. All rights Reserved. http: !!!."odenameone."om 3
Container Form 2ialog Label %utton Chec1%o-,0adio %utton (ulti4%utton Te-tField,Te-tArea Toggle %utton List, ContainerList, 0enderers & (odels "nderstanding (5C List Cell 0enderer &eneric List Cell 0enderer The List (odel Slider Ads Table Tree Share %utton .rogress Tabs (edia.layer 'eb%ro!ser Embedded Container The (a Com onent E+ents Animations & Transitions The E2T 4 E+ent 2is atch Thread In+o1e And %loc1 &ra hics, 2ra!ing & Images %asics 4 'here & Ho! 2o I 2ra! (anually* Images &lass .ane Layout (anagers %order Layout Flo! Layout &rid Layout %o- Layout Layered Layout Table Layout %uilding 6our #!n Layout (anager File System, Storage, $et!or1 & .arsing E-ternali/able #b7ects
Codename One 2012. All rights Reserved. http: !!!."odenameone."om 8
Storage +s9 File System Storage File System S:L $et!or1 (anager & Connection 0e;uest $et!or1 Ser+ices "I %indings & "tilities Logging .arsing) <S#$, =(L & CS5 (iscellaneous Features Analytics Integration .erformance & Si/e 0educing 0esource File Si/e Ad+anced To ics,"nder The Hood Sending Arguments To The %uild Ser+er The Architecture #f The &"I %uilder $ati+e Interfaces 2rag & 2ro .hysics 4 The (otion Class %i2i,0TL Language Su ort Signing, Certificates & .ro+isioning i#S >i.hone,i.ad? Android 0I(,%lac1%erry <3(E A endi-) 'or1ing 'ith i#S .ro+isioning .rofile & Certificates .ush $otifications
Introduction
Codename #ne is a set of tools for mobile a lication de+elo ment that deri+e a great deal of its architecture from <a+a9 It stands both as the name of the startu that created the set of tools and as a refi- to the distinct tools that ma1e u the Codename #ne roduct9 The goal of the Codename #ne ro7ect is to ta1e the com le- and fragmented tas1 of mobile de+ice rogramming and unify it under a single set of tools, A.Is and ser+ices to create a more manageable a roach to mobile a lication de+elo ment !ithout sacrificing de+elo ment o!er,control9
History
Codename #ne !as started by Chen Fishbein & Shai Almog !ho authored the # en Source L'"IT1 ro7ect at Sun (icrosystems starting at 3AAB9 The L'"IT ro7ect aimed at sol+ing the fragmentation !ithin <3(E,%lac1berry de+ices by targeting a higher standard of user interface than the common baseline at the time9 L'"IT recei+ed critical acclaim and traction !ithin multi le industries but !as limited by the declining feature hone mar1et9 In 3A13 the Codename #ne ro7ect has ta1en many of the basic conce ts de+elo ed !ithin the L'"IT ro7ect and ada ted them to the smart hone !orld !hich is e- eriencing similar issues to the de+ice fragmentation of the old <3(E hones9
See htt ),,l!uit9blogs ot9com, htt ),,l!uit97a+a9net, Codename One 2012. All rights Reserved. http: !!!."odenameone."om D
Codename #ne unifies the ieces illustrated abo+e allo!ing de+elo ers to use them as a single coherent roduct9 'hen building the final nati+e a lication the build ser+er roduces the actual nati+e a lication remo+ing the need for a dedicated machine,installation9
Lightweight UI
The biggest differentiation for Codename #ne is the light!eight architecture !hich allo!s for a great deal of the ca abilities !ithin Codename #ne9 A Light!eight com onent is a com onent !hich is !ritten entirely in <a+a, it dra!s its o!n interface and handles its o!n e+ents,states9
This has huge ortability ad+antages since the same code e-ecutes on all latforms, but it carries many additional ad+antages9 The com onents are infinitely customi/able 7ust by using standard inheritance and o+erriding aint,e+ent handling9 Theming and the &"I builder allo! for li+e re+ie! and accurate re roduction across latforms since the same code e-ecutes e+ery!here9
Installation
Installing Codename One In NetBeans
For the ur ose of this document !e !ill focus mostly on the $et%eans I2E for de+elo ment, ho!e+er most o erations are almost identical in the Ecli se I2E as !ell9 For instructions s ecific for Ecli se lease go to the follo!ing section9 These instructions assume you ha+e do!nloaded $et%eans B9-,installed and launchedit9 Select the Tools4G.lugins menu o tion & select the Settings tab
For the name enter) Codename #ne For the "0L enter) htt s),,codenameone9googlecode9com,s+n,trun1,Codename#ne,re o,netbeans,u dates9-ml In The A+ailable .lugins Tab Clic1 H0eload CatalogH Then Chec1 The Codename#ne .lugin
After that clic1 the install button belo!9 Follo! the 'i/ard instructions to install the lugin
6ou !ill be informed that the lugin is unsigned !hich is indeed true, you 7ust continue any!ay9
Clic1 the Add button on the right side & fill out the entries
Enter Codename #ne for the name &htt s),,codenameone9googlecode9com,s+n,trun1,Codename#ne,re o,ecli se,site9-ml for the location9 Select the entries & follo! the !i/ard to install
It is im ortant to use ro er ac1age names for the ro7ect since latforms such as i#S & Android rely on these names for future u dates9 They are thus ainful to changeK The con+ention is the common <a+a con+ention of re+erse domain names >e9g9 com9codenameone for the o!ner of codenameone9com etc9?9 %y default a &"I builder ro7ect is created, !e !ill maintain this default for the ur ose of this hello !orld9
Since this is a &"I builder ro7ect you can o en the Codename #ne 2esigner !ith the content of the theme9res file by double clic1ing the file9 F6I) If you choose to rename this file in the future it is im ortant to u date the resource file name in the ro7ect ro erties settings9
'ithin the Codename #ne 2esigner !e can see se+eral categories the most interesting of !hich are theme & &"I9 'e !ill start by o ening the theme section and clic1ing the entry there9 The default Codename #ne theme, deri+es from the latform nati+e theme9 'e can easily change the Hbase themeH in the re+ie! to see ho! the theme !ill act in different de+ices by clic1ing the nati+e theme o tion in the a lication menu as such9
To edit the "I for the a lication !e need to select the &"I section and clic1 L&"I 1M !ithin that section9 'e are then faced !ith a drag and dro interface to mani ulate the &"I of the a lication !e sa! !ithin the theme re+ie!9 All changes made here are reflected instantly to the theme re+ie!9
The &"I builder allo!s us to bind e+ents, !e !ill drag a ne! button into the &"I and use this functionality to select the button from the &"I and then add an action e+ent to a button listener to a button99
Clic1ing the action e+ent button creates a ne! method !ithin the I2E !hich !e can can use to bind functionality to the button9 'ithin the code !e sho! a dialog by adding the code) 2ialog9sho!>HHelloH, HHi ThereH, H#NH, null?O
If !e ins ect the Codename #ne ro7ect to some degree !e !ill notice that it is retty close to a standard <a+a ro7ect hence it can be modified,used in +ery similar !ays9 6ou can use the debugger and most refactoring functionality as usual9 Noti e that you should not change the class ath settings for the ro7ect since library su ort is a more com le- issue than 7ust modifying the class athK Furthermore, if you change ac1age,class names for some of the core classes you !ill need to u date the ro7ect settings accordingly9
In order to get a nati+e a lication for the de+ices you need to send a build to the build ser+er9 %efore you get started you !ill robably need to read the signing section of this guide in order to roduce an actual !or1ing a lication9 0ight clic1 the ro7ect and select the de+ice ty e for !hich you !ish to build9 If you ha+enEt registered in the build ser+er 7ust +isit htt ),,!!!9codenameone9com, and signu for free to get an account thereK
'ithin the build ser+er at htt ),,!!!9codenameone9com, you can follo! the status of your current build9
In the build ser+er !e can follo! the rogress of the build and the results for the current build9 'e can email a lin1 to the de loyment files, do!nload them or use a :0 reader to install them to the hone9 The Codename #ne LI5EK a lication allo!s follo!ing the status and installing a lications directly from the build ser+er9
It is im ortant to use ro er ac1age names for the ro7ect since latforms such as i#S & Android rely on these names for future u dates9 They are thus ainful to changeK The con+ention is the common <a+a con+ention of re+erse domain names >e9g9 com9codenameone for the o!ner of codenameone9com etc9?9 (a1e sure to select the Hello 'orld ro7ect and $#T the &"I %uilder ro7ectK 'ithin your ro7ect main class you !ill see a start method that contains the code) Form f P new Form'HHello 'orldH(O to add a button to the form that !ill sho! a dialog add the follo!ing) %utton d P new %utton'LSho! 2ialogM(O f9addCom onent'd(O d9addActionListener'new ActionListener'( ) p"bli *oid Action.erformed'ActionE+ent e+( ) 2ialog9sho!'HHelloH, HHi ThereH, H#NH, n"ll(O
Codename One 2012. All rights Reserved. http: !!!."odenameone."om 1@
+ +(O This !ill sho! a dialog !hen the user clic1s the button9 6ou can use the lay button in the I2E to run the a lication9
6ou can easily create a theme !ith any loo1 you desire or you can HinheritH the latform nati+e theme and start from that oint9 'hen adding a ne! theme you are gi+en the o tion9 Any theme can be configured to deri+e a nati+e theme
Codename One 2012. All rights Reserved. http: !!!."odenameone."om 1F
Codename #ne uses a theme constant called Hinclude$ati+e%oolH, !hen that constant is set to true Codename #ne starts by loading the nati+e theme first and then a lying all the theme settings9 This effecti+ely means your theme Hderi+esH the style of the nati+e theme first, similar to the cascading effect of CSS9 %y a+oiding this flag you can create themes that loo1 E=ACTL6 the same on all latforms9 6ou can simulate different #S latforms by using the nati+e theme menu o tion
2e+elo ers can ic1 the latform of their li1ing and see ho! the theme !ill a articular latform by selecting it and ha+ing the re+ie! u date on the fly9 6ou can easily create dee customi/ations that s an across all themes
ear in that
In this case !e 7ust customi/ed the "II2 of a label and created a style for the ne! "II29 'hen deri+ing a nati+e theme its im ortant to chec1 the +arious latform o tions to ma1e sure that
Codename One 2012. All rights Reserved. http: !!!."odenameone."om 1B
basic assum tions arenQt +iolated9 E9g9 labels might be trans arent on one latform but o a;ue on others9 #r labels might loo1 good in a dialog in Android but loo1 horrible in an i#S dialog >hint) use the 2ialog%ody "II2 for te-t content !ithin a dialog?9 Codename #ne allo!s you to o+erride a resource for a s ecific latform
A common case !e run into !hen ada ting for latform s ecific loo1s is that a s ecific resource should be different to match the latform con+entions9 The #+erride feature allo!s us to define resources that are s ecific to a gi+en latform combination9 #+erride resources ta1e recedence o+er embedded resources thus allo!ing us to change the loo1 or e+en beha+ior >!hen o+erriding a &"I builder element? for a s ecific latform,#S9 To o+erride select the latform !here o+erriding is a licable
Then clic1 the green chec1bo- to define that this resource is s ecific to this latform9 All resources added at this oint !ill only a ly to the gi+en latform9 If you change your mind and are no longer interested in a articular o+erride 7ust delete it in the o+erride mode and it !ill no longer be o+erridden9
This is easily done by selecting the H999H button9 'e can easily do the same in the &"I builder although this is a dangerous road to start follo!ing since it might end u !ith a great deal of fragmentation9
Component2Container Hierar hy
The com onent class is the basis of all "I !idgets in Codename #ne, to arrange multi le com onents together !e use the Container class !hich itself LIS AM Com onent subclass9 The Container is a Com onent that contains Com onents effecti+ely allo!ing us to nest Containers infinitely to build any ty e of +isual hierarchy !e !ant by nesting Containers9
Layo"t &anagers
Layout managers are installed on the Container class and effecti+ely osition the Com onents !ithin the gi+en container9 The Layout(anager class is abstract and allo!s users to create their o!n layout managers, ho!e+er Codename #ne shi s !ith multi le layout managers allo!ing for the creation of many layout ty es9 The layout managers are designed to allo! de+elo ers to build user interfaces that seamlessly ada t to all resolutions and thus they donEt state the com onent si/e, osition but rather the intended layout beha+ior9 To install a layout manager one does something li1e this) Container c P new Container'new %o-Layout'%o-Layout9=RA=IS((O c9addCom onent'new %utton'H1H((O c9addCom onent'new %utton'H3H((O c9addCom onent'new %utton'H8H((O This !ould roduce 8 buttons one ne-t to the other hori/ontally9 There are t!o ma7or ty es of layout managers) Constraint based & regular9 The regular layout managers li1e the bo- layout are 7ust installed on the container and Ldo their 7obM9 The constraint based layout managers associate a +alue !ith a Com onent sometimes e- licitly and sometimes im licitly9 Codename #ne shi s !ith 8 such layouts %orderLayout, TableLayout & &rou Layout9 A constraint layout can,must acce t a +alue !hen adding the com onent to indicate its osition e9g9) Container c P new Container'new %orderLayout'((O c9addCom onent'%orderLayout9CE$TE0, new %utton'H1H((O c9addCom onent'%orderLayout9$#0TH, new %utton'H3H((O c9addCom onent'%orderLayout9S#"TH, new %utton'H8H((O
This !ill stretch button 1 across the center of the container and buttons 348 !ill be stretched hori/ontally at the to and bottom of the container9 $otice that the order to adding doesnEt mean much once !e ha+e a constraint in+ol+ed999
3low Layo"t
Flo! layout can be used to 7ust let the com onents Lflo!M hori/ontally and brea1 a line !hen reaching the end of the com onent9 It is the default layout manager for Codename #ne but because it is so fle-ible it could be roblematic since it can cause the referred si/e of the Container to ro+ide false information triggering endless layout reflo!s >see belo!?9 Flo! layout can be aligned to the left >by default? center or to the right9 Com onents !ithin the flo! layout get their natural referred si/e by default and are not stretched in any a-is9 The layout manager also su orts modifying the hori/ontal alignment of the flo! layout in cases !here the container gro!s +ertically9
#inal Container layouts P new Container'(O #inal %utton borderLayout P new %utton'H%orderH(O #inal %utton bo-6Layout P new %utton'H%o- 6H(O #inal %utton bo-=Layout P new %utton'H%o- =H(O #inal %utton flo!Layout P new %utton'HFlo!H(O #inal %utton flo!CenterLayout P new %utton'HFlo! CenterH(O #inal %utton gridLayout P new %utton'H&ridH(O #inal %utton tableLayout P new %utton'HTableH(O layouts9setLayout'new Flo!Layout'Com onent9CE$TE0((O layouts9addCom onent'borderLayout(O layouts9addCom onent'bo-6Layout(O layouts9addCom onent'bo-=Layout(O layouts9addCom onent'flo!Layout(O layouts9addCom onent'flo!CenterLayout(O layouts9addCom onent'gridLayout(O layouts9addCom onent'tableLayout(O
Bo4 Layo"t
Codename One 2012. All rights Reserved. http: !!!."odenameone."om 31
%o- layout allo!s lacing com onents in a hori/ontal or a +ertical line that doesnEt brea1 the line9 Com onents are stretched along the o osite a-is, e9g9 = a-is bo- !ill flo! com onents hori/ontally and stretch them +ertically9
9 %o- layout acce ts the a-is in its constructor, the a-is can be either %o-Layout9=RA=IS or %o-Layout96RA=IS9
Border Layo"t
%order layout is ;uite uni;ue, its a constraint based layout that can lace u to D com onents in one of the D ositions) $orth, South, East, 'est or Center9 The layout al!ays stretches the $orth,South com onents on the = a-is to com letely fill the container and the East,'est com onents on the 6 a-is9 The center com onent is stretched to fill the remaining area by default9 Ho!e+er, the border layout has a flag to mani ulate the beha+ior of the center com onent allo!ing it to be laced in the absolute center !ithout stretching9
!rid Layo"t
The &rid Layout acce ts a redefined grid ro!s,columns and grants all com onents !ithin it an e;ual si/e based on the dimensions of the largest com onent9 It is an e-cellent layout for a set of icons in a grid9
-able Layo"t
The table layout is far more elaborate than the grid layout and more a1in to the HT(L table structure9 It is a constraint based layout, ho!e+er it includes a default constraint if none are s ecified >e9g9 using container9addCom onent'com onent(O is e;ui+alent to using addCom onent>>layout9createConstraint>?, cm ??9 A table generally gi+es elements their referred si/es but stretches them based on column,ro!9 There are abilities !ithin the constraint element to define multi le beha+iors such as ro!,column s anning, alignments and gro! beha+ior9
The table layout !ill automatically si/e com onents to the largest referred si/e in the ro!,column until running out of s ace, if the table is not hori/ontally scrollable this !ill ha en !hen the edge of the arent container is reached >close to the edge of the screen? and further com onents !ill be Hcrammed togetherH9 $otice that all cells in the table layout are si/ed to fit the entire cell al!ays9 To align, or margin cellQs a de+elo er can use the methods of the com onent,Style a ro riately9 A de+elo er can ro+ide hints to the table layout to enable s anning and more detailed column,ro! si/es using the constraint argument to the addCom onent method9 The constraint argument is an instance of TableLayout9Constraint that m"st not be reused for more than one cell, this !ill cause an e-ce tion9 A constraint can s ecify the absolute ro!,column !here the entry should fit as !ell as s anning bet!een cell boundaries9 $otice that in the icture the HFirstH cell is s anned +ertically !hile the HS anningH cell is s anned hori/ontally9 This is immensely useful in creating elaborate "IQs, Constraints can also s ecify a height,!idth for a column,ro! that !ill o+erride the default, this si/e is indicated in ercentage of the total table layout si/e9 In the icture you can see that the HFirstH label is si/ed to DAS !idth !hile the HForthH label is si/ed to 3AS height9
Codename One 2012. All rights Reserved. http: !!!."odenameone."om 38
Form mainForm P new Form'HTable LayoutH(O TableLayout layout P new TableLayout'@, 8(O mainForm9setLayout'layout(O TableLayout9Constraint constraint P layout9createConstraint'(O constraint9set5erticalS an'3(O constraint9set'idth.ercentage'DA(O mainForm9addCom onent'constraint, new Label'HFirstH((O mainForm9addCom onent'new Label'HSecondH((O mainForm9addCom onent'new Label'HThirdH((O constraint P layout9createConstraint'(O constraint9setHeight.ercentage'3A(O mainForm9addCom onent'constraint, new Label'HForthH((O mainForm9addCom onent'new Label'HFifthH((O constraint P layout9createConstraint'(O constraint9setHori/ontalS an'8(O Label s an P new Label'HS anningH(O s an9getStyle'(9set%order'%order9createLine%order'3((O s an9setAlignment'Com onent9CE$TE0(O mainForm9addCom onent'constraint, s an(O mainForm9sho!'(O
Layered Layo"t
The layered layout 7ust laces the com onents in order one on to of the other and si/es them all to the si/e of the largest com onent9 This is useful !hen trying to create an o+erlay on to of an e-isting com onent e9g9 an L-M button to allo! remo+ing the com onent9
Layo"t 7e#low
'hen adding a com onent to a form !hich isnEt sho!n on the screen there is no need to tell the "I to re aint or reflo!9 This ha ens im licitly9 Ho!e+er, !hen adding a com onent to a "I !hich is already +isible the com onent !ill not sho! by default9 The reason for this is erformance based9 E9g9 imagine adding 1AA com onents to an already +isible form !ith 1AA com onents !ithin it9 If !e laid out automatically layout !ould ha+e ha ened 1AA times !hen it can ha en only once9 That is !hy !hen you add com onents to a form that is already sho!ing you should in+o1e re+alidate or animate the layout a ro riately9 This also enables layout animation beha+ior e- lained belo!9
Layo"t 0nimations
To understand animations you need to understand a cou le of things about Codename #ne com onents9 'hen !e add a com onent to a container itQs generally 7ust added but not ositioned any!here9 A no+ice might notice the set=,6,'idth,Height methods on a com onent and 7ust try to osition it absolutely9 This !onQt !or1 since these methods are meant for the layout manager !hich it im licitly in+o1ed !hen a form is sho!n >internally in Codename #ne? and the layout manager uses these methods to osition the com onents as it sees fit9 Ho!e+er, if you add com onents to a Codename #ne Form that is already sho!n it is your res onsibility to in+o1e re+alidate >or layoutContainer? to arrange the ne!ly added com onents9 Codename #ne doesnQt Hreflo!H im licitly since that !ould be hugely e- ensi+e, imagine doing the layout calculations for e+ery com onent added to the container the cost !ould be closer to a factorial of the original cost of adding a com onent9 The animateLayout>? is sim ly a fancy form of re+alidate9 After changing the layout !hen you in+o1e this method it !ill animation the com onents to their ne! si/es and ositions seamlessly9 The first e-am le in the ti ster demo sho!s an HinterlaceH effect !here the com onents each slide from a se arate direction into the screen9 This is the code I used before sho!ing the form) f9re+alidate'(O #or'int iter P A O iter T c9getCom onentCount'( O iterUU( ) Com onent current P c9getCom onentAt'iter(O i#'iter S 3 PP A( ) current9set='4current9get'idth'((O + else ) current9set='current9get'idth'((O + +
c9setShouldCalc.referredSi/e'tr"e(O c9animateLayout'1AAA(O Lets go o+er this line by line) f9re+alidate'(O I ma1e sure the layout is +alid so I can start from the correct com onent ositions9 i#'iter S 3 PP A( ) current9set='4current9get'idth'((O + else ) current9set='current9get'idth'((O + I manually osition e+ery com onent outside of the screen, if they are odd I lace them to the right and if they are e+en I lace them to the left9 c9setShouldCalc.referredSi/e'tr"e(O I mar1 the "I as needing layout9 This is crucial since I +alidated the "I earlier >by calling re+alidate?9 Changing the =,6,'idth,Height doesnQt trigger a +alidationK Codename #ne doesnQt 1no! I made that changeK %y calling setShouldCalc.referredSi/e IQm e- licitly telling Codename #ne that I changed something in the "I and I !ant it to +alidate, normally this method is im licitly in+o1ed by Codename #ne9 c9animateLayout'1AAA(O .erform the animation o+er the length of a second, this might seem li1e much but the animation starts before the form entry transition so it isnQt that much9 The other animations are e+en sim ler than this one and all follo! the same basic rules, lace the com onents !here+er you !ant either manually >or by changing the layout? and use animateLayout>? to automatically rearrange them to the ne! osition9
under documented, mostly because its almost e-actly li1e its S!ing,A'T e;ui+alent) building a layout manager9 A layout manager contains all the logic for ositioning Codename #ne com onents, it essentially tra+erses a Codename #ne container and ositions com onents absolutely based on internal logic9 'hen !e build our o!n com onent !e need to ta1e adding into consideration, !hen !e build the layout !e need to ta1e margin into consideration9 %uilding a layout manager in+ol+es t!o sim le methods) layoutContainer & get.referredSi/e9 layoutContainer is in+o1ed !hene+er Codename #ne decides the container needs rearranging, Codename #ne tries to a+oid calling this method and only in+o1es it at the last ossible moment9 Since this method is generally +ery e- ensi+e >imagine the recursion !ith nested layouts999?, Codename #ne 7ust mar1s a flag indicating layout is HdirtyH !hen something im ortant changes and tries to a+oid Hreflo!sH9 get.referredSi/e allo!s the layout to determine the si/e desired for the container, this might be a difficult call to ma1e for some layout managers that try to ro+ide both fle-ibility and sim licity9 (ost of flo! layout bugs stem from the fact that this method is 7ust im ossible to im lement for flo! layout9 The si/e of the final layout !onQt necessarily match the re;uested si/e >it robably !onQt? but the re;uested si/e is ta1en into consideration, es ecially !hen scrolling and also !hen si/ing arent containers9 This is a layout manager that 7ust arranges com onents in a center column aligned to the middle) /** * Layout manager that arranges components in a center column * * @author Shai Almog */ p"bli lass CenterLayout e4tends Layout ) p"bli *oid layoutContainer'Container arent( ) int com onents P arent9getCom onentCount'(O Style arentStyle P arent9getStyle'(O int center.os P arent9getLayout'idth'( , 3 U arentStyle9get(argin'Com onent9LEFT(O int y P arentStyle9get(argin'Com onent9T#.(O #or'int iter P A O iter T com onents O iterUU( ) Com onent current P arent9getCom onentAt'iter(O 2imension d P current9get.referredSi/e'(O current9setSi/e'd(O current9set='center.os 4 d9get'idth'( , 3(O Style currentStyle P current9getStyle'(O y UP currentStyle9get(argin'Com onent9T#.(O
Codename One 2012. All rights Reserved. http: !!!."odenameone."om 3B
current9set6'y(O y UP d9getHeight'( U currentStyle9get(argin'Com onent9%#TT#((O + + p"bli 2imension get.referredSi/e'Container arent( ) int com onents P arent9getCom onentCount'(O Style arentStyle P arent9getStyle'(O int height P arentStyle9get(argin'Com onent9T#.( U arentStyle9get(argin'Com onent9%#TT#((O int margin= P arentStyle9get(argin'Com onent90I&HT( U arentStyle9get(argin'Com onent9LEFT(O int !idth P margin=O #or'int iter P A O iter T com onents O iterUU( ) Com onent current P arent9getCom onentAt'iter(O 2imension d P current9get.referredSi/e'(O Style currentStyle P current9getStyle'(O !idth P (ath9ma-'d9get'idth'( U margin= U currentStyle9get(argin'Com onent90I&HT( U currentStyle9get(argin'Com onent9LEFT(, !idth(O height UP currentStyle9get(argin'Com onent9T#.( U d9getHeight'( U currentStyle9get(argin'Com onent9%#TT#((O + 2imension si/e P new 2imension'!idth, height(O ret"rn si/eO + + Here is a sim le e-am le of using it) Form f P new Form'HCenteredH(O f9setLayout'new CenterLayout'((O #or'int iter P 1 O iter T 3A O iterUU( ) f9addCom onent'new %utton'H%utton) H U iter((O + f9addCom onent'new %utton'H0eally 'ide %utton Te-tKKKH((O f9sho!'(O
-heme Basi s
This cha ter co+ers the creation of a sim le hello !orld style theme and ho! it can be customi/ed +isually9 It uses the Codename #ne 2esigner tool to demonstrate basic conce ts in theme creation such as J4 iece borders, selectors and style ty es9 Codename #ne themes are effecti+ely a set of "II2Qs ma ed to a Style ob7ect, !e can create a ne! theme by adding it in the 2esigner tool and customi/ing the "II2 +alues9
'e can add a com onent style to a com onent such as %utton, ty ically "II2Qs are named !ith the same name as the Com onent class9 6ou can modify the "II2 of a com onent by in+o1ing set"II2>String? on an arbitrary com onent or changing the "II2 ro erty in the &"I builder9
Styles can ha+e one of @ states) 19 2efault >unselected? 4 the !ay a com onent a ears !hen its in none of the other states9 39 Selected 4 sho!n !hen the com onent has focus or is acti+e >on a touch screen de+ice this only a ears !hen the user interacts !ith the de+ice !ith touch or !ith a hysical 1ey?9 89 .ressed 4 sho!n !hen the com onent is ressed9 This is only acti+e for %uttonQs9 @9 2isabled 4 sho!n !hen the com onent is disabled9 6ou can add a style to any one of the states in the 2esigner to ma1e the com onent a e- ected in those cases9 ear as
'hen editing the style of the com onent you can customi/e multi le things such as the bac1ground image, the !ay such a bac1ground image is dis layed or a gradient,solid color bac1ground9 6ou can customi/e colors, fonts, adding,margin, border etc9
%orders are a remar1ably o!erful tool for customi/ing a Com onent9 The most o!erful a roach is the J4 iece image border !hich is easiest to use !hen using the Image %order 'i/ard9
The image border !i/ard allo!s you to ta1e an image and Hcut itH into J distinct ieces) @ corners, to , bottom, left, right & center9 The corners are laced as usual in the edges of the com onent and the other elements are tiled to fill u the a+ailable s ace9
Its im ortant !hen using a gradient effect !ithin the image border to ma1e sure the center iece is as narro! as ossible to a+oid a case of a Hbro1enH gradient9
0d*an ed -heming
This cha ter co+ers the ad+anced conce ts of theming as !ell as dee er understanding of ho! to build,design a Codename #ne Theme9
/tyle Inheritan e
Codename One 2012. All rights Reserved. http: !!!."odenameone."om 8F
There are multi le defaults defined for elements !ithin Codename #ne, e9g9 a Container defaults to /ero adding,margin and full trans arency9 %y default e+ery style inherits from these common cross latform defaults9 #ther than that a theme may deri+e from the latform nati+e theme ro+iding further defaults9 In the designer !e can define !hether a s ecific entry deri+es from the global default or defines its o!n o+erride)
The 2eri+e entry !ithin the style allo!s a s ecific style to deri+e and e-tend another style, e9g9 a %utton selected style can deri+e from a %utton unselected style thus remo+ing the need to redefine style beha+ior for e+ery state9 This is +ery useful !hen defining commonalities among entries in a theme9
Ba kgro"nds
The bac1ground tab is one of the more elaborate entries !ithin the style section9 $otice that a bac1ground !ill only a ly !hen no border is defined9 In general 3 ty es of bac1ground are su orted) Image or &radient9 6ou can ic1 se+eral modes for each9 For the gradients you can ic1 one of hori/ontal, +ertical or radial gradient9 In the case of gradients you need to define all the gradient +ariables mentioned !ithin the screen to define the source,destination colors and in the case of a radial the ro erties rele+ant to that9 'hen using an image bac1ground there are basically three o tions) Scaled, Tiled or Aligned9 An image can be scaled across the bac1ground of the com onent, this can create a decent effect in some cases but often causes some distortion9 An image can be aligned to a s ecific location !ithin the com onent bac1ground, in !hich case the com onent !ill be ainted based on the trans arency setting and the image !ill be ainted in the a ro riate location based on the alignment9 Finally an image can be tiled either com letely o+er the bac1ground or tiled as a single ro!,column aligned to a s ecific area !ithin the com onent9
Codename One 2012. All rights Reserved. http: !!!."odenameone."om 8I
3onts
Codename #ne su orts 3 ma7or font ty es1 system fonts and truety e fonts9 The system fonts are +ery limited in selection but are highly recommended for ortability9 They use the built in font on the gi+en de+ice !hich is often the font the user is used to9 A de+elo er has a selection from one of 8 generic si/es small, medium or large and basic style choices) bold, lain,italic9 'hen a s ecific truety e font is needed Codename #ne allo!s the de+elo er to lace a truety e font !ithin the src directory of the ro7ect9 This font !ill be automatically detected by the designer tool and offered as an o tion9 Since truety e fonts are only su orted on i#S, Android and 0I( de+ices you should still define a system font !hich !ill be used as a fallbac1 on unsu orted latforms9 Truety e fonts allo! s ecifying their si/es using one of 8 a roaches) 19 System font si/e scheme 4 the truety e font !ill ha+e the same si/e as a small, medium or large system font9 This allo!s the de+elo er to si/e the font based on the de+ice 2.I9 39 (illimeter si/e 4 allo!s si/ing the font in a more 2.I a!are si/e9 89 .i-els 4 a font can be si/ed in i-els, !hich is useful for some uni;ue cases but highly roblematic in multi42.I scenarios9
1
Historically bitma fonts !ere also su orted, ho!e+er this functionality is de recated and might be remo+ed in a future re+ision9 'e highly recommend you a+oid using the bitma font functionality9 Codename One 2012. All rights Reserved. http: !!!."odenameone."om 8J
Borders
See the theme basics abo+e about cutting a J4 iece border using the image border class9 Codename #ne su orts configuring the border according to se+eral configurations)
'hen ressing the W999E button you can customi/e the border using multi le configuration ty es)
There are se+eral border ty es that can be used to customi/e the loo1 of the com onent9
5adding2&argin
.adding and margin are conce ts deri+ed from the CSS bo- model9 Its slightly different in Codename #ne !here the border s acing is art of the adding but other than that they are retty similar)
In the abo+e diagram !e can see the com onent re resented in yello! occu ying its referred si/e9 The adding ortion in blue effecti+ely increases the com onents si/e9 The margin is an area !hich effecti+ely belongs to the com onent but the com onent doesnEt dra! anything !ithin that area it is re resented in red9 The theme allo!s us to customi/e the adding,margin and s ecify them for all @ sides of a com onent9 They can be s ecified in i-els, millimeters, or screen ercentage)
.adding is es ecially im ortant !hen a border is defined and !e need to s ace the com onent dra!ing from the edge of the border9 (argin allo!s us to s ace com onents from one another easily and create L!hites aceM !ithin the user interface9
-heme Constants
The Codename #ne 2esigner has a tab for creating constants !hich can be used to add global +alues of +arious ty es and beha+ior hints to Codename #ne and its com oennts9 Constants are al!ays strings, they ha+e some con+entions !here a constant ending !ith %ool is treated as
Codename One 2012. All rights Reserved. http: !!!."odenameone."om @1
a boolean true,false +alue and a constant ending !ith Int or Image >for image the string name of the image is stored but the image instance !ill be returned?9 To use a constant one can use the "I(anagerQs methods to get the a s ecifically) getThemeConstant isThemeConstant getThemeImageConstant ro riate constant ty e
Internally Codename #ne has se+eral built in constants and the list is constantly gro!ing as !e add features to Codename #ne, !e !ill try to 1ee this list u to date !hen ossible9 Constant al!aysTensile%ool Des ription20rg"ment Enables tensile drag e+en !hen there is no scrolling in the container >only for scrollable containers though? Image to gi+e a command !ith no icon .lace commands in the dialogs as buttons .lace the dialog in an arbitrary border layout osition >e9g9 $orth, South, Center etc9? .o u of the combo bo- !ill a ear in the center of the screen chec1%o-Chec12isImage Chec1%o- image to use instead of Codename #ne dra!ing it on its o!n Chec1%o- image to use instead of Codename #ne dra!ing it on its o!n Chec1%o- image to use instead of Codename #ne dra!ing it on its o!n Chec1%o- image to use instead of Codename #ne dra!ing it on its o!n Combo image to use instead of Codename #ne dra!ing it on its o!n Indicates ho! commands should act, as a touch menu, nati+e menu etc9 .ossible +alues) SoftNey, Touch, %ar, Title, 0ight, $ati+e Enables com onent grou !hich allo!s com onents to be
logically grou ed together so the "II2Qs of com onents !ould be modified based on their grou lacement9 This allo!s for some uni;ue styling effects !here the first,last elements ha+e different styles from the rest of the elements9 Its disabled by default thus lea+ing its usage u to the designer9 dialogTransitionIn dialogTransitionInImage dialogTransition#ut dialogTransition#utImage disabledColor dlgCommand%uttonSi/eInt dlgCommand&rid%ool dlgSlide2irection dlgSlideIn2ir%ool dlgSlide#ut2ir%ool fadeScroll%ar%ool fadeScrollEdge%ool 2efault transition for dialog 2efault transition Image for dialog, causes a Timeline transition effect 2efault transition for dialog 2efault transition Image for dialog, causes a Timeline transition effect Color to use !hen disabling entries by default (inimum si/e to gi+e to command buttons in the dialog .laces the dialog commands in a grid for uniform si/es Slide hints Slide hints Slide hints %oolean indicating if the scrollbar sho! fade !hen there is inacti+ity .laces a fade effect at the edges of the screen to indicate that its ossible to scroll until !e reach the edge >common on Android?9 Amount of i-els to fade out at the edge Indicates to the &enericListCell0enderer that it should determine 0TL status based on the first character in the sentence $umber corres onding to the fi-ed selection constants in List 2efault transition for form 2efault transition Image for form, causes a Timeline transition effect 2efault transition for form
fadeScrollEdgeInt firstChar0TL%ool
formTransition#utImage
2efault transition Image for form, causes a Timeline transition effect Indicates that a title !ith no content should be hidden e+en if the border for the title occu ies s ace Hide the focus com onent of the list !hen the list doesnQt ha+e focus True to deri+e from the latform nati+e theme, false to create a blan1 theme that only uses the basic defaults9 %uiltin item ga in the list, this defaults to 3 !hich redated adding,margin in Codename #ne Allo!s ositioning and si/ing the menu Allo!s ositioning and si/ing the menu 2efines menu entrance effect 2efines menu entrance effect 2efines menu entrance effect 2efines menu entrance effect 2efines menu entrance effect 2efines menu e-it effect 2efines menu entrance effect Allo!s ositioning and si/ing the menu Indicates !hether the form should minimi/e the entire a lication !hen the hysical bac1 button is ressed >if a+ailable? and no command is defined as the bac1 command9 2efaults to true9 Indicates that a se arate renderer "II2,instance should be used to the list !ithin the combo bo- o u Enables referred si/ed ac1ing of the touch menu >true by default?, !hen set to false this allo!s manually determining the touch menu si/e using ercentages
hideEm tyTitle%ool ignorListFocus%ool include$ati+e%ool listItem&a Int menuHeight.ercent menu.refSi/e%ool menuSlide2irection menuSlideIn2ir%ool menuSlide#ut2ir%ool menuTransitionIn menuTransitionInImage menuTransition#ut menuTransition#utImage menu'idth.ercent minimi/e#n%ac1%ool
other.o u 0enderer%ool
.ac1Touch(enu%ool
o u Cancel%ody%ool o u Title%ool ureTouch%ool radioSelected2isImage radioSelectedImage radio"nselected2isImage radio"nselectedImage rendererSho!s$umbers%ool re+erseSoft%uttons%ool slide2irection slideIn2ir%ool slide#ut2ir%ool sna &rid%ool tab.lacementInt tabsFill0o!s%ool tabs&rid%ool te-tCm 5AlignInt te-tFieldCursorColorInt tic1erS eedInt tintColor touchCommandFill%ool touchCommandFlo!%ool
Indicates that a cancel button should a bo- o u Indicates that a title should a o u Indicates the ure touch mode 0adio button image 0adio button image 0adio button image 0adio button image
Indicates !hether renderers should render the entry number S!a s the softbutton ositions 2efault slide transition settings 2efault slide transition settings 2efault slide transition settings Sna to grid toggle The lacement of the tabs in the Tabs com onent) T#. P A, %#TT#( P 3, LEFT P 1, 0I&HT P 8 Indicates if the tabs should fill the ro! using flo! layout Indicates !hether tabs should use a grid layout thus forcing all tabs to ha+e identical si/es The +ertical alignment of the te-t com onent) T#. P A, CE$TE0 P @, %#TT#( P 3 The color of the cursor as an integer >not he-? The s eed of label,button etc9 tic1ering in ms9 The aarrggbb he- color to tint the screen !hen a dialog is sho!n Indicates ho! the touch menu should layout the commands !ithin Indicates ho! the touch menu should layout the commands !ithin
Indicates the default s eed for transitions indicates that tensile drag should be enabled,disabled9 This is usually set by latform themes9
#ne HoddH beha+ior of constants is that once they are set by a theme they donQt get HlostH !hen re lacing the theme9 E9g9 if one !ould set the comboImage constant to a s ecific +alue in theme A and then s!itch to theme % that doesnQt define the comboImage, the original theme A comboImage might remain9 The reason for this is sim le, !hen e-tracting the constant +alues com onents 1ee the +alues in cache locally and 7ust donQt trac1 the change in +alue9 Furthermore, since the com onents allo! manually setting +alues its im ractical for them to trac1 !hether a +alue !as set by a constant or e- licitly by the user9 The solution for this is to either manually reset undesired +alues before re lacing a theme >e9g9 for the case abo+e by calling the default loo1 and feel method for setting the combo image !ith a null +alue? or defining a constant +alue to re lace the e-isting +alue9
C C C C C
font 4 A Font ob7ect instance alignment 4 an Integer ob7ect containing the LEFT,0I&HT,CE$TE0 constant +alues defined in Com onent9 te-t2ecoration 4 an Integer +alue containing one of the TE=TR2EC#0ATI#$R[ constant +alues defined in Style9 bac1groundTy e 4 a %yte ob7ect containing one of the constants for the bac1ground ty e defined in Style under %ACN&0#"$2R[9 bac1ground&radient 4 contains an #b7ect array containing 3 integers for the colors of the gradient9 If the gradient is radial it contains 8 floating oints defining the -, y & si/e of the gradient9
So to set the foreground color of a selected button to red a theme !ill define a ro erty li1e) %utton9selZfgColorPffAAAA This information is mostly useful for understanding ho! things !or1 !ithin Codename #ne, but it can also be useful in runtime9 E9g9 to increase the si/e of all fonts in the a lication !e can do something li1e) Hashtable h P new Hashtable'(O h9 ut'HfontH, largeFont(O "I(anager9getInstance'(9addTheme.ro s'h(O 2is lay9getInstance'(9getCurrent'(9refreshTheme'(O
ho!e+er, !e can e- licitly define images for multi le resolutions and erform high ;uality scaling so the LrightM image is a+ailable9 To add a multi4image !e can use t!o basic methods) ;uic1 add & standard add9 %oth rely on understanding the source resolution of the image, e9g9 you ha+e an icon that you e- ect to be 13I-13I i-els on i.hone @, 1A3-1A3 on ne-us one and F@-F@ on i.hone 8gs9 6ou can ro+ide the source image as the 13I i-el image and 7ust erform a ;uic1 add o tion !hile ic1ing the 5ery High density o tion as an o tion9 This !ill indicate to the algorithm that your source image is designed for +ery high density and it !ill scale for the rest of the densities accordingly9 Alternati+ely you can use the standard add multi4image dialog and set it li1e this)
$otice that I selected s;uare images essentially eliminating the height o tion9 Setting +alues to A re+ents the system from generating a multi4image entry for that resolution, !hich !ill mean a de+ice in that category !ill fall on the closest alternati+e9 The ercentage +alue !ill change the entire column and it means the ercentage of the screen9 E9g9 'e 1no! the icon is 13I for the +ery high resolution, !e can 7ust mo+e the ercentage until
Codename One 2012. All rights Reserved. http: !!!."odenameone."om @I
!e reach something close to 13I in the L5ery HighM ro! and the other ro!s !ill re resent a si/e that should be retty close in terms of hysical si/e to the 13I figure9
Container
The Codename #ne container is a base class for many high le+el com onents, a container is basically a com onent that can contain other com onents9 That is all9 E+ery com onent has a arent container !hich can be null if it isnEt !ithin a container at the moment or is a to le+el container9 A container can ha+e many children9 Com onents are arranged in containers using layout managers !hich are 7ust algorithms to determine the flo! !ithin a s ecific container9 6ou can read more about layout managers in the section belo! dedicated to layout managers9 The default layout of a Container is flo! layout !hich is useful for sim le ty es of layouts but roblematic !ith many scenarios9 'e recommend you read about this in the layout manager section9
3orm
The to le+el container of Codename #ne9 Form deri+es container and it is effecti+ely the element !e Lsho!M9 #nly one form can be +isible at any gi+en time and !e can get the currently +isible form using the code) Form currentForm P 2is lay9getInstance'(9getCurrent'(O A form is a uni;ue container in the sense that it has a title, a content area and o tionally a menu,menu bar area9 'hen in+o1ing methods such as add,remo+eCom onent on a form you are in fact in+o1ing something that loo1s li1e) myForm9getContent.ane'(9addCom onent'999(O 'hich ma1es sense since a form is really 7ust a Container that has a border layout, its north section is occu ied by the title area and its south section by the o tional menu bar9 The center >!hich stretches? is the content ane9 The content ane is !here you lace all your com onents9
There is one im ortant iece missing from this image !hich is the glass ane >more on that soon?, but basically you can see that e+ery form has s ace allocated for the title,menu bar9 If you donEt set the title if !onEt sho! u >its si/e !ill be /ero? but it !ill still be there9 The same isnEt al!ays true for the case of the menu bar !hich can +ary significantly9 Effecti+ely the section that matters is the content ane, so the form tries to do the Lright thingM by retending to be the content ane9 Ho!e+er, this isnEt al!ays seamless and sometimes code needs to 7ust in+o1e getContent.ane>? in order to !or1 directly !ith the container9 FormEs ha+e an additional layer ainted on to of them called the glass ane, this allo!s de+elo ers to o+erlay "I on to of e-isting "I and aint as they see fit9 This is useful for things that ro+ide notification but donEt !ant to intrude !ith a lication functionality9
Dialog
A dialog is a s ecial 1ind of form that can occu y only a ortion of the screen, it also has the additional functionality of the modal sho! method9 'hen sho!ing a dialog !e ha+e t!o basic o tions modless and modal9 (odal dialogs >the default? bloc1 the current E2T thread until the dialog is dismissed >to understand ho! they do it read about in+o1eAnd%loc1?9 (odal dialogs are an e-tremely useful !ay to rom t the used since the code has the users res onse on the ne-t line of e-ecution romoting a +ery linear !ay of coding9 The dialog class contains multi le static hel er methods to ;uic1ly sho! user notifications, but also allo!s a de+elo er to create a dialog instance, add information to its content ane and sho! the dialog9 'hen sho!ing a dialog in this !ay you can either as1 Codename #ne to osition the dialog in a s ecific general location >ta1en from the %orderLayout conce t for locations? or osition it by s acing it >in i-els? from the @ edges of the screen9
Label
Label allo!s dra!ing te-t or lacing an icon, it is a single line label that might tic1er and might end !ith L999M in some cases !here a ro riate9 2e+elo ers can determine the lacement of the label relati+ely to its icon in ;uite a fe! o!erful !ays9 Label ser+es as the base class for button !hich inherits all its functionality9 Label doesnEt brea1 lines since line brea1 su ort is e- ensi+e in terms of C.", ho!e+er Te-tArea does brea1 lines and a common use case for creating a multi4line label is to set the "II2 of te-t area to LLabelM and in+o1e its setEditable>false? method9
B"tton
A button is a subclass of label and so it inherits much of its functionality, s ecifically icon lacement, tic1ering etc9 %esides being L ressableM !hich is a uni;ue feature to %utton and its subclasses, it also allo!s for icons based on its states > ressed, ho+er etc9?9
&"lti9B"tton
A multi button is a s ecial com onent that allo!s button li1e functionality >although it technically deri+es from Container? !ith more ad+anced features9 It su orts u to @ lines of te-t >it doesnEt automatically !ra the te-t?, an emblem >usually na+igational arro!, or chec1 bo-? and an icon9 It can be used as a button, a label, a chec1bo- or a radio button and allo!s creating richer "IEs9 The (ulti%utton is meant to ro+ide de+elo ers !ith the ability to re licate some of the "I aradigms that are common to the "ITable5ie! i#S "IQs9 The (ulti%utton doesnQt include anything radically s ecial, its 7ust a standard container !ith a Lead Com onent based "I9 The (ulti%utton is mostly designed for use !ith the &"I builder although using it from code is similar9 A common source of confusion is the difference bet!een the icon and the emblem since both may ha+e an icon image associated !ith them9 The icon is an image re resenting the entry !hile the emblem is an o tional +isual re resentation of the action that !ill be underta1en !hen the element is ressed9 %oth may be used simultaneously or indi+idually of one another9
-e4t3ield2-e4t0rea
The Te-tField class deri+es from the Te-tArea class and both are the mechanisms for user te-t in ut in Codename #ne9 The semantic difference bet!een the t!o classes dates bac1 to the roots of Codename #ne in L'"IT !here feature hones donEt ha+e L ro erM in4 lace editing ca abilities9 Te-t field allo!ed in ut on +arious de+ice ty es !ithout o ening the nati+e full screen editing facilities9 This is not used in any smart hone latform other than Symbian9 #n those latforms Te-tField and Te-tArea are ractically identical9 %oth ro+ide multi4line editing ca abilities etc9 #ne small difference in te-t field is the blin1ing cursor animation !hich doesnEt a ear in the te-t area im lementation !hen it isnEt edited9 A common alternati+e use case of te-t area is as a multi4line label, to understand more about that lease read the label section abo+e9
-oggle B"tton
A toggle button is a button that is ressed and then stays ressed, !hen ressed again itQs released9 Hence the button has a selected state to indicate if itQs ressed or not9 <ust li1e the radio button or chec1bocom onents in Codename #ne9 So Codename #neQs ne! toggle buttons are really any button >chec1bo- & radio buttons deri+e from %utton? that has the setToggle>? method in+o1ed !ith true9 It thus aints itself !ith the toggle button style unless e- licitly defined other!ise >note that the "II2 !ill be im licitly changed to HToggle%uttonH?9 The cool thing about this is that you can effecti+ely ta1e your 1no!ledge about chec1bo-es & radio buttons and a ly it to toggle buttons9 ThatQs half the story though, to get the full effect of some cool toggle button "IQs !e !ould li1e to assign the buttons on the edges !ith a rounded feel li1e some latforms choose to do999 ThatQs retty easy, you can 7ust assign a different "II2 to the first,last buttons and be o+er !ith it9 %ut !hat if you !ant your code to be generic* After all you might add,remo+e a button in runtime based on a lication state and you !ould li1e it to ha+e the right style9 To sol+e this !e introduced the Com onent&rou 9 The Com onent&rou is a s ecial container that can be either hori/ontal or +ertical >%o- = or 6 res ecti+ely?, it also does nothing else9 6ou need to e- licitly acti+ate it in the theme by setting a theme ro erty to true >by default you need to set Com onent&rou %ool to true?9 'hen Com onent&rou %ool is set to true the com onent grou !ill modify the styles of all com onents laced !ithin it to match the element "II2 gi+en to it >by default &rou Element? !ith s ecial ca+eats to the first,last,only elements9 E9g9 19 If I ha+e one element !ithin a com onent grou it !ill ha+e the "II2) &rou Element#nly 39 If I ha+e t!o elements !ithin a com onent grou they !ill ha+e the "II2Qs &rou ElementFirst, &rou ElementLast 89 If I ha+e three elements !ithin a com onent grou they !ill ha+e the "II2Qs &rou ElementFirst, &rou Element, &rou ElementLast @9 If I ha+e four elements !ithin a com onent grou they !ill ha+e the "II2Qs &rou ElementFirst, &rou Element, &rou Element, &rou ElementLast 6ou get the icture999 This allo!s you to define s ecial styles for the sides >donQt forget to use the deri+e attribute to generali/e your theme? and ro+ide toggle buttons that include s ecial effects sim ly by lacing them into this grou 9 6ou can customi/e the "II2 set by the com onent grou by calling setElement"II2 in the com onent grou e9g9 setElement"II2>HToggle%uttonH? for the icture abo+e !ill result in) Toggle%uttonFirst, Toggle%utton, Toggle%uttonLast
Codename One 2012. All rights Reserved. http: !!!."odenameone."om DD
This is a short sam le) Com onent&rou buttons P new Com onent&rou '(O buttons9setElement"II2'HToggle%uttonH(O buttons9setHori/ontal'tr"e(O 0adio%utton lain P new 0adio%utton'H.lainH(O 0adio%utton underline P new 0adio%utton'H"nderlineH(O 0adio%utton stri1eout P new 0adio%utton'HStri1ethruH(O %utton&rou bg P new %utton&rou '(O init0b'bg, buttons, listener, lain(O init0b'bg, buttons, listener, underline(O init0b'bg, buttons, listener, stri1eout(O Container centerFlo! P new Container'new Flo!Layout'Com onent9CE$TE0((O f9addCom onent'centerFlo!(O centerFlo!9addCom onent'buttons(O pri*ate *oid init0b'%utton&rou bg, Container buttons, ActionListener listener, 0adio%utton rb( ) bg9add'rb(O rb9setToggle'tr"e(O buttons9addCom onent'rb(O rb9addActionListener'listener(O +
has no memory o+erhead but if it ta1es too long to rocess a model +alue it can be a big bottlenec1K This is all +ery generic but a bit too much for most, doing a list H ro erlyH re;uires some understanding9 The main source of confusion for de+elo ers is the stateless nature of the list and transfer of state to the model >e9g9 a chec1bo- list needs to listen to action e+ents on the list and u date the model in order for the renderer to dis lay that state999 #nce you understand that itEs easy?9
$e-t drag a list into the center of the layout and you should no! ha+e a functioning basic list !ith 8 items9
$e-t !e !ill create the 0enderer !hich indicates ho! an indi+idual item in the list a ears, start by ressing the Add $e! &"I Element button and sele t the ;Blank Container< o tionK Fill the name as L(y0endererM or anything li1e that9
'ithin the renderer you can drag any com onent you !ould li1e to a ear, labels, chec1bo-es, etc9 6ou can nest them in containers and layouts as you desire9 &i+e them names that are re resentati+e of !hat you are trying to accom lish e9g9 Firstname, selected etc9
6ou can no! go bac1 to the list, select it and clic1 the 0enderer ro erty in order to select the render container you created re+iously resulting in something li1e this9
6ouEll notice that the data doesnEt match the original content of the list, that is because the list contains strings instead of Hashtables9 To fi- this !e must edit the list data9 6ou can lace your o!n data in the list using the &"I builder !hich is generally desired regardless of !hat you end u doing since this allo!s you to re+ie! your designer in the &"I builder9 If you !ish to o ulate your list from code 7ust clic1 the e+ents tab and ress the List(odel button, you can fill u the model !ith an array of Hashtables as !e e- lain soon enough >you can read more about the list model belo!?9 To o ulate the list +ia the &"I builder clic1 the ro erties of the list and !ithin them clic1 the ListItems entry9 The entries !ithin can be strings or Hashtables, ho!e+er in order to be customi/able in the rendering stage !e !ill need them all to be Hashtables9 0emo+e all the current entries and add a ne! entry)
Codename One 2012. All rights Reserved. http: !!!."odenameone."om DJ
'e no! ha+e a customi/ed list thatEs ada ted to its renderer)
Understanding &=C
Lets reca , !hat is (5C) (odel 4 0e resents the data for the com onent >list?, the model can tell us e-actly ho! many items are in it and !hich item resides at a gi+en offset !ithin the model9 This differs from a sim le 5ector >or array? since all access to the model is controlled >the interface is sim ler? and unli1e a 5ector,Array the model can notify us of changes that occur !ithin it9 5ie! 4 The +ie! dra!s the content of the model9 It is a HdumbH layer that has no notion of !hat is dis layed and only 1no!s ho! to dra!9 It trac1s changes in the model >the model sends e+ents? and redra!s itself !hen it changes9 Controller 4 The controller acce ts user in ut and erforms changes to model !hich in turn cause the +ie! to refresh9 Codename #neQs List com onent uses the (5C aradigm to se arate its im lementation9 List itself is the Controller >!ith a bit of 5ie! mi-ed in?9 The ListCell0enderer interface is a 5ie! and the List(odel is >you guessed it by no!? the model9 'hen the list is ainted it iterates o+er the +isible elements in the model and as1s for them, it then dra!s them using the renderer9 'hy is this useful* Since the model is a light!eight interface it can be im lemented by you and re laced in runtime if so desired, this allo!s se+eral +ery cool use cases) 19 A list can contain thousands of entries but only load the ortion +isible to the user9 Since the model !ill only be ;ueried for the elements that are +isible to the user it !onQt need to load into
memory a +ery large data set until the user starts scrolling do!n >at !hich oint other elements may be offloaded from memory?9 39 A list can cache efficiently9 E9g9 a list can mirror data from the ser+er into local 0A( !ithout actually do!nloading all the data9 2ata can also be mirrored from 0(S for better erformance and discarded for better memory utili/ation9 89 $o need for state co ying9 Since renderers allo! us to dis lay any ob7ect ty e, the list model interface can be im lemented by the a lications data structures >e9g9 ersistence,net!or1 engine? !hich !ould return internal a lication data structures sa+ing you the need of co ying a lication state into a list s ecific data structure9 @9 "sing the ro-y attern >as e- lained in a re+ious ost? !e can layer logic such as filtering, sorting, caching etc9 on to of e-isting models !ithout changing the model source code9 D9 'e can reuse generic models for se+eral +ie!s e9g9 a model that fetches data from the ser+er can be initiali/ed !ith different arguments to fetch different data for different +ie!s9 5ie! ob7ects in different FormQs can dis lay the same model instance in different +ie! instances thus they !ould u date automatically !hen !e change one global model9 (ost of these use cases !or1 best for lists that gro! to a larger si/e or re resent com le- data !hich is !hat the list ob7ect is designed to do9
LetQs try to im lement our o!n renderer9 The most sim le,nai+e im lementation may choose to im lement the renderer as follo!s)
p"bli Com onent getListCell0endererCom onent'List list, #b7ect +alue, int inde-, boolean isSelected() ret"rn new Label'+alue9toString'((O + p"bli Com onent getListFocusCom onent'List list() ret"rn n"llO + This !ill com ile and !or1, but !onQt gi+e you much, notice that you !onQt see the List selection mo+e on the List, this is 7ust because the renderer returns a Label !ith the same style regardless if itQs being selected or not9 $o! LetQs try to ma1e it a bit more useful9 p"bli Com onent getListCell0endererCom onent'List list, #b7ect +alue, int inde-, boolean isSelected() Label l P new Label'+alue9toString>?(O i# 'isSelected( ) l9setFocus'tr"e(O l9getStyle'(9set%gTrans arency'1AA(O + else ) l9setFocus'#alse(O l9getStyle'(9set%gTrans arency'A(O + ret"rn lO + p"bli Com onent getListFocusCom onent'List list() ret"rn n"llO + In this renderer !e set the Label9setFocus>true? if itQs selected, calling to this method doesnQt really gi+es the focus to the Label, it sim ly indicates to the Loo1AndFeel to dra! the Label !ith fgSelectionColor and bgSelectionColor instead of fgColor and bgColor9 Then !e call to Label9getStyle>?9set%gTrans arency>1AA? to gi+e the selection semi trans arency and A for full trans arency if not selected9 #N thatQs a bit more functional, but not +ery efficient thatQs because !e create a ne! Label each time the method is called9
To ma1e it more de+ice friendly 1ee a reference to the Com onent or e-tend the 'idget9 lass (y0enderer e4tends Label implements ListCell0enderer ) p"bli Com onent getListCell0endererCom onent'List list, #b7ect +alue, int inde-, boolean isSelected() setTe-t'+alue9toString>?(O i# 'isSelected( ) setFocus'tr"e(O getStyle'(9set%gTrans arency'1AA(O + else ) setFocus'#alse(O getStyle'(9set%gTrans arency'A(O + ret"rn thisO + + + $o! LetQs ha+e a loo1 at a more ad+anced 0enderer lass Contacts0enderer e4tends Container implements ListCell0enderer ) pri*ate Label name P new Label'HH(O pri*ate Label email P new Label'HH(O pri*ate Label ic P new Label'HH(O pri*ate Label focus P new Label'HH(O p"bli Contacts0enderer'( ) setLayout'new %orderLayout'((O addCom onent'%orderLayout9'EST, ic(O Container cnt P new Container'new %o-Layout'%o-Layout96RA=IS((O name9getStyle'(9set%gTrans arency'A(O name9getStyle'(9setFont'Font9createSystemFont'Font9FACERS6STE(, Font9ST6LER%#L2, Font9SI\ER(E2I"(((O email9getStyle'(9set%gTrans arency'A(O cnt9addCom onent'name(O cnt9addCom onent'email(O addCom onent'%orderLayout9CE$TE0, cnt(O focus9getStyle'(9set%gTrans arency'1AA(O +
Codename One 2012. All rights Reserved. http: !!!."odenameone."om F@
p"bli Com onent getListCell0endererCom onent'List list, #b7ect +alue, int inde-, boolean isSelected( ) Contact erson P 'Contact( +alueO name9setTe-t' erson9get$ame'((O email9setTe-t' erson9getEmail'((O ic9setIcon' erson9get.ic'((O ret"rn thisO + p"bli Com onent getListFocusCom onent'List list( ) ret"rn focusO + +
In this renderer !e !ant to renderer a Contact #b7ect to the Screen, !e build the Com onent in the constructor and in the getListCell0endererCom onent !e sim ly u dates the Labels te-ts according to the Contact #b7ect9 $otice that in this renderer I return a focus Label !ith semi trans arency, as mentioned before the focus com onent can be modified by using this method9 For e-am le I can modify the focus Com onent to ha+e an icon9 focus9getStyle'(9set%gTrans arency'1AA(O try ) focus9setIcon'Image9createImage'H,du1e9 ngH((O focus9setAlignment'Com onent90I&HT(O + at h 'I#E-ce tion e-( ) e-9 rintStac1Trace'(O +
&enericListCell0enderer is a renderer designed to be as sim le to use as a Com onent4 Container hierarchy, !e effecti+ely crammed most of the common renderer use cases into one class9 To enable that !e need to 1no! the content of the ob7ects !ithin the model, so the &enericListCell0enderer assumes the model contains only Hashtable ob7ects9 Since HashtableQs can contain arbitrary data the list model is still ;uite generic and allo!s storing a lication s ecific data, furthermore a Hashtable can still be deri+ed and e-tended to ro+ide domain s ecific business logic9 The &enericListCell0enderer acce ts t!o container instances >more later on !hy at least t!o and not one? !hich it ma s to indi+idual Hashtable entries !ithin the model by finding the a ro riate com onents !ithin the gi+en container hierarchy9 Com onents are ma ed to the Hashtable entries based on the name ro erty of the com onent >get,set$ame? and the 1ey +alue !ithin the Hashtable e9g9) For a model that contains a Hashtable entry li1e this) HFooH) H%arH H=H) H6H H$otH) HA licableH H$umberH) Integer>1? A renderer !ill loo o+er the com onent hierarchy in the container searching for com onentQs !hose name matches Foo, =, $ot and $umber and assign to them the a ro riate +alue9 $otice that you can also use image ob7ects as +alues and they !ill be assigned to labels as e- ected9 Ho!e+er, you canQt assign both an image and a te-t to a single label since the 1ey !ill be ta1en9 That isnQt a big roblem since t!o labels can be used ;uite easily in such a renderer9 To ma1e matters e+en more attracti+e the renderer seamlessly su orts list tic1ering !hen a ro riate and if a Chec1%o- a ears !ithin the renderer it !ill toggle a boolean flag !ithin the Hashtable seamlessly9 #ne issue that cro s u !ith this a roach is that if a +alue is missing from the hashtable it is treated as em ty and the com onent is reset, this can ose an issue if !e hardcode an image or te-t !ithin the renderer and !e donQt !ant them re lace >e9g9 an arro! gra hic?9 The solution for this is to name the com onent !ith Fi-ed in the end of the name e9g9) HardcodedIconFi-ed9 $aming a com onent !ithin the renderer !ith ]number !ill automatically set it as a counter com onent for the offset of the com onent !ithin the list9 Styling the &enericListCell0enderer is slightly different, the renderer uses the "II2 of the container assed to the generic list cell renderer and the bac1ground focus uses that same "II2 !ith the !ord HFocusH a ended9 It is im ortant to notice that the generic list cell renderer !ill grant focus to the child com onents of the selected entry if they are focusable thus changing the style of said entries9 E9g9 a Container might ha+e a child label that has one style !hen the arent container is unselected and another !hen its selected >focused?, this can be easily achie+ed by defining the label as
focusable9 $otice that the com onent !ill ne+er recei+e direct focus since it is still a ar of a renderer9 Last but not least, the generic list cell renderer acce ts t!o or four instances of a Container rather than the ob+ious choice of acce ting only one instance9 This allo!s the renderer to treat the selected entry differently !hich is es ecially im ortant to tic1ering although its also useful for fisheye9 Since it might not be ractical to seamlessly clone the Container for the rendererQs needs Codename #ne e- ects the de+elo er to ro+ide t!o se arate instances, they can be identical in all res ects but they must be se arate instances for tic1ering to !or19 The renderer also allo!s for a fisheye effect !here the selected entry is actually different from the unselected entry in its structure, it also allo!s for a instri e effect !here odd,e+en ro!s ha+e different styles >this is accom lished by ro+iding @ instances of the containers selected,unselected for odd,e+en?9 The best !ay to learn about the generic list cell renderer and the hashtable model is by laying !ith them in the &"I builder, ho!e+er they can be used in code !ithout any de endency on the &"I builder and can be ;uite useful at that9 Here is a sim le sam le for a list !ith chec1bo-es that get u dated automatically) List list P new List'create&enericListCell0enderer(odel2ata'((O list9set0enderer'new &enericListCell0enderer'create&eneric0endererContainer'(, create&eneric0endererContainer'(((O
pri*ate Container create&eneric0endererContainer'( ) Container c P new Container'new %orderLayout'((O c9set"II2'HList0endererH(O Label name P new Label'(O name9setFocusable'tr"e(O name9set$ame'H$ameH(O c9addCom onent'%orderLayout9CE$TE0, name(O Label surname P new Label'(O surname9setFocusable'tr"e(O surname9set$ame'HSurnameH(O c9addCom onent'%orderLayout9S#"TH, surname(O Chec1%o- selected P new Chec1%o-'(O selected9set$ame'HSelectedH(O selected9setFocusable'tr"e(O c9addCom onent'%orderLayout9'EST, selected(O ret"rn cO +
pri*ate Hashtable>? create&enericListCell0enderer(odel2ata'( ) Hashtable>? data P new Hashtable>D?O data>A? P new Hashtable'(O data>A?9 ut'H$ameH, HShaiH(O data>A?9 ut'HSurnameH, HAlmogH(O data>A?9 ut'HSelectedH, %oolean9T0"E(O data>1? P new Hashtable'(O data>1?9 ut'H$ameH, HChenH(O data>1?9 ut'HSurnameH, HFishbeinH(O data>1?9 ut'HSelectedH, %oolean9T0"E(O data>3? P new Hashtable'(O data>3?9 ut'H$ameH, H#firH(O data>3?9 ut'HSurnameH, HLeitnerH(O data>8? P new Hashtable'(O data>8?9 ut'H$ameH, H6ani+H(O data>8?9 ut'HSurnameH, H5a1aratH(O data>@? P new Hashtable'(O data>@?9 ut'H$ameH, H(eira+H(O data>@?9 ut'HSurnameH, H$achmano+itchH(O ret"rn dataO +
p"bli String get$ame'( ) ret"rn nameO + p"bli String getEmail'( ) ret"rn emailO + p"bli Image get.ic'( ) ret"rn icO + + lass Contacts0enderer e4tends Container implements ListCell0enderer ) pri*ate Label name P new Label'HH(O pri*ate Label email P new Label'HH(O pri*ate Label ic P new Label'HH(O pri*ate Label focus P new Label'HH(O p"bli Contacts0enderer'( ) setLayout'new %orderLayout'((O addCom onent'%orderLayout9'EST, ic(O Container cnt P new Container'new %o-Layout'%o-Layout96RA=IS((O name9getStyle'(9set%gTrans arency'A(O email9getStyle'(9set%gTrans arency'A(O cnt9addCom onent'name(O cnt9addCom onent'email(O addCom onent'%orderLayout9CE$TE0, cnt(O + p"bli Com onent getListCell0endererCom onent'List list, #b7ect +alue, int inde-, boolean isSelected( ) Contact erson P 'Contact( +alueO name9setTe-t'inde- U H) H U erson9get$ame'((O email9setTe-t' erson9getEmail'((O ic9setIcon' erson9get.ic'((O ret"rn thisO + p"bli Com onent getListFocusCom onent'List list( )
Codename One 2012. All rights Reserved. http: !!!."odenameone."om FJ
ret"rn focusO + + String>?>? C#$TACTSRI$F# P ) )H$ir 59H,H$ir95^Sun9C#(H+, )HTidhar &9H,HTidhar9&^Sun9C#(H+, )HIddo A9H,HIddo9A^Sun9C#(H+, )HAri S9H,HAri9S^Sun9C#(H+, )HChen F9H,HChen9F^Sun9C#(H+, )H6oa+ %9H,H6oa+9%^Sun9C#(H+, )H(oshe S9H,H(oshe9S^Sun9C#(H+, )HNeren S9H,HNeren9S^Sun9C#(H+, )HAmit H9H,HAmit9H^Sun9C#(H+, )HAr1ady $9H,HArcadi9$^Sun9C#(H+, )HShai A9H,HShai9A^Sun9C#(H+, )HElina N9H,HElina9N^Sun9C#(H+, )H6ani+ 59H,H6ani+95^Sun9C#(H+, )H$ada+ %9H,H$ada+9%^Sun9C#(H+, )H(artin L9H,H(artin9L^Sun9C#(H+, )HTamir S9H,HTamir9S^Sun9C#(H+, )H$ir S9H,H$ir9S^Sun9C#(H+, )HEran N9H,HEran9N^Sun9C#(H+ +O int contact'idthP 8FO int contactHeightP @IO int cols P @O 0esources images P 0esources9o en'H,images9resH(O Image contacts P images9getImage'H eo le97 gH(O Image>? ersons P new Image>C#$TACTSRI$F#9length?O #or'int i P AO i T ersons9length O iUU() ersons>i? P contacts9subImage''iScols([contact'idth, 'i,cols([contactHeight, contact'idth, contactHeight, tr"e(O + #inal Contact>? contactArray P new Contact> ersons9length?O #or 'int i P AO i T contactArray9lengthO iUU( ) int os P i S C#$TACTSRI$F#9lengthO contactArray>i? P new Contact'C#$TACTSRI$F#> os?>A?, C#$TACTSRI$F#> os?>1?, ersons> os?(O + Form millionList P new Form'H(illionH(O
Codename One 2012. All rights Reserved. http: !!!."odenameone."om BA
millionList9setScrollable'#alse(O List l P new List'new List(odel'( ) pri*ate int selectionO p"bli #b7ect getItemAt'int inde-( ) ret"rn contactArray>inde- S contactArray9length?O + p"bli int getSi/e'( ) ret"rn 1AAAAAAO + p"bli int getSelectedInde-'( ) ret"rn selectionO + p"bli *oid setSelectedInde-'int inde-( ) selection P inde-O + p"bli *oid add2ataChangedListener'2ataChangedListener l( ) + p"bli *oid remo+e2ataChangedListener'2ataChangedListener l( ) + p"bli *oid addSelectionListener'SelectionListener l( ) + p"bli *oid remo+eSelectionListener'SelectionListener l( ) + p"bli *oid addItem'#b7ect item( ) + p"bli *oid remo+eItem'int inde-( ) + +(O l9setListCell0enderer'new Contacts0enderer'((O l9setFi-edSelection'List9FI=E2R$#$ERC6CLIC(O millionList9setLayout'new %orderLayout'((O millionList9addCom onent'%orderLayout9CE$TE0, l(O millionList9sho!'(O
&"ltiList
The (ultiList is a reconfigured list that contains a ready made renderer !ith defaults that ma1e sense for the most common use cases9 It still retains most of the o!er a+ailable to the list com onent but reduces the com le-ity of one of the hardest things to gras for most de+elo ers) rendering9 It still has the full o!er of the model and allo!s you to create a million entry list !ith 7ust a fe! lines of code, ho!e+er the ob7ects the model returns should al!ays be in the form of Hashtables and not any arbitrary ob7ect li1e the standard list allo!s9 6ou can create a (utiList by 7ust dro ing it into lace in the &"I builder and 7ust editing the list data ro erty >see the instructions abo+e for creating a list in the &"I builder, you !onEt need the renderer ortion?9
/lider
A slider is an em ty com onent that can be filled hori/ontally or +ertically to allo! indicating rogress,+olume etc9 It can be editable to allo! the user to determine its +alue or none editable to 7ust relay that information to the user9 It can ha+e a thumb on to to sho! its current osition9
The interesting art about the slider is that it has t!o se arate style "II2Es, Slider & SliderFull9 The Slider "II2 is al!ays ainted and SliderFull is rendered on to based on the amount the slider should be filled9
-able
"nli1e list the table is a com osite com onent, !hich means it is really a subclass of a Container and is effecti+ely built from multi le com onents9 The general thought rocess is that Table is an elaborate com onent and should include com le- editing, !hile the list is more of a selection com onent designed for scalability9 Here is a minor sam le of using the standard table com onent, it should be retty self e- lanatory) #inal Form f P new Form'HTable TestH(O Table(odel model P new 2efaultTable(odel'new String>? )HCol 1H, HCol 3H, HCol 8H+, new #b7ect>?>? ) )H0o! 1H, H0o! AH, H0o! =H+, )H0o! 3H, H0o! %H, H0o! 6H+, )H0o! 8H, H0o! CH, H0o! \H+, )H0o! @H, H0o! 2H, H0o! NH+, +( )
Codename One 2012. All rights Reserved. http: !!!."odenameone."om B3
p"bli boolean isCellEditable'int ro!, int col( ) ret"rn col KP AO + +O Table table P new Table'model(O table9setScrollable='tr"e(O f9setLayout'new %orderLayout'((O f9addCom onent'%orderLayout9CE$TE0, table(O f9sho!'(O Ho!e+er, the more HinterestingH as ect of the table is the table layout and its ability to create rather uni;ue layouts relati+ely easily similarly to HT(LQs tables9 6ou can use the layout constraints >also e- osed in the table class? to create s anning and elaborate "IQs9 In order to customi/e the table cell beha+ior you can no! deri+e the table to create a Hrenderer li1eH !idget, ho!e+er unli1e the list this com onent is H1e tH and used as is9 This means you can bind listeners to this com onent and !or1 !ith it as you !ould !ith any other com onent in Codename #ne9
-ree
A tree allo!s dis laying hierarchical data such as folders and files in a colla sible,e- andable "I9 Li1e the Table it is a Container deri+ed com onent that !or1s against a model to construct its user interface on the fly9 In order for the tree to ha+e content you need to create a tree model e9g9 this) lass StringArrayTree(odel implements Tree(odel ) String>?>? arr P new String>?>? ) )HColorsH, HLettersH, H$umbersH+, )H0edH, H&reenH, H%lueH+, )HAH, H%H, HCH+, )H1H, H3H, H8H+ +O p"bli 5ector getChildren'#b7ect arent( ) i#' arent PP n"ll( ) 5ector + P new 5ector'(O #or'int iter P A O iter T arr>A?9length O iterUU( ) +9addElement'arr>A?>iter?(O + ret"rn +O + 5ector + P new 5ector'(O #or'int iter P A O iter T arr>A?9length O iterUU( ) i#' arent PP arr>A?>iter?( )
Codename One 2012. All rights Reserved. http: !!!."odenameone."om B8
i#'arr9length G iter U 1 && arr>iter U 1? KP n"ll( ) #or'int i P A O i T arr>iter U 1?9length O iUU( ) +9addElement'arr>iter U 1?>i?(O + + + + ret"rn +O + p"bli boolean isLeaf'#b7ect node( ) 5ector + P getChildren'node(O ret"rn + PP n"ll __ +9si/e'( PP AO + + Tree dt P new Tree'new StringArrayTree(odel'((O 'ill result in this)
/hare B"tton
The share button allo!s you to hel your users mar1et your a lication by sharing it !ith their friends easily9 'hen they ress the button they !ill be faced !ith either the nati+e sharing
Codename One 2012. All rights Reserved. http: !!!."odenameone."om B@
ca ability of the latform >as is a+ailable on Android? or a builtin set of sharing features such as faceboo1, email, S(S etc9 6ou can customi/e the button to add additional sharing o tions9
In#inite 5rogress
The infinite rogress indicator s ins an image infinitely, it is automatically associated !ith a default image for infinite rogress from the nati+e theme9 This can be used in se+eral !ays e9g9 you can lace this com onent into a layout to indicate !or1 under!ay9 A useful function in the infinite rogress com onent is the sho!Inifinite%loc1ing>? method !hich modelessly sho!s a translucent dialog !ith the infinite rogress indicator in it9
-abs
Codename One 2012. All rights Reserved. http: !!!."odenameone."om BD
The Tabs com onent allo!s arranging com onents into grou s !ithin containers, its a container ty e that allo!s leafing through its children using labeled buttons9 The tabs can be laced in multi le different !ays >to , bottom, left or right? !ith the default being determined by the latform9 This class also allo!s s!i ing bet!een com onents to leaf bet!een said tabs >for this ur ose the tabs themsel+es can also be hidden?9
&edia5layer
The media layer allo!s you to control +ideo laybac1 e9g9 to sho! a +ideo one can sim ly use something li1e this) #inal (edia.layer m P new (edia.layer'(O try ) m 9set2ataSource'my(ediaFile(O + at h 'I#E-ce tion e-( ) e-9 rintStac1Trace'(O + layer9addCom onent'%orderLayout9CE$TE0, m (O In order to run the media,+ideo in the simulator you !ill need to run a +ersion of <a+a B u date F or ne!er9 'e rely on features that !ere integrated into that +ersion in order to ro+ide ro er +ideo codec su ort9
WebBrowser
The !eb bro!ser com onent sho!s the nati+e de+ice !eb bro!ser !hen su orted by the de+ice and the HT(LCom onent !hen the !eb bro!ser isnEt su orted on the gi+en de+ice9 To create a sim le !eb bro!ser com onent !e can do something li1e this >assuming age9html is resent in the 7ar?)
Codename One 2012. All rights Reserved. http: !!!."odenameone."om BF
'eb%ro!ser !b P new 'eb%ro!ser'(O !b9set"0L'H7ar),,,.age9htmlH(O Ho!e+er, on de+ices !here more elaborate HT(L rendering e-ists !e can also do things such as communicate !ith the HT(L code using <a+aScri t calls >notice that o ening an alert in an embedded nati+e bro!ser might not !or1?9 E9g9 !e can create HT(L li1e this) @html langABenBC @headC @meta harsetAB"t#9DBC @titleCTest@2titleC @s riptC function fnc>message? ` document9!rite>message?O aO @2s riptC @2headC @body C @pC2emo@2pC @2bodyC @2htmlC And then communicate !ith the function from code li1e this) 'eb%ro!ser !eb P new 'eb%ro!ser'() ^#+erride p"bli *oid onLoad'String url( ) Com onent c P getInternal'(O i#'c instan eo# %ro!serCom onent( ) %ro!serCom onent b P '%ro!serCom onent(cO b9e-ecute'Hfnc>QT GHello 'orldT, GQ?H(O + + +O f9addCom onent'%orderLayout9CE$TE0, !eb(O !eb9set"0L'H7ar),,, age9htmlH(O In order to see the nati+e !eb bro!ser in the simulator you !ill need to run using <a+a B u date F or ne!er9
Embedded Container
EmbeddedContainer sol+es a roblem that e-ists only !ithin the &"I builder and the class ma1es no sense outside of the conte-t of the &"I builder9
The necessity for EmbeddedContainer came about due to i.hone ins ired designs that relied on tabs >i.hone style tabs at the bottom of the screen? !here different features of the a lication are !ithin a different tab9 This didnQt mesh !ell !ith the &"I builder na+igation logic and so !e needed to rethin1 some of it9 'e !anted to reuse &"I as much as ossible !hile still en7oying the ad+antage of na+igation being com letely managed for me9 Android does this !ith Acti+ities and the i.hone itself has a +ie! controller, !e donQt li1e both a roaches and thin1 they both suc19 The roblem is that you ha+e !hat is effecti+ely t!o incom atible hierarchies to mi- and match !hich is !hy Android needed to Hin+entH fragments and A le canQt mi- +ie! controllers !ithin a single a lication9 The Com onent,Container heirarchy is o!erful enough to re resent such a "I but !e needed a Hmar1erH to indicate to the "I%uilder !here a HrootH com onent e-ists so na+igation occurs only !ithin the gi+en HrootH9 Here EmbeddedContainer comes into lay, its a sim le container that can only contain another &"I from the &"I builder9 $othing else9 So !e can lace it in any form of "I and effecti+ely ha+e the "I change a ro riately and na+igation !ould default to Hsensible +aluesH9 $a+igation re laces the content of the embedded container, it finds the embedded container based on the com onent that broadcast the e+ent9 If you !ant to na+igate manually 7ust use the sho!Container>? method !hich acce ts a com onent, you can gi+e any com onent that is under the EmbeddedContainer you !ant to re lace and Codename #ne !ill be smart enough to re lace only that com onent9 The nice art about using the EmbeddedContainer is that the resulting "I can be +ery easily refactored to ro+ide a more traditional form based "I !ithout du licating effort and can be easily ada ted to a more tablet oriented "I >!ith a side bar? again !ithout much effort9
The screenshot abo+e !as roduced using the follo!ing code) Form ma P new Form'H(a H(O ma 9setLayout'new %orderLayout'((O ma 9setScrollable'#alse(O #inal (a Com onent mc P new (a Com onent'(O try ) ,,get the current location from the Location A.I Location loc P Location(anager9getLocation(anager'(9getCurrentLocation'(O Coord lastLocation P new Coord'loc9getLatitude'(, loc9getLongtitude'((O Image i P Image9createImage'H,blueR in9 ngH(O .ointsLayer l P new .ointsLayer'(O l9set.ointIcon'i(O .ointLayer P new .ointLayer'lastLocation, H6ou Are HereH, i(O 9set2is lay$ame'tr"e(O l9add.oint' (O mc9addLayer' l(O
Codename One 2012. All rights Reserved. http: !!!."odenameone."om BJ
+ at h 'I#E-ce tion e-( ) e-9 rintStac1Trace'(O + mc9/oomToLayers'(O ma ma ma ma 9addCom onent'%orderLayout9CE$TE0, mc(O 9addCommand'new %ac1Command'((O 9set%ac1Command'new %ac1Command'((O 9sho!'(O
The e-am le belo! sho!s ho! to integrate the (a Com onent !ith the &oogle Location A.I9 ma1e sure to obtain your secret a i 1ey from the &oogle Location data A.I at) htt s),,de+elo ers9google9com,ma s,documentation, laces,
#inal Form ma P new Form'H(a H(O ma 9setLayout'new %orderLayout'((O ma 9setScrollable'#alse(O #inal (a Com onent mc P new (a Com onent'(O Location loc P Location(anager9getLocation(anager'(9getCurrentLocation'(O
Codename One 2012. All rights Reserved. http: !!!."odenameone."om IA
,,use the code from abo+e to sho! you on the ma ut(e#n(a 'mc(O ma 9addCom onent'%orderLayout9CE$TE0, mc(O ma 9addCommand'new %ac1Command'((O ma 9set%ac1Command'new %ac1Command'((O Connection0e;uest re; P new Connection0e;uest'( ) prote ted *oid read0es onse'In utStream in ut( throws I#E-ce tion ) <S#$.arser P new <S#$.arser'(O Hashtable h P 9 arse'new In utStream0eader'in ut((O ,, HstatusH ) H0E:"ESTR2E$IE2H String res onse P 'String(h9get'HstatusH(O i#'res onse9e;uals'H0E:"ESTR2E$IE2H(() System9out9 rintln'Hma1e sure to obtain a 1ey from H U Hhtt s),,de+elo ers9google9com,ma s,documentation, laces,H(O rogress9dis ose'(O 2ialog9sho!'HInfoH, Hma1e sure to obtain an a lication 1ey from H U Hgoogle laces a iQsH , H#1H, n"ll(O ret"rnO + #inal 5ector + P '5ector( h9get'HresultsH(O Image im P Image9createImage'H,redR in9 ngH(O .ointsLayer l P new .ointsLayer'(O l9set.ointIcon'im(O l9addActionListener'new ActionListener'( ) p"bli *oid action.erformed'ActionE+ent e+t( ) .ointLayer P '.ointLayer( e+t9getSource'(O System9out9 rintln'H ressed H U (O 2ialog9sho!'H2etailsH, HH U 9get$ame'(, H#1H, n"ll(O + +(O #or 'int i P AO i T +9si/e'(O iUU( ) Hashtable entry P 'Hashtable( +9elementAt'i(O Hashtable geo P 'Hashtable( entry9get'HgeometryH(O Hashtable loc P 'Hashtable( geo9get'HlocationH(O 2ouble lat P '2ouble( loc9get'HlatH(O
Codename One 2012. All rights Reserved. http: !!!."odenameone."om I1
2ouble lng P '2ouble( loc9get'HlngH(O .ointLayer oint P new .ointLayer'new Coord'lat9double5alue'(, lng9double5alue'((, 'String( entry9get'HnameH(, n"ll(O l9add.oint' oint(O + rogress9dis ose'(O mc9addLayer' l(O ma 9sho!'(O mc9/oomToLayers'(O + +O re;9set"rl'Hhtt s),,ma s9googlea is9com,ma s,a i, lace,search,7sonH(O re;9set.ost'#alse(O re;9addArgument'HlocationH, HH U loc9getLatitude'( U H,H U loc9getLongtitude'((O re;9addArgument'HradiusH, HDAAH(O re;9addArgument'Hty esH, HfoodH(O re;9addArgument'HsensorH, HfalseH(O ,,get your o!n 1ey from htt s),,de+elo ers9google9com,ma s,documentation, laces, ,,and re lace it here9 String 1ey P HyourA.INeyHO re;9addArgument'H1eyH, 1ey(O $et!or1(anager9getInstance'(9addTo:ueue're;(O + at h 'I#E-ce tion e-( ) e-9 rintStac1Trace'(O + +
-ransitions
Transitions allo! us to re lace one com onent !ith another, most ty ically forms or dialogs are re laced !ith a transition ho!e+er a transition can be a lied to re lace any arbitrary com onent9
Codename One 2012. All rights Reserved. http: !!!."odenameone."om I8
2e+elo ers can im lement their o!n custom transition and install it to com onents by deri+ing the transition class, although most commonly the built in CommonTransition class is used for almost e+erything9 6ou can define transitions for forms,dialogs,menus globally either +ia the theme constant or +ia the Loo1AndFeel class9 Alternati+ely you can install a transition on to le+el com onents +ia setter methods9 To a ly a transition to a com onent !e can 7ust use the Container9re lace method as such) Container c P re lace9get.arent'(O ta9set.referredSi/e're lace9get.referredSi/e'((O c9re laceAnd'ait're lace, ta, CommonTransitions9createSlide'CommonTransitions9SLI2ER5E0TICAL, tr"e, DAA((O c9re laceAnd'ait'ta, re lace, CommonTransitions9createSlide'CommonTransitions9SLI2ER5E0TICAL, #alse, DAA((O In addition !e can im lement our o!n transitions, e9g9 the follo!ing code demonstrates an e- losion transition in !hich an e- losion animation is dis layed on e+ery com onent as the e- lode one by one !hile !e mo+e from one screen to the ne-t9
p"bli lass E- losionTransition e4tends Transition ) pri*ate int durationO pri*ate Image>? e- losionsO pri*ate (otion animO pri*ate Class>? classesO pri*ate boolean doneO pri*ate int>? location=O pri*ate int>? location6O pri*ate 5ector com onentsO pri*ate 5ector se;uenceO pri*ate boolean se;uentialO pri*ate int se;LocationO
Codename One 2012. All rights Reserved. http: !!!."odenameone."om I@
p"bli E- losionTransition'int duration, Class>? classes, boolean se;uential( ) this9duration P durationO this9classes P classesO this9se;uential P se;uentialO + p"bli *oid initTransition'( ) try ) e- losions P new Image>? ) Image9createImage'H,e- losion19 ngH(, Image9createImage'H,e- losion39 ngH(, Image9createImage'H,e- losion89 ngH(, Image9createImage'H,e- losion@9 ngH(, Image9createImage'H,e- losionD9 ngH(, Image9createImage'H,e- losionF9 ngH(, Image9createImage'H,e- losionB9 ngH(, Image9createImage'H,e- losionI9 ngH( +O done P #alseO Container c P 'Container(getSource'(O com onents P new 5ector'(O addCom onents#fClasses'c, com onents(O i#'com onents9si/e'( PP A( ) ret"rnO + location= P new int>com onents9si/e'(?O location6 P new int>com onents9si/e'(?O int ! P e- losions>A?9get'idth'(O int h P e- losions>A?9getHeight'(O #or'int iter P A O iter T location=9length O iterUU( ) Com onent current P 'Com onent(com onents9elementAt'iter(O location=>iter? P current9getAbsolute='( U current9get'idth'( , 3 4 ! , 3O location6>iter? P current9getAbsolute6'( U current9getHeight'( , 3 4 h , 3O + i#'se;uential( ) anim P (otion9createS line(otion'A, e- losions9length 4 1, duration , location=9length(O se;uence P new 5ector'(O + else ) anim P (otion9createS line(otion'A, e- losions9length 4 1, duration(O + anim9start'(O + at h 'I#E-ce tion e-( )
Codename One 2012. All rights Reserved. http: !!!."odenameone."om ID
e-9 rintStac1Trace'(O + + pri*ate *oid addCom onents#fClasses'Container c, 5ector result( ) #or'int iter P A O iter T c9getCom onentCount'( O iterUU( ) Com onent current P c9getCom onentAt'iter(O i#'current instan eo# Container( ) addCom onents#fClasses''Container(current, result(O + #or'int ci P A O ci T classes9length O ciUU( ) i#'current9getClass'( PP classes>ci?( ) result9addElement'current(O breakO + + + + p"bli *oid cleanu '( ) s"per9cleanu '(O e- losions P n"llO i#'se;uential( ) com onents P se;uenceO + i#'com onents KP n"ll( ) #or'int iter P A O iter T com onents9si/e'( O iterUU( ) ''Com onent(com onents9elementAt'iter((9set5isible'tr"e(O + com onents9remo+eAllElements'(O + + p"bli Transition co y'( ) ret"rn new E- losionTransition'duration, classes, se;uential(O + p"bli boolean animate'( ) i#'se;uential( ) i#'anim KP n"ll && anim9isFinished'( && com onents9si/e'( G A( ) Com onent c P 'Com onent(com onents9elementAt'A(O com onents9remo+eElementAt'A(O se;uence9addElement'c(O
Codename One 2012. All rights Reserved. http: !!!."odenameone."om IF
c9set5isible'#alse(O i#'com onents9si/e'( G A( ) se;LocationUUO anim9start'(O + ret"rn tr"eO + ret"rn com onents9si/e'( G AO + i#'anim KP n"ll && anim9isFinished'( && Kdone( ) ,, allo!s us to animate the last frame, !e should animate once more !hen ,, finished PP true done P tr"eO ret"rn tr"eO + ret"rn KdoneO + p"bli *oid aint'&ra hics g( ) getSource'(9 aintCom onent'g(O int offset P anim9get5alue'(O i#'se;uential( ) g9dra!Image'e- losions>offset?, location=>se;Location?, location6>se;Location?(O ret"rnO + #or'int iter P A O iter T location=9length O iterUU( ) g9dra!Image'e- losions>offset?, location=>iter?, location6>iter?(O + i#'offset G @( ) #or'int iter P A O iter T com onents9si/e'( O iterUU( ) ''Com onent(com onents9elementAt'iter((9set5isible'#alse(O + + + +
What Is -he EDCodename #ne allo!s de+elo ers to create as many threads as they !ant, ho!e+er in order to interact !ith the Codename #ne user interface com onents a de+elo er must use the E2T9 The E2T is the main thread of Codename #ne, by using 7ust one thread Codename #ne can a+oid com le- synchroni/ation code and focus on sim le functionality that assumes only one thread9 This has huge ad+antages in your code as !ell, you can normally assume that all code !ill occur on a single thread, ho!e+er this also comes !ith a rice999 $ormally, e+ery call you recei+e from Codename #ne !ill occur on the E2T9 E9g9 e+ery e+ent, calls to aint>?, lifecycle calls >start etc9? should all occur on the E2T9 This is retty o!erful, ho!e+er it means that as long as your code is rocessing nothing else can ha en in Codename #ne999 If your code ta1es too long to e-ecute then no ainting or e+ent rocessing !ill occur during that time, so a call to Thread9slee >? !ill actually sto e+erythingK The solution is retty sim le, if you need to erform something that re;uires intensi+e C." you can s a!n a thread, Codename #neEs net!or1ing code automatically s a!ns a se arate thread >see that $et!or1(anager cha ter for more?9 Ho!e+er, !e no! run into a roblem999 Codename #ne assumes all modifications to the "I are erformed on the E2T but !e 7ust s a!ned a se arate thread9 Ho! do !e force our modifications bac1 into the E2T* Codename #ne includes 8 methods in the 2is lay class to hel in these situations) isE2T>?, callSerially>0unnable? & callSeriallyAnd'ait>0unnable?9 isE2T>? is useful for generic code that needs to test !hether the current code is e-ecuting on the E2T9
Codename #ne ro+ides a tool to hel you detect some of these +iolations !ith some ca+eats, it is an im erfect tool9 It might fire Lfalse ositi+esM meaning it might detect a +iolation for erfectly legal code and it might miss some illegal calls9 Ho!e+er, it is a +aluable tool in the rocess of detecting hard to trac1 bugs !hich are sometimes only re roducible on the de+ices >due to race condition beha+ior?9 To acti+ate this tool 7ust select the 2ebug E2T menu o tion in the simulator and ic1 the le+el of out ut you !ish to recei+e)
Full out ut !ill include stac1 traces to the area in the code that is sus ected in the +iolation9
+ +(O This allo!s code to lea+e the E2T and then later on return to it to erform things !ithin the E2T9 The callSeriallyAnd'ait>0unnable? method bloc1s the current thread until the method com letes, this is useful for cases such as user notification e9g9) ,, this code is e-ecuting in a se arate thread methodThatTa1esALongTime'(O 2is lay9getInstance'(9callSeriallyAnd'ait'new 0unnable'( ) p"bli *oid run'( ) ,, this occurs on the E2T so I can ma1e changes to "I com onents globalFlag P 2ialog9sho!'HAre 6ou Sure*H, H2o you !ant to continue*H, HContinueH, HSto H(O + +(O ,, this code is e-ecuting the se arate thread ,, global flag !as already set by the call abo+e i#'KglobalFlag( ) ret"rnO + other(ethod'(O It sometimes ma1es sense to in+o1e callSerially >but not call serially and !ait? on the E2T9 'e sometimes !ant to ost one an action to the ne-t cycle of the E2T loo , but that is a rare occurrence9
,, as1 !hat !ent !rong999 + + $otice that the dialog sho! method !ill bloc1 the calling thread until the user clic1s #N or $ot #N999 If you read a bit about Codename #ne you !ould notice that !e are bloc1ing the E2T >E+ent 2is atch Thread? !hich is also res onsible for ainting, ho! does the dialog aint itself or handle e+ents* The secret is in+o1eAnd%loc1, it allo!s us to Hbloc1H the E2T and resume it !hile 1ee ing a HnestedH E2T functioning9 The semantics of this logic are a bit hairy so I !onQt try to e- lain them further, this functionality is also a+ailable in S!ing !hich has the e-act same modality feature ho!e+er S!ing doesnQt e- ose the HengineH to de+elo ers9 Fo-trot, e- oses this undocumented engine to S!ing de+elo ers, in Codename #ne !e chose to e- ose the ability to bloc1 the E2T >!ithout HreallyH bloc1ing it? as a sim le A.I) in+o1eAnd%loc19 The best !ay to e- lain this is by e-am le) p"bli *oid action.erformed'ActionE+ent e+( ) label9setTe-t'HInitiating I#, lease !ait999H(O 2is lay9getInstance'(9in+o1eAnd%loc1'new 0unnable'( ) p"bli *oid run'( ) ,, erform I# o eration999 + +(O label9setTe-t'HI# com letedKH(O ,, u date "I999 + $otice that the beha+ior here is similar to the modal dialog, in+o1eAnd%loc1 Hbloc1edH the current thread des ite the fact that it is the E2T and erformed the run>? method in a se arate thread9 'hen run>? com letes the E2T is resumed9 All the !hile re aints and e+ents occur as usual, you can ha+e in+o1eAnd%loc1 calls occurring !hile another in+o1eAnd%loc1 is still ending there are no limitations here although !e !ould recommend against it since in+o1eAnd%loc1 does carry some o+erhead9 As you can see this is a +ery sim le a roach for thread rogramming in "I, you donQt need to bloc1 your flo! and trac1 the "I thread9 6ou can 7ust rogram in a !ay that seems se;uential >to to bottom? but really uses multi4threading correctly !ithout bloc1ing the E2T9
&oneti6ation
Codename #ne tries to ma1e the li+es of soft!are de+elo ers easier by integrating se+eral forms of builtin moneti/ation solutions such as ad net!or1 su ort, in4a 4 urchase etc9 The Codename #ne integration is only a licable !hen de+elo ing the a lication, the actual integration is a matter of runtime relationshi !ith the ser+ice ro+ider19
0d Networks
*ser*
The +ser+ ad net!or1 ro+ides a uni;ue ro osition !here ads are dis layed in full screen before during and sometimes after a lication e-ecution9 The biggest feature !ithin +ser+ is its ability to seamlessly integrate !ith an e-isting a lication and ro+ide +alue to the de+elo ers !ithout changing a single line of a lication code9
To Clarify) all ayment and financial transactions go through the moneti/ation ro+ider and not through Codename #ne9 E9g9 Ad net!or1 re+enue is the ro erty of the de+elo er and Codename #ne doesnEt ta1e any cut from the de+elo ersK Codename One 2012. All rights Reserved. http: !!!."odenameone."om J3
Codename #ne ro+ides dee integration !ith this uni;ue ad net!or1 the the I2E lugin !here de+elo ers can in ut their +ser+ \one Id >login to +ser+ to ac;uire a /one Id?9 Setting the /one I2 to an em ty string disables +ser+ ads, /one I2 F31F is useful for debugging ur oses9 The transition ad timeout indicates the amount of time to !ait before ushing an ad bet!een transitions in milliseconds9 6ou can set it to a +ery large number to disable that functionality9 The other ro erties are entirely o tional and allo! +ser+ to better target its ads to different a lication needs9
Innera ti*e
To integrate Inneracti+e banner adQs lease register first using htt ),,console9inner4 acti+e9com,iam , ublisher,register*refRidPaffiliateRCodename#ne9 #nce registered you !ill be able to create an a associate ads !ith your account9 lication id !ith !hich you !ill be able to
To initiate the inneracti+e ads you !ill need to enter the follo!ing line in your a init>#b7ect? or start>? method) AdsSer+ice9setAds.ro+ider>InnerActi+e9class?O
lication
From here on you can 7ust use the standard Codename #ne Ads Com onent and lace it as you !ish !ithin the "I or drag it into lace !ithin the &"I builder9 The Ads Com onent has multi le ro erties you can set to indicate your acti+ity but the most im ortant one is the setA I2>? attribute >a Id in the &"I builder? !ith !hich you can determine the a lication that !ill recei+e the ayouts for the ads9
#nce the roduct is urchased you recei+e an e+ent that the urchase !as com leted and you can act a ro riately9 #n the other hand mobile ayments are 7ust a transfer of a sum of money9 %oth &oogleEs and A leEs stores rohibit the sale of hysical goods +ia the stores, so a mobile ayment system needs to be used for those cases9 This is !here the similarity ends bet!een the &oogle & A le a roach9 &oogle e- ects de+elo ers to build their o!n storefront and ro+ides de+elo ers !ith an A.I to e-tract the data in order to construct said storefront9 A le e- ects the de+elo ers to o en its storefront to erform e+erything9 'e tried to encode all 8 a roaches into the urchase A.I !hich means you !ould need to handle all 8 cases !hen !or1ing9 "nfortunately these things are +ery hard to simulate and can only be ro erly tested on the de+ice9 So to organi/e the abo+e !e ha+e) 19 (anaged ayments 4 ayments are handled by the latform9 'e essentially buy an item not transfer money >in a urchase?9 39 (anual ayments 4 !e transfer money, there are no items in+ol+ed9 #inal 5"r hase p A 5"r hase:getIn0pp5"r hase'(E i#'p %A n"ll( ) i#'p:is&an"al5ayment/"pported'(( ) p"r haseDemo:addComponent'new Label'B&an"al 5ayment &odeB((E #inal -e4t3ield t# A new -e4t3ield'BFGGB(E t#:setHint'B/end "s money. thanksB(E B"tton send&oney A new B"tton'B/end Us &oneyB(E send&oney:add0 tionListener'new 0 tionListener'( ) p"bli *oid a tion5er#ormed'0 tionE*ent e*t( ) p:pay'Do"ble:parseDo"ble't#:get-e4t'((. BU/DB(E + +(E p"r haseDemo:addComponent't#(E p"r haseDemo:addComponent'send&oney(E + i#'p:is&anaged5ayment/"pported'(( ) p"r haseDemo:addComponent'new Label'B&anaged 5ayment &odeB((E #or'int iter A G E iter @ I-E&HN0&E/:length E iterII( ) B"tton b"y A new B"tton'I-E&HN0&E/>iter?(E #inal /tring id A I-E&HID/>iter?E b"y:add0 tionListener'new 0 tionListener'( ) p"bli *oid a tion5er#ormed'0 tionE*ent e*t( ) p:p"r hase'id(E +
Codename One 2012. All rights Reserved. http: !!!."odenameone."om J@
+(E p"r haseDemo:addComponent'b"y(E + + + else ) p"r haseDemo:addComponent'new Label'B5ayment "ns"pported on this de*i eB((E + The item names in the demo code abo+e should be hard coded and added to the a ro riate stores in+entory9 'hich is a +ery latform s ecific rocess for iTunes and &oogle lay9 #nce this is done you should be able to issue a urchase re;uest either in the real or the sandbostore9
Container has a glass ane method called aint&lass>&ra hics?, !hich can be o+erridden to ro+ide a similar effect on a Container le+el9 This is es ecially useful for com le- containers such as Table !hich dra!s its lines using such a methodology9 %ac1ground ainter 4 the bac1ground ainter is installed +ia the style, by default Codename installs a custom bac1ground ainter of its o!n9 Installing a custom ainter allo!s a de+elo er to com letely define ho! the bac1ground of the com onent is dra!n9
A aint method can be im lemented by deri+ing a Form as such) p"bli (yForm ) p"bli *oid aint'&ra hics g( ) ,, red color g9setColor'A-ffAAAA(O ,, aint the screen in red g9fill0ect'get='(, get6'(, get'idth'(, getHeight'((O ,, dra! hi !orld in !hite te-t at the to left corner of the screen g9setColor'A-ffffff(O g9dra!String'LHi 'orldM, get='(, get6'((O + +
Images
Codename #ne has ;uite a fe! image ty es) loaded, 0&% >builtin?, 0&% >Codename #ne?, (utable, EncodedImage,S5&, (ulti4Image & Timeline9 There are also FileEncodedImage, FileEncodedImageAsync, StorageEncodedImage,Async !hich !ill be co+ered in the I# section9 Here are the ros,cons and logic behind e+ery image ty e and ho! its created) C Loaded Image 4 this is the basic image you get !hen loading an image from the 7ar or net!or1 using Image9createImage>String?,Image9createImage>In utStream?,Image9createImage>byteXY, int, int?9 In some latforms >e9g9 (I2.? calling get&ra hics>? on an image li1e this !ill thro! an e-ce tion >its immutable in (I2. terms?, this is true for almost all other images as !ell9 This restriction might not a ly for all latforms9 The image is encoded based on de+ice logic and should be reasonably efficient9 0&% Image >internal? 4 close cousin of the loaded image9 This image is created using the method Image9createImage>intXY, int, int? and recei+es A0&% data forming the image9
Codename One 2012. All rights Reserved. http: !!!."odenameone."om JB
It is usually >although not al!ays? a high color image9 Its more efficient than the Codename #ne 0&% image but canQt be modified, at least not on the i-el le+el9 C 0&%Image >Codenme #ne? 4 constructed +ia the 0&%Image constructors this image is effecti+ely an A0&% array that can be dra!n by Codename #ne9 #n many latforms this is ;uite inefficient but for some i-el le+el mani ulations there is 7ust no other !ay9 EncodedImage 4 created +ia the encoded image static methods, the encoded image is effecti+ely a loaded image that is HhiddenH9 'hen creating an encoded image only the .$& >or 7 eg etc9? is loaded to an array in 0A(9 $ormally such images are +ery small relati+ely so they can be 1e t in memory !ithout much effect9 'hen image information is needed >e9g9 i-els, dimension etc9? the image is decoded into 0A( and 1e t in a !ea1,sort reference9 This allo!s the image to be cached for erformance and allo!s the garbage collector to reclaim it !hen the memory becomes scarce9 Encoded image is not final and can be deri+ed to roduce com le- image fetching strategies such as la/ily loading an image from the filesystem >read more about it in the I# section?9 S5& 4 S5&Qs can be loaded directly +ia Image9createS5&>? if Image9isS5&Su orted>? returns true9 'hen adding S5&Qs +ia the Codename #ne 2esigner fallbac1 images are roduced for de+ices that do not su ort S5&9 The fallbac1 images are effecti+ely multi4 images9 (ulti4Image 4 The multi4image is seamless to de+elo ers it is strictly a design time feature, during runtime an EncodedImage is returned !hene+er a multi4image is used9 In the Codename #ne 2esigner one can add se+eral images based on the 2.I of the de+ice >one of se+eral redefined ranges?9 'hen loading the resource file irrele+ant images are s1i ed thus sa+ing the additional memory9 (ulti4images are ideal for icons or small artifacts that are hard to scale ro erly9 They are not meant to re lace things such as J4image borders etc9 since ada ting them to e+ery resolution or to de+ice rotation isnQt ractical9 J4image borders use multi4images by default internally to 1ee their a earance more refined on the different 2.IEs9 Timeline 4 TimelineQs allo! rudimentary animation and enable &IF im orting using the Codename #ne 2esigner9 Effecti+ely a timeline is a set of images that can be mo+ed rotated, scaled & blended to ro+ide interesting animation effects9 It can be created manually using the Timeline class9
All image ty es are mostly seamless to use and !ill 7ust !or1 !ith dra!Image and +arious image related image A.IQs for the most art !ith ca+eats on erformance etc9 For animation images the code must in+o1e images animate>? method >this is done automatically by
Codename One 2012. All rights Reserved. http: !!!."odenameone."om JI
Codename #ne !hen lacing the image as a bac1ground or as an iconK 6ou only need to do it if you in+o1e dra!Image in code rather than use a builtin com onent?9 All images might also be animated in theory e9g9 my gif im lementation returned animated gifs from the standard Loaded Image methods and this !or1ed retty seamlessly >since IconsQs and bac1grounds 7ust !or1?9 To find out if an image is animated you need to use the isAnimation>? method, currently S5& images are animated in (I2. but most of our orts donQt su ort &IF animations by default >although it should be easy to add to some of them?9 .erformance and memory !ise you should read the abo+e carefully and be a!are of the image ty es you use9 The Codename #ne designer tries to conser+e memory and be Hcle+erH by using only encoded images, !hile these are great for lo! memory they are not as efficient as loaded images in terms of s eed9 Also !hen scaled these images ha+e much larger o+erhead since they need to be con+erted to 0&%, scaled and then a ne! image is created9 Nee ing all these things in mind !hen o timi/ing a s ecific "I is +ery im ortant9
!lass 5ane
The &lass.ane in Codename #ne is ins ired by the S!ing &lass.ane & layered ane !ith ;uite a fe! t!ists9 'e tried to imagine ho! S!ing de+elo ers !ould ha+e im lemented the glass ane 1no!ing !hat they do no! about ainters and S!ings learning cur+e9 %ut IQm getting ahead of myself, !hat is the glass ane* A ty ical Codename #ne a lication is essentially com osed of 8 layers >this is a gross sim lification though?, the bg ainters are res onsible for dra!ing the bac1ground of all com onents including the main form9 The com onent dra!s its o!n content !hich might o+errule the ainter and the glass ane aints last999 Essentially the glass ane is a ainter that allo!s us to dra! an o+erlay on to of the Codename #ne a lication9 Initially !e didnQt thin1 !e need a glass ane, !e used to suggest that eo le should o+erride the formQs aint>? method to reach the same result9 Feel free to try and guess !hy this failed before reading the e- lanation in the ne-t aragra h9 #+erriding the aint method of a form !or1ed initially, !hen you enter a form this beha+es 7ust as you !ould e- ect9 Ho!e+er, !hen modifying an element !ithin the form only that element gets re ainted not the entire formK So if I had a form !ith a %utton and te-t dra!n on to using the FormQs aint method it !ould get erased !hene+er the button got focus9 Thats good for the forms aint method, calling the forms aint method !ould be 0EALL6 e- ensi+e for e+ery little thing that occurs in Codename #ne9 Ho!e+er, !e do !ant o+erlays for some things and !e donQt need to re aint e+ery com onent in the screen to get them9 The glass ane is called !hene+er a com onent gets ainted, it only aints !ithin the cli ing region of the com onent hence it !onQt brea1 the rest of the glass ane9
Codename One 2012. All rights Reserved. http: !!!."odenameone."om JJ
The ainter chain is a tool that allo!s us to chain se+eral ainters together to erform different logistical tas1s such as a +alidation ainter cou led !ith a fade out ainter9 The sam le belo! sho!s a crude +alidation anel that allo!s us to dra! error icons ne-t to com onents !hile e-ceeding their hysical bounds as is common in many user interfaces p"bli lass 5alidation.ane implements .ainter ) pri*ate 5ector com onents P new 5ector'(O pri*ate stati Image errorO p"bli 5alidation.ane'Form arentForm( ) try ) i#'error PP n"ll( ) error P Image9createImage'H,error9 ngH(O + + at h 'I#E-ce tion e-( ) e-9 rintStac1Trace'(O + .ainterChain9install&lass.ane' arentForm, this(O + p"bli *oid aint'&ra hics g, 0ectangle rect( ) #or'int iter P A O iter T com onents9si/e'( O iterUU( ) Com onent c P 'Com onent( com onents9elementAt'iter(O i#'c PP n"ll( ) com onents9remo+eElementAt'iter(O ontin"eO + #b7ect P c9getClient.ro erty'5ALI2ATI#$R.0#.(O int - P c9getAbsolute='(O int y P c9getAbsolute6'(O - 4P error9get'idth'( , 3O y UP c9getHeight'( 4 error9getHeight'( , 3O g9dra!Image'error, -, y(O + + p"bli *oid addIn+alid'Com onent c( ) com onents9addElement'c(O + p"bli *oid remo+eIn+alid'Com onent c( ) com onents9remo+eElement'c(O +
Codename One 2012. All rights Reserved. http: !!!."odenameone."om 1AA
E4ternali6able Ob$e ts
Codename #ne ro+ides the e-ternali/able interface !hich is similar to the <a+a SE e-ternali/able interface9 This interface allo!s an ob7ect to declare itself as e-ternali/able for seriali/ation >so an ob7ect can be stored in a file,storage or sent o+er the net!or1?9 Ho!e+er, due to the lac1 of reflection and use of obfuscation these ob7ects must be registered !ith the "til class9 Codename #ne !ill robably ne+er su ort the <a+a SE Seriali/ation A.I due to the si/e issues and com le-ities related to obfuscation9 The ma7or ob7ects used by Codename #ne are e-ternali/able by default) String, 5ector, Hashtable, Integer, 2ouble, Float, %yte, Short, Long, Character, %oolean, #b7ectXY, byteXY, intXY, floatXY, longXY, doubleXY9 E-ternali/ing an ob7ect such as h belo! should !or1 7ust fine) Hashtable h P new Hashtable'(O h9 ut'HHiH,H'orldH(O h9 ut'HdataH, new byte>? )999+(O Ho!e+er, notice that some things arenEt olymor hic e9g9 if I !ill e-ternali/e a String array I !ill get bac1 an #b7ect array since String arrays arenEt su orted9 So im lementing the E-ternali/able interface is only im ortant !hen !e !ant to store a ro rietary ob7ect9 In this case !e must register the ob7ect !ith the com9codename19io9"til class so the e-ternali/ation algorithm !ill be able to recogni/e it by name by in+o1ing) "til9register'H(yClassH, (yClass9 lass(O A e-ternali/able ob7ects must ha+e a default ublic constructor and must im lement the follo!ing @ methods) p"bli int get5ersion'(O p"bli *oid e-ternali/e'2ata#ut utStream out( throws I#E-ce tionO p"bli *oid internali/e'int +ersion, 2ataIn utStream in( throws I#E-ce tionO p"bli String get#b7ectId'(O The +ersion 7ust returns the current +ersion of the ob7ect allo!ing the algorithm to change in the future >the +ersion is then assed !hen internali/ing the ob7ect?9 The ob7ect id is a String
Codename One 2012. All rights Reserved. http: !!!."odenameone."om 1A3
uni;uely re resenting the ob7ect, it usually corres onds to the class name >in the e-am le abo+e the "ni;ue $ame should be (yClass?9 2e+elo ers need to !rite the data of the ob7ect in the e-ternali/e method using the methods in the data out ut stream and read the data of the ob7ect in the internali/e method e9g9) p"bli *oid e-ternali/e'2ata#ut utStream out( throws I#E-ce tion ) out9!rite"TF'name(O i#'+alue KP n"ll( ) out9!rite%oolean'tr"e(O out9!rite"TF'+alue(O + else ) out9!rite%oolean'#alse(O + i#'domain KP n"ll( ) out9!rite%oolean'tr"e(O out9!rite"TF'domain(O + else ) out9!rite%oolean'#alse(O + out9!riteLong'e- ires(O + p"bli *oid internali/e'int +ersion, 2ataIn utStream in( throws I#E-ce tion ) name P in9read"TF'(O i#'in9read%oolean'(( ) +alue P in9read"TF'(O + i#'in9read%oolean'(( ) domain P in9read"TF'(O + e- ires P in9readLong'(O +
A file system can s an o+er an S2 card area and has a hierarchy,rules9 $ot all hones su a L ro erM file system e9g9 the i.hone doesnEt !or1 !ell !ith such ste ing outside of the a lications bo-ed area9 'hen in doubt !e al!ays recommend using Storage !hich is sim ler9
ort
/torage
Storage is accessed +ia the com9codename19io9Storage class9 It is not a hierarchy and contains the ability to list,delete and !rite to named storage entries9 The Storage A.I also ro+ides con+enient methods to !rite ob7ects to Storage and read them from Storage s ecifically read#b7ect & !rite#b7ect9
3ile /ystem
The file system is accessed +ia the com9codename19io9FileSystemStorage class9 It ma s to the underlying #SEs file system A.I ro+iding all the common o erations on a file name from o ening to renaming and deleting9 $otice that the file system A.I is some!hat latform s ecific in its beha+ior, all aths used the A.I should be absolute other!ise they are not guaranteed to !or19
Clo"d /torage
$otice) the cloud storage is a remium aid ser+ice9 Codename #ne offers a free ;uota for all de+elo ers using its latform9 Cloud storage is an A.I that allo!s us to ersist ob7ects into Codename #neEs cloud ser+ers hosted by the &oogle A Engine9 This guarantees high reliability and s eed, it also im lies some constraints9 Cloud ob7ects are stored using a distributed ob7ect database, donEt thin1 of them as you !ould of tables or ty ical S:L li1e storage since they are bac1ed by &oogleEs big table A.I9 Each cloud ob7ect is +ery much li1e a (a allo!ing set,get o erations on ro erties9 An ob7ect can ha+e a ty e associated !ith it as !ell as a +isibility sco e for the !orld9 A sim le e-am le might be in order) Cloud#b7ect ob7 P new Cloud#b7ect'H(y#b7ectH, Cloud#b7ect9ACCESSR."%LICR0EA2R#$L6(O ob79setString'Ht-tH, title9getTe-t'((O ob79setInde-String'1, title9getTe-t'((O CloudStorage9getInstance'(9sa+e'ob7(O int result P CloudStorage9getInstance'(9commit'(O i#'result KP CloudStorage90ET"0$RC#2ERS"CCESS( )
Codename One 2012. All rights Reserved. http: !!!."odenameone."om 1A@
2ialog9sho!'HCloud ErrorH, HError H U result, H#NH, n"ll(O + As you can see, the code abo+e creates and stores a cloud ob7ect, there are se+eral things to notice about the e-am le abo+e) 19 Cloud ob7ect is a s ecific Codename #ne ty e, you cannot store arbitrary ob7ects9 39 5alues can be anything 89 'e can define ob7ect +isibility sco e @9 There is a s ecial inde- column D9 Sa+e doesnEt actually send data to the ser+er F9 Commit is synchronous !hich means !e 1no! !hether the commit succeeded in the ne-t line9 Lets go o+er this line by line) Cloud#b7ect ob7 P new Cloud#b7ect'H(y#b7ectH, Cloud#b7ect9ACCESSR."%LICR0EA2R#$L6(O Here !e create a ne! cloud ob7ect, !e gi+e it a ty e >sort of li1e a class?9 $otice that ro erties !e store into the ob7ect can be anything and donEt ha+e to be identical for ob7ects that ha+e the same ty e, this is mostly for your con+enience as de+elo ers9 Then !e gi+e the ob7ect its +isibility sco e, !hen the +isibility is defined you !ill only be able to !or1 !ith an ob7ect that is !ithin your sco e9 Cloud ob7ects ha+e D le+els of +isibility) C ACCESSR."%LIC 4 A !orld +isible,modifiable ob7ectK C ACCESSR."%LICR0EA2R#$L6 4 A !orld +isible ob7ectK Can only be modified by its creator9 C ACCESSRA..LICATI#$ 4 An a lication +isible,modifiable ob7ectK C ACCESSRA..LICATI#$R0EA2R#$L6 4 An a lication sco e readable ob7ectK Can only be modified by its creator C ACCESSR.0I5ATE 4 An ob7ect that can only be +ie!ed or modified by its creator 'hen creating an ob7ect you determine its sco e and once the sco e is assigned it cannot be modified, you !ill need to create a ne! ob7ect to do so9 'hen ;uerying you can only ;uery one sco e >more on that later?9 A lication sco e is determined by your a lication ac1age and de+elo er email, since these are entirely uni;ue and canEt be occu ied by another de+elo er you are safe to assume that only your a lications ha+e access to that data9 Ho!e+er, since this data is +isible it isnEt hac1er safe9 Any sensiti+e data should be ass!ord rotected9 Some of the sco es re;uire a user identity in order to modify or access an ob7ect, a uni;ue user is automatically created !hen logging into an a lication9 Ho!e+er, you can login e- licitly !ith a s ecific user by using the Cloud.ersona A.I9 E9g9) Cloud.ersona9createFromTo1en>String?O The creatFromTo1en method initiali/es the ersona based on a to1en, since this method assumes binary transfer of a com leted to1en the to1en isnQt +erified in any !ay and the user is
Codename One 2012. All rights Reserved. http: !!!."odenameone."om 1AD
considered logged in9 The idea here is that !hen a user logs in using some other means >e9g9 Faceboo1?, identifying information e9g9 the users email can be used as a Lto1enM9 That !ay !hen a user logs in from another de+ice the same to1en >email? !ould be used and he !ould ha+e the same ob7ects +isible to him on both de+ices9 A user doesnEt ha+e to be a single erson, it can be a cor oration identity or any such grou thus allo!ing the !hole grou to share a single to1en to get access to the ri+ate sco e together9 ob79setString'Ht-tH, title9getTe-t'((O Here !e see a string being laced into the ob7ect store, you can lace Strings and numbers into the ob7ect store but not too much data9 String length is limited to DAA bytes and ob7ects canEt be too large or you !ill get a ser+er failure9 'e suggest staying !ell belo! the 1AA1b mar19 To store large files you !ill need to use the filestore A.I !hich !ill be e- lained bello!9 ob79setInde-String'1, title9getTe-t'((O :uerying in an ob7ect datastore is retty difficult, since you can define a ro erty to be almost anything, !e also !ant the ;ueries to be 0EALL6 fast e+en on stores containing more than 1 million entries9 To accom lish both goals !e created 1A inde- entries in the ob7ect store >from 1 to 1A? into !hich you can ut any arbitrary data that you can ;uery or sort9 E9g9 say you ha+e an entity such as) Cloud#b7ect o P 999O o9setString'Hfirst$ameH, first(O o9setString'HsurnameH, last(O And you !ould li1e to sort them in a case insensiti+e !ay based on first$ame4last$ame and by last$ame4first$ame9 To do this you !ill need to create t!o inde-es) o9setInde-String'1, 'first U H H U last(9toLo!erCase'((O o9setInde-String'3, 'last U H H U first(9toLo!erCase'((O This !ill allo! you to order your res onses either based on the first or the second inde-9 This is a bit difficult but it guarantees ridiculously fast ;ueries since e+ery ;uery is effecti+ely an ob7ect loo1u 9 CloudStorage9getInstance'(9sa+e'ob7(O The cloud storage class is the singleton that allo!s you to sa+e, delete, ;uery and refresh your ob7ects9 int result P CloudStorage9getInstance'(9commit'(O (ost modification o erations arenEt sent to the ser+er immediately, they should be committed or rolled bac1 !hich can be done synchronously on the E2T or asynchronously9 Commit returns a ser+er res onse !hich can indicate the ty e of failure if a failure has occurred9
2o not mista1e commit,rollbac1 to S:L ty e transactions, unli1e S:L art of the o eration can succeed !hile another art can fail, the commit command allo!s you to batch se+eral o erations into a single ordered ser+er re;uest !hich is more erformant than sending multi le small re;uests9 A cou le of other things !e should 1ee in mind) C E+ery ob7ect has a modification date !hich is tested against the ser+er timestam 9 This re+ents t!o users,de+ices from changing a cloud ob7ect concurrently9 C E+ery ob7ect has a uni;ue I2 String identifying it, you can instantly access any ob7ect +ia that CloudId 'e can no! fetch the data !e committed) Cloud#b7ect>? ob7ects P CloudStorage9getInstance'(9;uerySorted'H(y#b7ectH, 1, tr"e, A, 1A, Cloud#b7ect9ACCESSR."%LICR0EA2R#$L6(O $otice that this ;uery is synchronous >there is an asynchronous +ersion of this ;uery as !ell?, its functionality is relati+ely sim le though9 It searches for ob7ects of ty e (y#b7ect and returns them sorted in ascending order >the true argument? based on inde- number 19 It only returns the first 1A ob7ects >start offset A and destination 1A? and only searches the ublic read only sco e9 #nce fetched you can modify,sa+e the ob7ects and commit them9 This can be further sim lified by binding a user interface directly to a Cloud #b7ect using our Cloud %indc feature9 To bind a com onent "I tree created in the &"I builder use the follo!ing) Cloud#b7ect ob7ectTo%ind P VO ob7ectTo%ind9bindTree'form, Cloud#b7ect9%I$2I$&RI((E2IATE, tr"e(O There are se+eral things ha ening here9 The "I is assumed to ha+e names associated !ith the rele+ant com onents, these names are used as the 1eys for the Cloud #b7ectEs created9 The last argument indicates !hether the "I should get the initial +alues for the entries from the cloud ob7ect or +isa +ersa >true means the Cloud #b7ect determines initial +alues?9 The binding o tions in bet!een has 8 different le+els) C %I$2I$&R2EFE00E2 4 Changes to the bound ro erty !onQt be reflected into the bound cloud ob7ect until commit binding is in+o1ed9 C %I$2I$&RI((E2IATE 4 Changes to the bound ro erty !ill be reflected instantly into the cloud ob7ect C %I$2I$&RA"T#RSA5E 4 Changes to the bound ro erty !ill be reflected instantly into the cloud ob7ect and the ob7ect !ould be sa+ed immediately >not committedK?9 These 8 essentially match ty ical "I use cases9 2eferred binding is great for "I that has a LcancelM o tion, if the user resses cancel you donEt ha+e to do anything >although you can in+o1e cancel%inding>? to cleanu ?9 If the user resses sa+e you !ill need to in+o1e the method
Codename One 2012. All rights Reserved. http: !!!."odenameone."om 1AB
commit%inding>? and your changes !ill be a lied >but not sa+ed or committed des ite the name?9 %inding immediate changes the cloud ob7ect instantly !hich is great for "IEs that donEt ha+e a sa+e o tion >as is common on mobile de+ices and the (ac?9 The same is true for the last o tion only it goes further and in+o1es sa+e for you9 It still doesnEt in+o1e commit !hich you !ill ha+e to do at some oint9
/JL
(ost ne!er de+ices contain one +ersion of s;lite or another, s;lite is a +ery light!eight S:L database designed for embedding into de+ices9 For ortability we re ommend a*oiding /JL altogether since it is both fragmented bet!een de+ices >different s;lite +ersions? and isnEt su orted on other de+ices9 In general S:L seems o+erly com le- for most embedded de+ice rogramming tas1s9 If you !ish to use S:L and are !illing to !or1 around the limitations 7ust use 2atabase db P 2is lay9getInstance'(9o en#rCreate'Ldatabase$ameM(O $otice that db !ill be null if the S:L A.I isnEt su orted on the gi+en latform9 6ou can in+o1e standard ;ueries on the database and tra+erse it using a Cursor ob7ect9
Currently Codename #ne only su orts htt ,htt s connections due to limitations inherent in many de+ices,net!or1 o erator bac1ends9 To o en a connection one needs to use a Connection0e;uest ob7ect !hich has some similarities to the net!or1ing mechanism in <a+aScri t but is ob+iously some!hat more elaborate9 To send a get re;uest to a "0L one erforms something li1e) Connection0e;uest re;uest P new Connection0e;uest'(O re;uest9set"rl'url(O re;uest9set.ost'#alse(O re;uest9setContentTy e'contentTy e(O re;uest9add0e;uestHeader'header$ame, header5alue(O re;uestElement9addArgument' arameter, +alue(O re;uest9add0es onseListener'new ActionListener'( ) p"bli *oid action.erformed'ActionE+ent e+( ) $et!or1E+ent e P '$et!or1E+ent(e+O ,, V rocess the res onse + +(O ,, re;uest !ill be handled asynchronously $et!or1(anager9addTo:ueue're;uest(O $otice that you can also im lement the same thing and much more by a+oiding the res onse listener code and instead o+erriding the methods of the Connection0e;uest class !hich offers multi le oints to o+erride e9g9 Connection0e;uest re;uest P new Connection0e;uest'( ) prote ted *oid read0es onse'In utStream in ut( ) ,, 7ust read from the res onse in ut stream + prote ted *oid ost0es onse'( ) ,, in+o1ed on the E2T after rocessing is com lete to allo! the net!or1ing code ,, to u date the "I + prote ted *oid build0e;uest%ody'#ut utStream os( ) ,, !rites ost data, by default this L7ust !or1sM but if you !ant to !rite this ,, manually then o+erride this + +O
Codename #ne includes a $et!or1 (onitor tool !hich you can access +ia the file menu of the simulator, this tool reflects all the re;uests made through the connection re;uests and echos them all9 Allo!ing you to trac1 issues in your code,!eb ser+ice and see e+erything Lgoing through the !ireM9 This is a remar1ably useful tool for o timi/ing and for figuring out !hat e-actly is ha ening !ith your ser+er connection logic9
Network /er*i es
Codename #ne shi s !ith a fe! default bindings for common net!or1 ser+ices such as do!nloading and caching images locally & 0SS9 6ou can find out more about these ser+ices in the ser+ices ac1age9
For a roduction a lication you can use Log90E.#0TI$&R.0#2"CTI#$ !hich !ill only email the log on e-ce tion9 Codename #ne also su orts a crashR rotection) true build arameter9 Ho!e+er, this argument causes significant erformance o+erhead at the moment and is only recommended during de+elo ment time9 It allo!s de+elo ers to recei+e a stac1 trace for crashes and in logging9 Ho!e+er, the stac1 traces are only limited to the Codename #ne and de+elo er classes and donEt a ly to o erating system classes9
The <S#$ H<a+a Scri t #b7ect $otationH format is o ular on the !eb for assing +alues to,from !ebser+ices since it !or1s so !ell !ith <a+aScri t9 .arsing <S#$ is 7ust as easy but has t!o different +ariations9 6ou can use the <S#$.arser class to build a tree of the <S#$ data as such) <S#$.arser arser P new <S#$.arser'(O Hashtable res onse P arser9 arse'reader(O The res onse is a Hashtable containing a nested hierarchy of 5ectors, Strings and numbers to re resent the content of the submitted <S#$9 To e-tract the data from a s ecific ath 7ust iterate the Hashtable 1eys and recurs into it9 $otice that there is a !ebser+ices demo as art of the 1itchen sin1 sho!ing the returned data as a Tree structure9
Codename One 2012. All rights Reserved. http: !!!."odenameone."om 111
An alternati+e a roach is to use the static data arse>? method of the <S#$.arser class and im lement a callbac1 arser e9g9) <S#$.arser9 arse'reader, callbac1(O $otice that a static +ersion of the method is usedK The callbac1 ob7ect is an instance of the <S#$.arseCallbac1 interface !hich includes multi le methods9 These !ill be in+o1ed by the arser to indicate internal arser states in a similar !ay to a traditional =(L SA= e+ent based arser9 Ad+anced readers might !ant to dig dee er into the rocessing language contributed by Eric Coolman !hich allo!s for - ath li1e e- ressions !hen arsing <S#$ & =(L9 0ead about it in EricQs blog9 Last but not least is the =(L arser, to use it 7ust create an instance of the =(L.arser class and in+o1e arse) =(L.arser arser P new =(L.arser'(O Element elem P arser9 arse'reader(O The element contains children and attributes and re resents a tag element !ithin the =(L document or e+en the document itself9 6ou can iterate o+er the =(L tree to e-tract the data from !ithin the =(L file9
0nalyti s Integration
#ne of the features in Codename #ne is builtin su ort for analytic instrumentation9 Currently Codename #ne has builtin su ort for &oogle Analytics !hich ro+ides reasonable enough statistics of a lication usage9 The infrastructure is there to su ort any other form of analytics solution of your o!n choosing9
Analytics is retty seamless for a &"I builder a lication since na+igation occurs +ia the Codename #ne A.I and can be logged !ithout de+elo er interaction9 Ho!e+er, to begin the instrumentation one needs to add the line) AnalyticsSer+ice9init'agent, domain(O To get the +alue for the agent +alue 7ust create a &oogle Analytics account and add a domain, then co y and aste the string that loo1s something li1e "A4JJJJJJJJ4I from the console to the agent string9 #nce this is in lace you should start recei+ing statistic e+ents for the a lication9 If your a lication is not a &"I builder a lication or you !ould li1e to send more detailed data you can use the Analytics9+isit>? method to indicate that you are entering a s ecific age9
3a ebook /"pport
Faceboo1 uses the &ra h A.I1 !hich is a <S#$ based !eb rotocol that allo!s de+elo ers to tra+erse the information !ithin faceboo1 and u date it9 To !or1 !ith Faceboo1 you need to read about the rocess of creating a faceboo1 a lication9 A Faceboo1 a lication identifies your a lication to Faceboo1 and allo!s them to associate in+ocations,changes made by your a lication !ith you9 The main issue !ith Faceboo1 is the authentication rocess !hich re;uires the #Auth standard to +alidate against the !ebsite9 #Auth forces the user to login to the !ebsite and a ro+e the ermissions re;uested by the a lication, once these credentials are gi+en in the !eb bro!ser the a lication is gi+en a to1en !hich it can use for all its calls9 This to1en can be reused
See htt ),,de+elo ers9faceboo19com,docs,reference,a i, Codename One 2012. All rights Reserved. http: !!!."odenameone."om 118
bet!een in+ocations so the user doesnEt need to re4enter his ass!ord9 Ho!e+er, the to1en needs to be re+alidated in case the user is logged out or changed his settings9 The main class of interest is Face%oo1Access !ith !hich !e obtain the to1en, notice that in the follo!ing code you should robably u date all the strings to match your actual needs) Face%oo1Access9setClientId'H183JBAJ1FI3IAIAH(O Face%oo1Access9setClientSecret'HFaaf@cIeaBJ1fAIea1DB8DebF@BbecfeH(O Face%oo1Access9set0edirect"0I'Hhtt ),,!!!9codenameone9com,H(O Face%oo1Access9set.ermissions'new String>?)HuserRlocationH, HuserR hotosH, HfriendsR hotosH, H ublishRstreamH, HreadRstreamH, HuserRrelationshi sH, HuserRbirthdayH, HfriendsRbirthdayH, HfriendsRrelationshi sH, HreadRmailbo-H, HuserRe+entsH, HfriendsRe+entsH, HuserRaboutRmeH+(O Face%oo1Access9getInstance'(9sho!Authentication'new ActionListener'( ) p"bli *oid action.erformed'ActionE+ent e+t( ) i# 'e+t9getSource'( instan eo# String( ) String to1en P 'String( e+t9getSource'(O String e- ires P #auth39getE- ires'(O System9out9 rintln'Hreci+ed a to1en H U to1en U H !hich e- ires on H U e- ires(O Storage9getInstance'(9!rite#b7ect'HautheniticatedH, HtrueH(O i#'main KP n"ll() main9sho!%ac1'(O + + else ) E-ce tion err P 'E-ce tion( e+t9getSource'(O err9 rintStac1Trace'(O 2ialog9sho!'HErrorH, HAn error occurred !hile logging in) H U err, H#NH, n"ll(O + + +(O
6ou can then get access to the !all by doing something li1e) Face%oo1Access9getInstance'(9get'allFeed'HmeH, '2efaultList(odel( !all9get(odel'(, n"ll(O
Impro*ing 5er#orman e
There are ;uite a fe! things you can do as a de+elo er in order to im ro+e the erformance and memory foot rint of a Codename #ne a lication9 This sometimes de ends on s ecific de+ice beha+iors but some of the ti s here are true for all de+ices9
The simulator contains some tools to measure erformance o+erhead of a s ecific com onent and also detect E2T bloc1ing logic9 #ther than that follo! these guidelines to create more erformance code) C C A+oid round rect borders 4 they ha+e a huge o+erhead on all latforms9 "se image borders instead >counter intuiti+ely they are ("CH faster?9 %itma fonts are retty slo! on many latforms, !e recommend a+oiding them9 (ethods such as string'idth, can also be +ery slo! on some latforms9 This means that reflo!ing the "I > referred si/e calls string !idth? can become +ery e- ensi+e9 0ead carefully the Image section and ma1e sure to ma1e conscious choices regarding the image ty es you choose9 Some older de+ices >symbian mostly? erform +ery badly !ith translucent images9 "se larger images !hen tiling or building image borders, using a 1 i-el >or e+ent a fe! i-els? !ide or high image and tiling it re eatedly can be +ery e- ensi+e9
C C C
5er#orman e &onitor
The erformance monitor tool is accessible +ia the menu o tion in the simulator and it o s u a dialog sho!ing some information that can hel you in debugging slo! erforming "IEs9 6ou !ill be able to see the amount of time and amount of aint o erations that occur for e+ery com onent as !ell as rintouts about e+ery image allocation and 0A( statistics for said allocations9
bloc1Rser+erRregistration
true,false flag defaults to false9 %y default Codename #ne a lications register !ith our ser+er, setting this to true bloc1s them from sending information to our cloud9 'e 1ee this data for statistical ur oses and intend to ro+ide additional installation stats in the future9 one of ios, i ad, i hone >defaults to ios?9 Indicates !hether the resulting binary is targeted to the i hone only or i ad only9 true,false defaults to false9 Hides the i#S status bar if set to true9 true,false defaults to false9 The i#S build rocess ada ts the submitted icon for i#S con+entions >adding an o+erlay? that might not be a ro riate on some icons9 Setting this to true lea+es the icon unchanged >only scaled?9 true,false >defaults to true?9 Indicates !hether the a lication should e-it immediately on home button ress9 The default is to e-it, lea+ing the a lication running is only artially tested at the moment9 "IInterface#rientation.ortrait by default9 Indicates the orientation, one or more of >se arated by colon )?) "IInterface#rientation.ortrait, "IInterface#rientation.ortrait" side2o!n, "IInterface#rientationLandsca eLeft, "IInterface#rientationLandsca e0ight true,false defaults to true9 Indicates !hether the user is rom ted for ermissions on 0I( de+ices9 true,false defaults to true9 #nly a licable to aying users9 Instruments an a lication !ith on de+ice e-ce tion logging !hich allo!s the a lication to send a crash log to the ser+er !hen it fails9 true,false defaults to false9 'hen set to true the 0I( build targets only D9A de+ices and ne!er and doesnEt build the @9- +ersion9 true,false defaults to false9 Enables the nati+e blac1berry bro!ser on #S D or higher9 It is disabled by default since it might casue crashes on some cases9 true,false defaults to false9 #bfuscate the <A0 before in+o1ing the rimc com iler9 entries to in7ect into the i#S list file during build9 true,false >defaults to false?9 'hether to include the ush ca abilities in the i#S build9
ios9a
licationRe-its
ios9interfaceRorientation
rim9ignorRlegacy rim9nati+e%ro!ser
noE-tra0esources
true,false >defaults to false?9 %loc1s codename one from in7ecting its o!n resources !hen set to true, the only effect this has is in slightly reducing archi+e si/e9 2efaults to @I-@I9 The si/e of the icon in the format of !idth height >!ithout the s acing?9
73me9iconSi/e
"I%uilder u P new "I%uilder'(O Container c P u9createContainer'r, Hui$ameIn0esourceH(O >$otice that since Form & 2ialog both deri+e from Container you can 7ust do!ncast to the a ro riate ty e?9 This !ould !or1 for any resource file and can !or1 com letely dynamicallyK E9g9 you can do!nload a resource file on the fly and 7ust sho! the "I that is !ithin the resource file999 That is !hat Codename #ne LI5EK is doing internally9
IDE Bindings
'hile the o tion of creating a 0esource file manually is o!erful, its not nearly as con+enient as modern &"I builders allo!9 2e+elo ers e- ect the ability to o+erride e+ents and basic beha+ior directly from the &"I builder and in mobile a lications e+en the flo! for some cases9 To facilitate I2E integration !e decided on using a single Statemachine class, similar to the common controller attern9 'e considered multi le classes for e+ery form,dialog,container and e+entually decided this !ould ma1e code generation more cumbersome9 The designer effecti+ely generates one class HStatemachine%aseH !hich is a subclass of "I%uilder >you can change the name, ac1age of the class in the Codename #ne ro erties file at the root of the ro7ect?9 Statemachine%ase is generated e+ery time the resource file is sa+ed assuming that the resource file is !ithin the src directory of a Codename #ne ro7ect9 Since the state machine base class is al!ays generated, all changes made into it !ill be o+er!ritten !ithout rom ting the user9 "ser code is laced !ithin the Statemachine class, !hich is a subclass of the Statemachine %ase class9 Hence it is a subclass of "I%uilderK 'hen the resource file is sa+ed the designer generates 3 ma7or ty es of methods into Statemachine base) 19 Finders 4 find=>Container c?9 A shortcut method to find a com onent instance !ithin a hierarchy of containers9 Effecti+ely this is a shortcut synta- for "I%uilder9find%y$ame>?, its still useful since the method is ty e safe9 Hence if a resource com onent name is changed the find>? method !ill fail in subse;uent com ilations9 39 Callbac1 e+ents 4 these are +arious callbac1 methods !ith common names e9g9) onCreateForm=>?, beforeForm=>? etc9 These !ill be in+o1ed !hen a articular e+ent,beha+ior occurs9
'ithin the &"I builder, the e+ent buttons !ould be enabled and the &"I builder ro+ides a ;uic1 and dirty !ay to 7ust o+erride these methods9 To re+ent a future case in !hich the underlying resource file !ill be changed >e9g form= could be renamed to form6? a su er method is in+o1ed e9g9 su er9onCreateForm=>?O This !ill robably be re laced !ith the ^#+erride annotation !hen <a+a D features are integrated into Codename #ne9
the finder method9 If the finder method doesnQt find the friend root under the arent it !ill find the HtrueH root com onent and search there9 The friends root is a container that contains the full list of our HfriendsH and !ithin it !e can 7ust !or1 !ith the com onents that !ere instantiated by the &"I builder9 Im lementing Custom Com onents There are t!o basic a roaches for custom com onents) 19 #+erride a s ecific ty e 4 e9g9 ma1e all FormQs deri+e a common base class9 39 0e lace a de loyed instance9 The first uses a feature of "I%uilder !hich allo!s o+erriding com onent ty es, s ecifically o+erride createCom onentInstance to return an instance of your desired com onent e9g9) prote ted Com onent createCom onentInstance'String com onentTy e, Class cls( ) i#'cls PP Form9 lass( ) ret"rn new (yForm'(O + ret"rn s"per9createCom onentInstance'com onentTy e, cls(O + This code allo!s me to create a unified global form subclass9 ThatQs +ery useful !hen I !ant so global system le+el functionality that isnQt su orted by the designer normally9 The second a roach allo!s me to re lace an e-isting com onent)
prote ted *oid beforeS lash'Form f( ) s"per9beforeS lash'f(O s lashTitle P findTitleArea'f(O ,, create a Hslide inH effect for the title dummyTitle P new Label'(O dummyTitle9set.referredSi/e's lashTitle9get.referredSi/e'((O f9re lace's lashTitle, dummyTitle, n"ll(O + prote ted *oid ostS lash'Form f( ) s"per9 ostS lash'f(O f9re lace'dummyTitle, s lashTitle, CommonTransitions9createSlide'CommonTransitions9SLI2ER5E0TICAL, tr"e, 1AAA((O s lashTitle P n"llO dummyTitle P n"llO +
$otice that !e re lace the title !ith an em ty label, in this case !e do this so !e can later re lace it !hile animating the re lace beha+ior thus creating a slide4in effect !ithin the title9 It can be re laced though, for e+ery ur ose including the ur ose of a com letely different custom made com onent9 %y using the re lace method the e-isting layout constraints are automatically maintained9
Nati*e Inter#a es
Lo! le+el calls into the Codename #ne system, including su ort for ma1ing latform nati+e A.I calls9 $otice that !hen !e say Hnati+eH !e do not mean C,CUU al!ays but rather the latforms Hnati+eH en+ironment9 So in the case of <3(E the <a+a code !ill be in+o1ed !ith full access to the <3(E A.IQs, in case of i#S an #b7ecti+e4C message !ould be sent and so forth9 $ati+e interfaces are designed to only allo! rimiti+e ty es, Strings, arrays >single dimension onlyK? of rimiti+es and .eerCom onent +alues9 Any other ty e of arameter,return ty e is rohibited9 Ho!e+er, once in the nati+e layer the nati+e code can act freely and ;uery the <a+a layer for additional information9 Furthermore, nati+e methods should a+oid features such as o+erloading, +arargs >or any <a+a DU feature for that matter? to allo! ortability for languages that do not su ort such features >e9g9 C?9 Im ortantK 2o not rely on ass by reference,+alue beha+ior since they +ary bet!een latforms9 Im lementing a nati+e layer effecti+ely means) 19 Creating an interface that e-tends $ati+eInterface and only defines methods !ith the arguments,return +alues declared in the re+ious aragra h9 39 Creating the ro er nati+e im lementation hierarchy based on the call con+entions for e+ery latform !ithin the nati+e directory E9g9 to create a sim le hello !orld interface do something li1e) pa kage om:my: odeE p"bli inter#a e (y$ati+e e4tends $ati+eInteface ) String hello'orld'String hi(O + Then to use that interface use (y$ati+e my P >(y$ati+e?$ati+eLoo1u 9create>(y$ati+e9class?O $otice that for this to !or1 you must im lement the nati+e code on all su orted latformsK To im lement the nati+e code use the follo!ing con+ention9 For <a+a based latforms >Android, 0I(, <3(E?) <ust create a <a+a class that resides in the same ac1age as the $ati+eInterface you created and bares the same name !ith Im l a ended e9g9) (y$ati+eIm l9 So for these latforms the code !ould loo1 something li1e this)
pa kage om:my: odeE p"bli lass (y$ati+eIm l implements (y$ati+e ) p"bli String hello'orld'String hi( ) ,, code that can in+o1e Android,0I(,<3(E res ecti+ely + + $otice that this code !ill only be com iled on the ser+er build and is not com iled on the client9 These sources should be laced under the a ro riate folder in the nati+e directory and are sent to the ser+er for com ilation9 For #b7ecti+e4C, one !ould need to define a class matching the name of the ac1age and the class name combined !here the H9H elements are re laced by underscores9 #ne !ould need to ro+ide both a header and an HmH file follo!ing this con+ention e9g9) ^inter#a e comRmyRcodeR(y$ati+e ) $S#b7ect ) + 4 'id(initO 4 '$SString[(hello'orld)'$SString [( aram1O ^end $otice that the arameters in #b7ecti+e4C are named !hich has no e;ui+alent in <a+a9 That is !hy the nati+e method in #b7ecti+e4C ("ST follo! the con+ention of naming the arameters H aram1H, H aram3H etc9 for all the nati+e method im lementations9 <a+a arrays are con+erted to $S2ata ob7ects to allo! features such as length indication9 .eerCom onent return +alues are automatically translated to the latform nati+e eer as an e- ected return +alue9 E9g9 for a nati+e method such as this) .eerCom onent create.eer>?O Android nati+e im lementation !ould need) 5ie! create.eer>?O 'hile 0I( !ould e- ect) Field create.eer>? The i hone !ould need to return a ointer to a +ie! e9g9) 4 >"I5ie![?create.eerO <3(E doesnQt su ort nati+e eers hence any method that returns a nati+e eer !ould al!ays return null9
Nati*e 5ermissions
$ormally ermissions in Codename #ne are retty seamless, !e tra+erse the bytecode and automatically assign ermissions to Android a lications based on the A.IEs used by the de+elo er9 Ho!e+er, !hen accessing nati+e functionality this 7ust !onEt !or1 since nati+e code might re;uire s eciali/ed ermissions and !e donEt,canEt run any serious analysis on it >it can be 7ust about anything?9 So if you re;uire additional ermissions in your Android nati+e code you need to define them in the build arguments using the android9- ermissions build argument and setting it to your
$otice that the Container class has a sim le sam le dro im lementation you can use to get started9
The motion class re resents a hysics o eration that starts at a fi-ed time bound to the system current time millis +alue9 The use case is entirely for "I animations and so many of its beha+iors are sim lified for this ur ose9 The motion class can be re laced in some of the builting classes to ro+ide a slightly different feel to some of the transition effects9
C C
%idi algorithm 4 allo!s con+erting bet!een logical to +isual re resentation for rendering &lobabl 0TL flag 4 default flag for the entire a lication indicating the "I should flo! from right to left Indi+idual 0TL flag 4 flag indicating that the s ecific com onent,container should be resented as an 0TL,LT0 com onent >e9g9 for dis laying English elements !ithin a 0TL "I?9 0TL te-t field in ut 0TL bitma font rendering ort is under the hood, the Loo1AndFeel global 0TL flag can
"I(anager9getInstance'(9getLoo1AndFeel'(9set0TL'tr"e(O >$otice that setting the 0TL to true im licitly acti+ates the bidi algorithm?9
#nce 0TL is acti+ated all ositions in Codename #ne become re+ersed and the "I becomes a mirror of itself9 E9g9 A soft1ey laced on the left mo+es to the right, adding on the left becomes adding on the right, the scroll mo+es to the left etc9 This a lies to the layout managers >e-ce t for grou layout? and most com onents9 %idi is mostly seamless in Codename #ne but a de+elo er still needs to be a!are that his "I might be mirrored for these cases9
iO/ 'i5hone2i5ad(
i#S signing has t!o distinct modes) A Store signing !hich is only +alid for distribution +ia iTunes >you !onQt be able to run the resulting a lication !ithout submitting it to A le? and de+elo ment mode signing9 6ou ha+e t!o ma7or files to 1ee trac1 of) Certificate 4 your signature .ro+isioning .rofile 4 details about the a lication and !ho is allo!ed to e-ecute it 6ou need t!o +ersions of each file >@ total files? one air is for de+elo ment and the other air is for u loading to the itunes A Store9 Important) 8o" need to "se a &a in order to reate a erti#i ate #ile #or iO/. methods to a hie*e this witho"t a &a prod" e an in*alid erti#i ate that #ails on the ser*er and lea*es hard to remo*e resid"e1: Adobe !rote a retty decent signing tutorial on this sub7ect for Air !hich you can retty much follo! to get the files !e need > 13 and mobile ro+ision?9 The first ste you need to accom lish is signing u as a de+elo er to A leQs i#S de+elo ment rogram, e+en for testing on a de+ice this is re;uiredK This ste re;uires that you ay A le JJ "S2 on a yearly basis9 The A le !ebsite !ill guide you through the rocess of a lying for a certificate at the end of this rocess you should ha+e a distribution and de+elo ment certificate air9 After that oint you can login to the i#S ro+isioning ortal !here there are lenty of +ideos and tutorials to guide
Seriously9 An in+alid name is stuc1 in the ser+ers and you !onEt be able to build later e+en if you ha+e a +alid certificate9 Its a ain for us so lease follo! the instructions ro erly and use a (ac for this stage9 Codename One 2012. All rights Reserved. http: !!!."odenameone."om 13I
you through the rocess9 'ithin the i#S ro+isioning ortal you need to create an a and register your de+elo ment de+ices9
lication I2
6ou then create a ro+isioning rofile !hich comes in t!o fla+ors) distribution >for building the release +ersion of your a lication? and de+elo ment9 The de+elo ment ro+isioning rofile needs to contain the de+ices on !hich you !ant to test9 6ou can then configure the @ files in the I2E and start sending builds to the Codename #ne cloud9
0ndroid
Its really easy to sign Android a lications if you ha+e the <2N installed9 Find the 1eytool e-ecutable >it should be under the <2NQs bin directory? and e-ecute the follo!ing command) 1eytool 4gen1ey 41eystore Neystore91s 4alias XaliasRnameY 41eyalg 0SA 41eysi/e 3A@I 4+alidity 1DAAA 4dname HC$PXfull nameY, #"PXouY, #PXcom Y, LPXCityY, SPXStateY, CPXCountry CodeYH 4store ass X ass!ordY 41ey ass X ass!ordY The elements in the brac1ets should be filled u based on this) Alias) XaliasRnameY >7ust use your name,com any name !ithout s aces? Full name) Xfull nameY #rgani/ational "nit) XouY Com any) Xcom Y City) XCityY State) XStateY CountryCode) XCountry CodeY .ass!ord) X ass!ordY >!e e- ect both ass!ords to be identical? E-ecuting the command !ill roduce a Neystore91s file in that directory !hich you need to 1ee since if you lose it you !ill no longer be able to u grade your a licationsK Fill in the a ro riate details in the ro7ect ro erties or in the Codename#ne section in the $etbeans references dialog9 For more details see htt ),,de+elo er9android9com,guide, ublishing,a 4signing9html
7I&2Bla kBerry
Codename One 2012. All rights Reserved. http: !!!."odenameone."om 13J
6ou can no! get signing 1eys for free from 0I( by going here9 After obtaining the certificates and installing them on your machine >you !ill need the 0I( de+elo ment en+ironment for this?9 6ou !ill ha+e t!o files) sigtool9db and sigtool9cs1 on your machine >!ithin the <2E directory hierarchy?9 'e need them and their associated ass!ord to erform the signed build for %lac1berry a lication9
LN&E
Currently signing <3(E a licationQs isnQt su orted9 6ou can use tools such as the S rint 'TN to sign the resulting 7ad,7ar roduced by Codename #ne9
In the certificates section you can do!nload your de+elo ment and distribution certificates9
In the de+ices section add de+ice idQs for the de+elo ment de+ices you !ant to su $otice no more than 1AA de+ices are su ortedK
ort9
Create an a erfectlyK
lication
Create a ro+isioning rofile for de+elo ment, ma1e sure to select the right a ma1e sure to add the de+ices you !ant to use during debug9
and
0efresh the screen to see the rofile you 7ust created and ress the do!nload button to do!nload your de+elo ment ro+isioning rofile9
Create a distribution ro+isioning rofile, it !ill be used !hen u loading to the a There is no need to s ecify de+ices here9
store9
'e can no! im ort the cer files into the 1ey chain tool on a (ac by double clic1ing the file, on 'indo!s the rocess is slightly more elaborate
'e can e- ort the 13 files for the distribution and de+elo ment rofiles through the 1eychain tool
In the I2E !e enter the ro7ect settings, configure our ro+isioning rofile, the ass!ord !e ty ed !hen e- orting and the 13 certificates9 It is no! ossible to send the build to the ser+er9
The H ro+iderH is the ser+er code that !ishes to notify the de+ice9 It needs to as1 A le to ush to a s ecific de+ice and a s ecific client a lication9 There are many com le-ities not mentioned here such as the need to ha+e a ush certificate or ho! the notification to A.$S actually ha ens but the basic idea is identical in i#S and AndroidQs &C(9 Codename #ne hides some but not all of the com le-ities in+ol+ed in the ush notification rocess9 Instead of !or1ing bet!een the differences of A.$S,&C( & falling bac1 to olling, !e effecti+ely do e+erything thatQs in+ol+ed9 .ush consists of the follo!ing stages on the client) 19 Local 0egistration 4 an a lication needs to register to as1 for ush9 This is done by in+o1ing) 39 2is lay9getInstance>?9register.ush>Hauth 1eyfor &C(H, fallbac1?O 89 The fallbac1 flag indicates !hether the system should fallbac1 to olling if ush isnQt su orted9 @9 #n i#S this stage rom ts the user indicating to him that the a lication is interested in recei+ing ush notification messages9 D9 0emote registration 4 once registration in the client !or1s, the de+ice needs to register to the cloud9 This is an im ortant ste since ush re;uires a s ecific de+ice registration 1ey >thin1 of it as a H hone numberH for the de+ice?9 $ormally Codename #ne registers all de+ices that reach this stage so you can ush a notification for e+eryone, ho!e+er if you !ish to ush to a s ecific de+ice you !ill need to catch this informationK To get ush e+ents your main class >im ortant, this must be your main classK? should im lement the .ushCallbac1 interface9 The registeredFor.ush>String? callbac1 is called !ith the uni;ue de+ice I2 that can be used later on !hen ushing to this articular de+ice9 F9 In case of an error during ush registration you !ill recei+e the dreaded) ush0egistrationError9 B9 This is a +ery roblematic area on i#S, !here you must ha+e a ac1age name that matches E=ACTL6 the o tions in your ro+isioning rofile !hich is setu to su ort ush9 It is also critical that you do not use a ro+isioning rofile containing a [ character in it9
Codename One 2012. All rights Reserved. http: !!!."odenameone."om 18I
I9 6ou !ill recei+e a ush callbac1 if all goes !ell9 Sending the ush re;uires t!o different things for &oogle and i#S9 In &C( >&oogle? you send a ush +ia a 1ey that is generated for you in the Android mar1et you can read more about it here htt ),,de+elo er9android9com,google,gcm,gs9html9 For i#S de+elo ers must do!nload a ush certificate from the i#S ro+isioning ortal for the gi+en a lication9 $otice that by enabling ush you !ill robably need to regenerate the ro+isioning rofile as !ell and do!nload,re lace your e-isting ro+isioning rofile9 The certificate must be con+erted to a 13 certificate as I e- lained in the ro+isioning rofile tutorial9 For ush to !or1 on i#S one needs to define the ios9include.ush build argument to true in order to enable ush related features9 Currently !e donQt ha+e the o tion to send the i#S certificate as art of the ush re;uest so you !ill ha+e to host it some!here and ro+ide us !ith the lin19 To send a ush message use the follo!ing !eb A.I) htt s),,codename4one9a s ot9com,send.ush(essage*authPgoogleAuthNey& ac1age$ameP ac1age$ame#fA lication& emailPemailAccount& de+icePthe2e+iceNey& ty eP1& roductionPtrue,false& cert.ass!ordP ass& certPCertificate"0L $otice the follo!ing arguments in articular) C de+ice 4 this is an o tional argument, to send to all de+ices 7ust omit this argument9 To send to a articular de+ice you need to ro+ide its 1ey !hich !as gi+en in the registeredFor.ush>? callbac19 C ty e 4 this must currently be set to 1, there !ill be additional ty es in the future C roduction 4 i#S has roduction and de+elo ment ush ser+ices each of !hich re;uires a different certificate9 Its im ortant to ic1 the right one9 .ass true for roduction and false for de+elo ment9 C cert 4 the "0L for the i#S ush certificate !hich you are hosting9 C cert.ass!ord 4 the ass!ord of the certificate