Date post: | 16-Nov-2014 |
Category: |
Documents |
Upload: | api-16493855 |
View: | 766 times |
Download: | 0 times |
CreateYourFirstHTML‐BasedAIRApplicationwithDreamweaverCS4Lab1:HelloMAXThefirstthingweneedtodoistocreateanAIRprojectwithinDreamweaver.Tocreatethenewproject,pleasefollowthestepsbelow.Section1:CreatingtheProjectStep1:CreateanewDreamweaversite SelectSite>NewSitefromthemainmenu
ThiswillopenthenewSitewizard.
FillinthenamepropertywithMAX_AIRandclickNext.Onthefollowingscreenselect“No,Idonotwanttouseaservertechnology”andclickNext.Onthethirdscreenselect“Editlocalcopiesonmymachine,thenuploadtoserverwhenready”.Also,browsetoastoragelocationandclickNext.
Onthefourthscreenselect“None”fromthe“Howdoyouconnecttoyourremoteserver?”dropdownandclickNext.FinallyonthefifthscreenverifyyourinformationandclickDone.Nowthatwehaveaproject,wecanaddamainapplicationfile.Step2:CreateanewHTMLfile SelectFile>New PageTypeHTML|Layout<none> ClickCreate
Step3:AddHelloMAX Add<h1>HelloMAX</h1>withinthe<body>tagsof thefileyoujustcreated. SelectFile>SaveandnamethefileIndex.html
Withthemainapplicationfilecreated,wecannowaddtheAIRapplicationsettingstotheproject,whichturnsourprojectintosomethingthatwecanrunwithintheAIRruntime.Step4:AddAIRApplicationSettings ChooseSite>AIRApplicationSettings
TheAIRApplicationandInstallerSettingswindowwillnowopen.ThisdialogisbasicallyanXMLeditortoconfigurethesettingsthattheAIRSDKwillusetocompileyourapplication.Youcanleaveallofthedefaultsettings.TheonlyrequirementisthatyoubrowseforanInitialcontentfile,whichistheIndex.htmlfilewepreviouslycreated.ClicktheBrowsebuttonandselecttheIndex.htmlfilefromyourprojectandthenclicktheSavebutton.
Ifyoulookatyourprojectwindow,youwillnoticeanewapplication.xmlfile.ThisfileistheconfigurationfileforyourAIRapplication.
Thatisallthatisrequiredtotestourapplication.TodoyoucaneitheropentheAIRApplicationswindowandclickthePreviewbuttonorCtrl+Shift+F12(Windows)orCmd+Shift+F12(Macintosh).
TheAIRapplicationwillnowlaunchandyoushouldseewhatisshownbelow.
Congratulations,youarenowofficiallyanAIRdeveloper!
Section2:PackageandInstall
NowthatwehaveaworkingAIRapplication,letspackageitupsothatwecaninstalltotheoperatingsystem.
Step1:OpentheAIR Application and Installer Settings window again (see Lab 1)
Step2:Addadigitalsignaturebyclickingthe
UponclickingtheSetbutton,anewwindowwillopenaskingforyourcertificate.
Ifyoudon’thaveacertificate,youwillneedtocreateaself‐signedcertificate.YoucancreateonebyclickingontheCreatebutton.ThiswillopentheSelf‐SignedDigitalCertificatewindowshownbelow.
Filloutthisform,thenclickthebrowsebuttonandnavigatetowhereveryouwishtostoreyourcertificateandclickOK.Youshouldseesomethinglikethewindowshownbelow.
ClickOKtoclosetheAlertwindow,thenclickOKtoclosetheDigitalCertificatewindow.
Step3:CreatetheAIRinstallerfile
YouwillnowbeabletoclicktheCreateAIRFilebuttonontheAIRApplicationandInstallerSettingswindow.Thiswillcreateanewfilenamedwitha.airextension.Thisisthepackagedapplicationthatcannowbeinstalledbydoubleclickingonit.
Lab2:DebuggingyourApplicationDevelopershaveusedthetrace()statementforeverwhenbuildingFlashcontentwithinFlashIDE,FlexBuilder,etcforoutputtinginformationtotheconsole.WithinHTMLbasedAIRapplicationswecanoutputtotheconsolethoughtheuseofAIRIntrospector.js.Loggingsomethingtotheintrospectorwilllaunchtheapplicationshownbelow.
Section1:OutputtotheconsoleStep1:AddAIRIntrospector.jstoyourproject.
TheAdobeFlexSDKincludeswithaJavaScriptfilenamedAIRIntrospector.Youcanfindthisfilewithin:
SDKRoot/frameworks/libs/air
CopythisfileintoyourprojectfolderandrefreshyourprojectwithinDreamweaver.
Step2:Createanewfile(Debug.html)
Step3:IncludetheAIRIntrospector.jsTousetheAIRIntrospector,youwillneedtoincludeitwithintheDebug.htmlfile.Todoso,simplyaddthefollowingscripttothe<head>oftheDebug.htmlfile.
<scripttype="text/javascript"
src="AIRIntrospector.js"></script>
Step4:Outputtotheconsole
Addthecodebelowtothe<body>ofyourDebug.htmlfile.
<script>
functiontrace(){
varmessage="HelloMAX"; air.Introspector.Console.log(message); }
</script>
<buttononclick="trace()">trace()</button>
AddalinktotheDebug.htmlfileinthe<body>oftheIndex.htmlfile.
<p><ahref="Debug.html">Debug</a></p>
Runtheapplication,clicklinktotheDebug.htmlfileandthenclickthetrace()buttonandyouwillseethemessageappearwithintheAIRIntrospector.
Lab3:UtilizingAIRclassesTogainaccesstotheAIRclasses,youcanleveragetheJavaScriptthatAdobehasprovidedtoconnectyourapplicationtotheAIRSDK.ThisJavaScriptfileiscalledAIRAliases.jsandshipswithintheAIRSDK.Section1:AccessingAIRclassesvia AIRAliases.js Step1:AddAIRAliases.jstoyourproject.
TheAdobeFlexSDKincludeswithaJavaScriptfilenamedAIRAliases.Youcanfindthisfilewithin:
SDKRoot/frameworks/libs/air
CopythisfileintoyourprojectfolderandrefreshyourprojectwithinDreamweaver.
Section2:UsingtheAIRFileSDKStep1:Createanewfile(FileSystem.html)
Step2:IncludetheAIRAliases.jsSimplyaddthefollowingscripttothe<head>oftheFileSystem.htmlfile.
<scripttype="text/javascript"
src="AIRAliases.js"></script>
Step3:CreateanewDirectoryThefirstthingwewilldoistousetheAIRFileAPItocreateanewdirectoryonthefilesystem.TheAIRSDKincludessomefilesystemaliasestomakeiteasiertonavigatethefilesystemonmultipleoperatingsystems.Theavailablealiasesare
• applicationDirectory• applicationStorageDirectory• desktopDirectory• documentsDirectory• userDirectory
Forthisexample,wewillusethedesktop.Addthecodebelowwithinthe<body>oftheFileSystem.htmlfile.
<script>
functioncreateDirectory(){
vard=air.File.desktopDirectory.resolvePath("myDirectory");d.createDirectory();
}
</script>
<buttononclick="createDirectory()">createDirectory()</button>
SavethefileandthenaddthefollowingtotheIndex.htmlfilebelowthelinktotheDebug.htmlfile.
<p><ahref="FileSystem.html">FileSystem</a></p>
Runtheapplication,clicklinktotheFileSystem.htmlfileandthenclickthecreateDirectory()buttonandyouwillseeanewdirectoryonyourdesktop.
Step4:CreateanewFileCreatinganewfileissimilartocreatinganewdirectory.YousimplyneedtousetheresolvePath()methodbutinthiscase,includeafilenameastheparameter.
AlthoughtheresolvePath()methodwillcreateareferencetothemyFile.txtonthefilesystem,thefilewillnotbewrittentothefilesystemuntilitcontainssomecontents.WewillaccomplishthisbyutilizingtheFileStreamclass.
TheFileStreamclassallowsyoutoopenafilewithaspecificmodebypassinginaFileModetype.ThepossibletypesforFileModeareAPPEND,READ,UPDATE,andWRITE.
Addthecodebelowwithinthe<body>oftheFileSystem.htmlfile.
<script>
functioncreateFile(){
varf=air.File.desktopDirectory.resolvePath("myFile.txt"); varfs=newair.FileStream(); fs.open(f,air.FileMode.WRITE); fs.writeUTFBytes("HelloMAX");
fs.close();
}
</script>
<buttononclick="createFile()">createFile()</button>
Runtheapplication,clicklinktotheFileSystem.htmlfileandthenclickthecreateFile()buttonandyouwillseeanewfileonyourdesktop.
Section3:UsingtheAIRSQLiteSDKStep1:CreateanSQLitedatabaseASQLitedatabaseissimplyafilewitha.dbextension.So,tocreateadatabase,wewillfollowthesamestepsthatweusedwithinSection2ofLab3.
First,createanewfilewithinyourDreamweaverprojectnamedSQLite.htmltoholdthecodefortheSQLitesample.
Next,simplyaddthefollowingscriptstothe<head>oftheSQLite.htmlfile.
<scripttype="text/javascript"src="AIRIntrospector.js"></script>
<scripttype="text/javascript"src="AIRAliases.js"></script>
Nowcreateanew<script>blockandaddthefollowingvariableandfunctions:
varconn;
functionopenDatabase(){
conn=newair.SQLConnection();
vardbFile=air.File.desktopDirectory.resolvePath("MAX.db");conn.openAsync(dbFile);
}
Next,addacalltotheopenDatabase()functionwithinthe<body>tag.
<bodyonload="openDatabase()">
Finally,addalinktotheSQLite.htmlfilewithinyourIndex.html.
<p><ahref="SQLite.html">SQLite</a></p>
NowruntheIndex.html,clickonthelinktoSQLiteandyoushouldseeafilenamedMAX.dbonyourdesktop.
Step2:CreateanSQLitetableNowthatwehaveadatabase,weneedtocreateatable.Tocreateatable,wewilluseastandardSQLstatement.Addthefollowingvariablesrightbelowtheconnvariable.
varopenStmt;
varsqlCreateTable=
"CREATETABLEIFNOTEXISTSMAXTable("+
"idINTEGERPRIMARYKEYAUTOINCREMENT,"+ "fNameTEXT,lNameTEXT)";
Weneedto,updatetheopenDatabase()functionthatweaddedinStep1tothefollowingtoincludesomeaneventhandlerthatwillbecalledwhenthedatabaseisopened:
functionopenDatabase(){
conn=newair.SQLConnection();vardbFile=air.File.desktopDirectory.resolvePath("MAX.db");conn.addEventListener(air.SQLEvent.OPEN,openHandler);conn.openAsync(dbFile);
}
Now,addtheopenHandler()functionshownbelow.Thisfunctionwillberunwhenthedatabaseisopened.Whenwelookatwhatis
goingonwithintheopenHandler()function,youwillnoticethatanewSQLStatementiscreatedandpassedtheopenedSQLConnection.Next,thetextpropertyissettoourcreatestatement,afeweventlistenersareaddedtohandlethesuccessandfailureoftheSQLStatement.Finally,theSQLStatementisexecuted.
functionopenHandler(event){
openStmt=newair.SQLStatement(); openStmt.sqlConnection=conn;
openStmt.text=sqlCreateTable; openStmt.addEventListener(air.SQLEvent.RESULT,
onResult);
openStmt.addEventListener(air.SQLErrorEvent.ERROR,
onError);
openStmt.execute();
}
AddtheonResult()andonError()methods.ThesemethodswillprovidesomefeedbacktotheIntrospectorsothatwecantracktheresults.
functiononResult(event){ air.Introspector.Console.log(event.target.text+
"completed");
}
functiononError(event){ air.Introspector.Console.log(event.error.message); air.Introspector.Console.log(event.error.details);
}
Runtheapplication,clickontheSQLitelinkandthedatabasewillnowbecreatedwithatablenamedMAXTable.
Step3:InsertDataWhatgoodisaSQLitetablewithoutdata?So,letsaddsomedata.Todoso,wefirstneedaformtocollectthedata.
Addthefollowingcodetothe<body>totheSQLite.htmlfile.
<formname="contactForm">
Firstname:<inputname="fName"/><br/>
Lastname:<inputname="lName"/>
<inputtype="button"value="SavetoDB"onclick="insert()"/>
</form>
Next,weneedanothervariabletoholdtheSQLinsertstatement.
AddvarinsertStmt;rightbelowtheopenStmtvariable.
Now,weneedtoaddtheinsert()functionthatwillbecalledwhenourformissubmitted.ThistimeweneedtocreatetheSQLwhentheinsert()functioniscalledasitisuniquetothedatabeingsaved.AddthefollowingfunctiontotheSQLite.htmlfile.NoticehowtheformfieldsarebeingreferencedwithinthesqlInsertvariable.
functioninsert(){
sqlInsert="INSERTINTOMAXTable(fName,lName)"+ "VALUES("+"'"+
document.contactForm.fName.value+"'"+
","+"'"+document.contactForm.lName.value+
"'"+")";
insertStmt=newair.SQLStatement(); insertStmt.sqlConnection=conn;
insertStmt.text=sqlInsert; insertStmt.addEventListener(air.SQLEvent.RESULT,
onResult);
insertStmt.addEventListener(air.SQLErrorEvent.ERROR,
onError);
insertStmt.execute();
}
Runtheapplicationandsubmittheformafewtimes.YouwillseethattheSQLStatementcompletessuccessfullywithintheIntrospector.
Step4:QueryDataOkay,wehaveinserteddatatotheMAXTableright?Well,itappearsthateverythingranproperlywithinStep3andthatthedatawasinserted,butIliketoseethingswithmyowneyes.
So,letscreateanewfunctiontoqueryourtable.
ThistimeweknowwhattheSQLwillbeso,simplyaddthefollowingvariablebelowtheinsertStmt.
varsqlSelectAll="SELECT*FROMMAXTable";
Also,addanewvariabletoholdtheSQLStatement.
varselectStmt;
Now,wecanaddafunctiontoruntheselectStmtcalledgetAll().
functiongetAll(){
selectStmt=newair.SQLStatement(); selectStmt.sqlConnection=conn;
selectStmt.text=sqlSelectAll; selectStmt.addEventListener(air.SQLEvent.RESULT,
getAllHandler);
selectStmt.addEventListener(air.SQLErrorEvent.ERROR,
onError);
selectStmt.execute();
}
ThegetAll()functionwillcallthegetAllHandler()whenitsuccessfullyruns.ThegetAllHandler()simplyiteratesovertheresultsandoutputstotheIntrospetor.
functiongetAllHandler(event){
varresults=selectStmt.getResult().data;
if(results!=null){
air.Introspector.Console.log(results.length+
"recordsfound");
for(i=0;i<results.length;i++){
air.Introspector.Console.log("id:"+results[i].id+""+"fName:"+results[i].fName+""+"lName:"+results[i].lName);
}
}
}
Finally,addabuttontothe<body>belowthecontactForm.
<buttononclick="getAll()">getAll()</button>
RuntheapplicationclickthegetAll()buttonandyoushouldseeyourdatabeingoutputtotheIntrospector.
Lab4:Using3rdpartyAJAXlibrariesSection1:AddaYUIDataTableNowthatwehaveadatasetbeingreturnedtoourapplication,itwouldbenicetohaveitformattedandsortable.
Step1:CopytheYUIfilesintoyourprojectGrabtheYUIfolderfromthesourcefilesfolderandcopyitintotheMAX_AIRfolder.BackinDreamweaver,refreshyourapplication.Step2:Addthenecessaryimportstatements
TousetheYUIlibrarywewillneedtoaddsomeimportstatementstotheSQLite.htmlfile.TheseincludebothCSSincludesandJavaScriptincludes.Addthefollowingtowithinthe<head>tagsoftheSQLite.htmlfile.
<linkhref="YUI/2.6.0/build/fonts/fonts‐min.css"rel="stylesheet"type="text/css">
<linkhref="YUI/2.6.0/build/datatable/assets/skins/sam/datatable.css"rel="stylesheet"type="text/css">
<scriptsrc="YUI/2.6.0/build/yahoo‐dom‐event/yahoo‐dom‐event.js"type="text/javascript"></script>
<scriptsrc="YUI/2.6.0/build/element/element‐beta‐min.js"type="text/javascript"></script>
<scriptsrc="YUI/2.6.0/build/datasource/datasource‐min.js"type="text/javascript"></script>
<scriptsrc="YUI/2.6.0/build/datatable/datatable‐min.js"type="text/javascript"></script>
Step3:AddthehtmltableTheYUIDataTableutilizesatraditionalhtmltableasthebase.Thisnormallyallowsnon‐JavaScriptenablebrowserstodegradegracefully.ItisgoodtoknowthatthiswillneverbeanissuewithinAIRapplications.
Addthefollowingcodetothe<body>oftheSQLite.htmlfilerightbelowthegetAll()button.
<divid="yuidatatable1">
<tableid="yuidatatable1_data">
<thead>
<tr>
<th>Id</th>
<th>Firstname</th>
<th>Lastname</th>
</tr>
</thead>
</tbody>
</table>
</div>
Step4:AddtheJavaScripttodefineDataTableTheYUIDataTableneedtohaveitscolumnsanddatatypesdefinedsothatitunderstandshowtoorganizeandsortthedata.AddthefollowingscriptblockatthebottomoftheSQLite.htmlfilerightaftertheclosing</body>tag.
<scripttype="text/javascript">
(function(){
varcn=document.body.className.toString();
if(cn.indexOf('yui‐skin‐sam')==‐1){
document.body.className+="yui‐skin‐sam";
}
})();
varinityuidatatable1=function(){
varcolumnDef_yuidatatable1=[{key:"id",label:"Id",formatter:YAHOO.widget.DataTable.formatNumbere,sortable:true},
{key:"fName",label:"Firstname",sortable:true},{key:"lName",label:"Lastname",sortable:true},
];
this.DS_yuidatatable1=newYAHOO.util.DataSource(YAHOO.util.Dom.get("yuidatatable1_data"));
this.DS_yuidatatable1.responseType=YAHOO.util.DataSource.TYPE_HTMLTABLE;
this.DS_yuidatatable1.responseSchema={
fields:[
{key:"id",parser:YAHOO.util.DataSource.parseNumber},
{key:"fName"},
{key:"lName"}
]
};
varyuidatatable1=newYAHOO.widget.DataTable("yuidatatable1",
columnDef_yuidatatable1,
this.DS_yuidatatable1);
};
</script>
Step5:ReplacethegetAllHandler() Nowthatwehaveallofthenecessarylayout,imports,andtabledefinitionsdefined,wesimplyneedtoupdatethegetAllHandler()functiontoaddrowstothenewDataTableratherthanoutputtingtotheconsole.
functiongetAllHandler(event){
varresults=selectStmt.getResult().data;
if(results!=null){
air.Introspector.Console.log(results.length+"recordsfound");
vartableHTML='<tableid="yuidatatable1_data">';tableHTML+='<thead>';
tableHTML+='<tr>';
tableHTML+='<th>Id</th>';
tableHTML+='<th>Firstname</th>';
tableHTML+='<th>Lastname</th>';
tableHTML+='</tr>';
tableHTML+='</thead>';
tableHTML+='<tbody>'; for(i=0;i<results.length;i++){
tableHTML+='<tr>';
tableHTML+='<td>'+results[i].id+'</td>'; tableHTML+='<td>'+results[i].fName+'</td>'; tableHTML+='<td>'+results[i].lName+'</td>'; tableHTML+='</tr>';
}
tableHTML+='</tbody>';
tableHTML+='</table>';
document.getElementById("yuidatatable1").innerHTML=tableHTML;
YAHOO.util.Event.onDOMReady(inityuidatatable1);
}
}
GoaheadandruntheIndex.htmlfileandthenclickthegetAll()buttonwithintheSQLitepage.
Step6:FetchtherecordsonchangeTomakesuretheDataTablestayscurrent,simplyaddacalltogetAll()withintheonResult()functionoftheSQLite.htmlfile.Sincethe
onResult()functiongetscalledwheneverthefileislaunchedorwhenanewrecordisadded,itwillalwayskeepthedatafresh.
ExtraCredit:DeleteaRecordYouhavenowanapplicationthatcaninsertandquerydata,forextracredit,pleaseadddeletefunctionalitytotheapplication.
Iftimepermits,wewillcoverthisduringclass.Ifnot,youcanseethesolutioninafilecalledSQLiteWithDelete.htmlwithintheresourcesfolder.