SlideShare a Scribd company logo
Visage Android Hands-on LabStephen Chin – GXShttp://steveonjava.com/
The Visage Language2“Visage is a domain specific language (DSL) designed for the express purpose of writing user interfaces.”Statically Compiled LanguageBased on F3 / JavaFX ScriptPlanning Support for Different Platforms:JavaFX 2.0AndroidApache PivotFlexJSF
Language FeaturesDeclarative Object ConstructionCode looks like the UI it is representing. Data BindingVariables can be bound to UI state, allowing automatic updates and behavior to be triggered. Behavior EncapsulationVisage provides closures to make it easy to implement event handlers or other behavior-driven logic. Null SafetyApplication logic will proceed even if intermediate variables are undefined or null. 3
Hello World VisageStage {  title: "Hello World"  Scene {    Text {      "Hello World"    }  }}4
Visage on Android5Visage Runs as a Native App on AndroidFull Access to all the Android APIsDeclarative Layer on Top of Android APIs
6Lesson 1Java vs. visage
Language SimilaritiesJava is…Statically typedCompiled to bytecodesRuns on the JVMHas a large libraryVisage is…Statically typedCompiled to bytecodesRuns on the JVMCan call Java libraries7
Language Differences8
Integrating Visage and JavaCalling Java from VisageCan call Java interface or classes directlyAutomatic conversion to and from Arrays and CollectionsCan even extend Java interfaces and classesCalling Visage from JavaEasiest way is to create a Java interface that Visage extendsCan invoke Visage as a script and get results back9
Hello World, VisageModule 110
Exercise 1.A – Android SetupSetup and run the VirtualBox imageCreate an emulator instanceCreate a new Android project from the command lineRun the project in the emulator11
Setting Up Your MachineCopy these files off the USB stick:VirtualBox for your platform (mac or windows)VisageLab folderDecompress VisageLab/Visage Dev2.vdi.zipInstall VirtualBoxOpen Visage Dev.vbox12
Setting Up Your MachineDownload and Install the Android SDKhttp://developer.android.com/sdk/index.htmlDownload the Visage SDKhttp://code.google.com/p/visage/downloads/listInstall the Android/Visage SDKOn the USB stick13
Set Up Your Device for DebuggingAnd mount it from:Devices > USB Devices > (your-device-name)1414
Or Create a Virtual Android Device15Launch the AVD Manager by typing: android
Setting Up Your ProjectProject creation command:android create project –t 1 –p HelloVisage –k org.test –a HelloVisageArguments:n : Project name (optional)t : Target ID of the new project (required)p : Project directory (required)k : Package name for the application (required)a : Name of the default Activity (required)16
Android XML Code<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"   android:orientation="vertical" android:layout_width="fill_parent"  android:layout_height="fill_parent"      ><TextViewandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:text="Hello World, HelloVisage"/></LinearLayout>17
Plus some more Java…public class HelloVisage extends Activity {/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedIS) {super.onCreate(savedIS);setContentView(R.layout.main);    }}18
Run Your Projectcd HelloVisageant installOpen it in the applications menu19
Exercise 1.B – All Java ConversionMake sure you have the basic project running firstConvert the XML Code to JavaRun the all Java projectYou should get identical results20
Converted XML Code (simplified)public class HelloVisage extends Activity {  @Override public void onCreate(Bundle savedIS) {super.onCreate(savedIS);Context context = getApplicationContext();LinearLayout layout = new LinearLayout(context);layout.setOrientation(LinearLayout.VERTICAL);TextView text = new TextView(context);text.setText("Hello World, Java Only");layout.addView(text);setContentView(layout);}}21
(and here are the imports…)import android.app.Activity;import android.content.Context;import android.os.Bundle;import android.widget.LinearLayout;import android.widget.TextView;22
Exercise 1.C – DDMS DebuggingSo you made a mistake in your code…  the compiler can’t catch everything(even if you didn’t make a mistake, force one…  a beautiful NullPointerException will do)Launch DDMS and select your emulator/device23
Break the code (change in bold)public class HelloVisage extends Activity {  @Override public void onCreate(Bundle savedIS) {super.onCreate(savedIS);Context context = getApplicationContext();LinearLayoutlayout = null;//new LinearLayout(context);layout.setOrientation(LinearLayout.VERTICAL);TextView text = new TextView(context);text.setText("Hello World, HelloVisage");layout.addView(text);setContentView(layout);}}24
DDMS Displaying a Stack Trace25
Exercise 1.D – Visage PortModify the build script to compile VisageCopy the Visage Runtime librariesConvert the Java code to VisageRun on device/emulator26
Modify the Build Script (1)<target name="-post-compile">    <path id="android.classpath">        <filesetdir="./libs" includes="*.jar" />        <path refid="android.target.classpath"/>        <pathelement location="${out.classes.absolute.dir}"/>    </path>    <pathconvertrefid="android.classpath" property="androidcpath"/>    <path id="visage.sources">        <filesetdir="${source.absolute.dir}" includes="**/*.fx"/>    </path>27
Modify the Build Script (2) <pathconvertrefid="visage.sources" property="visagepath" pathsep=" "/>    <exec executable="${visagehome}/bin/javafxc${binary.extension}" failonerror="true" logerror="true">        <arg value="-d"/>        <arg value="${out.classes.absolute.dir}"/>        <arg value="-cp"/>        <arg value="${androidcpath}"/>        <arg line="${visagepath}"/>    </exec></target>28
Add Some Properties…local.properties:visagehome=/home/visage/visage-sdkbinary.extension=29
Copy Over the Runtime JARCopy:javafxrt.jarFrom:$visagehome/lib/shared/To:$projectdir/libs30
Straight JavaFX Conversion...public class Test extends Activity {  override function onCreate(savedInstanceState:Bundle) {super.onCreate(savedInstanceState);def context = getApplicationContext();def layout = new LinearLayout(context);layout.setOrientation(LinearLayout.VERTICAL);def text = new TextView(context);text.setText("Hello World, Hello Long Visage");layout.addView(text);setContentView(layout);}}31
Rename your source file*.java -> *.fx32
Exercise 1.E – Simplified VisageInclude the visage-android jarModify the Visage code to use the new APIsRun on device/emulator33
Copy the visage-android JARCopy:visage-android.jarFrom:/home/visage/visage-android/dist/To:$projectdir/libs34
Android JavaFX Codepublic class HelloVisage extends Activity {    override var view = LinearLayout {        orientation: Orientation.VERTICAL        view: TextView {            text: "Hello World, Beautified Visage"        }    }}35
And change the imports…org.visage.android.app.Activity;org.visage.android.widget.LinearLayout;org.visage.android.widget.Orientation;org.visage.android.widget.TextView;36
Working Hello Visage Application37
Visage Language FundamentalsLesson 238
Datatype Support39
Visage Operators40Multiplication and division of two durations is allowed, but not meaningful
Underflows/Overflows will fail silently, producing inaccurate results
Divide by zero will throw a runtime exceptionVisage Operators (continued)41
Access Modifiers42
Data BindingA variable or a constant can be bound to an expressionvar x = bind a + b;The bound expression is rememberedThe dependencies of the expression is watchedVariable is updated lazily when possible43
CONTROLS AND SETTINGSModule 244
Exercise 2.A – NetBeans IntegrationCreate a new JavaFXNetBeans projectMerge in build scripts from Android projectStart coding!45
Create a new JavaFX ProjectFile > New Project…Name the project “ConfigReporter”In package "org.test"46
Merging Project FoldersCopy these files over:*.propertiesAndroidManifest.xmlres/libs/proguard.cfgbuild.xml [replace]47
Merging Build ScriptsUpdate the build.xml file:Set the project name to “ConfigReporter”Update the strings.xml file:Set the app_name to “ConfigReporter”Load the NetBeans property files (in build.xml):<property file="nbproject/private/config.properties"/><property file="nbproject/private/configs/${config}.properties"/><property file="nbproject/private/private.properties"/><property file="${user.properties.file}"/><property file="nbproject/configs/${config}.properties"/><property file="nbproject/project.properties"/>48
Alias NetBeans Targets:<target name="launch" depends="install”>  <exec executable="${adb}" failonerror="true">   <arg line="${adb.device.arg}"/>    <arg value="shell"/>    <arg value="am"/>    <arg value="start"/>    <arg value="-n"/>    <arg value=”org.test/.ConfigReporter"/>    <arg value="-a"/>    <arg value="android.intent.action.MAIN"/>  </exec></target><target name="jar" depends="compile"/><target name="run" depends="launch"/>49
Update AndroidManifest.xmlChange project name to "ConfigReporter"50
Modify Project PropertiesSet JavaFX Platform to “Visage_SDK”Add Libraries:“libs” folderandroid.jar51
Update ConfigReporter.fxMake it extend the visage Activity classFor now, you can copy the logic from HelloVisage52
Exercise 2.C – Android ControlsCreate a Text FieldCreate an Edit BoxWire them up using Binding53
Bound Controls (1)override var view = LinearLayout {orientation: Orientation.VERTICALvarsecret:String;view: [EditText {hint: "Super Secret Text”password: truetext: bind secret with inverse54
Bound Controls (2)}TextView {text: "Is Revealed!!!”}TextView {text: bind secret}]}55
Exercise 2.D – Button HandlerCreate a Button ControlAdd an onClick handlerMake something happen (maybe a bind)56
Button onClick handlerButton {    text: "Launch Settings"onClick: function() {startActivity(new Intent(this, Settings.class));        setting = "Launching...";    }}TextView {    text: "Setting is:"}TextView {    text: bind setting}57
Exercise 2.E – Android SettingsCreate a Settings ActivityPopulate it with the following preferences:TextPasswordListLaunch it from the Button control58
Settings Classpublic class Settings extends PreferenceActivity {varusernamePref:EditTextPreference;varpasswordPref:EditTextPreference;varpollingPref:ListPreference;    override var screen = PreferenceScreen {        preferences: [           …59
Text PreferencePreferenceCategory {    title: "Preferences"    preferences: [usernamePref = EditTextPreference {            title: "Username"            key: "usernamePref"            summary: bind if (usernamePref.text == "") "Currently undefined" else "Current value: {usernamePref.text}"}60
Password PreferencepasswordPref = EditTextPreference {  title: "Password”  key: "passwordPref”  summary: bind passwordPref.text.replaceAll(".", "*");}61
List PreferencepollingPref= ListPreference {  title: "Polling Interval"key: "pollingPref"defaultValue: "60000"entries: ["30 seconds", "1 minute", "5 minutes", "10 minutes", "15 minutes", "30 minutes", "1 hour"]entryValues: ["30000", "60000", "300000", "600000", "900000", "1800000", "3600000"]summary: bind pollingPref.entry}62
Service MetadataUpdate AndroidManifest.xml:<activity android:name=".Settings"                  android:label="@string/settings_label"/>Update string.xml:<string name="settings_label">Settings</string>63
Invoke the new serviceIn the onClick handler:startActivity(new Intent(this, Settings.class));64
Working Settings Panel65
Advanced Javafx sequencesLesson 366
What Bind Updatesvar x = bind if(a) then b else cx is updated if a or b or c changesvar x = bind for (i in [a..b]) { i * i }Not everything is recalculatedIf a = 1 and b = 2, x is [1, 4]If b changes to 3, only the added element is calculated67149
Binding to ExpressionsBinding to a blockBound block may contain any number of defs followed by one expressionDependencies of block is backtraced from the expressionBinding to function invocation expressionRegular function: dependencies are parametersBound function: backtraced from final expression inside function68
Binding to Object Literalsvar a = 3; var b = 4;var p = bind Point { x: a, y: b };var q = bind Point { x: bind a, y: b };var r = bind Point { x: bind a, y: bind b };When a changes:p gets a new instance of Pointq and r keep the old instance with a new x valuer will never get a new instance of Point(the outer bind in r is useless)69
Visage SequencesRepresents collections of homogeneous dataA fundamental container data typeRich set of language facilitiesContributor to declarative syntaxAutomatic conversion to and from Java Arrays and Collections70
Creating SequencesExplicit sequence expression[1, 3, 5, 7, 9]Elements are separated by commasComma may be omitted if element ends with brace7113579
Creating SequencesNumeric sequence with range expressions:[1..10]Can have a step:[1..10 step 2][0.0..0.9 step 0.1]Can be decreasing:[10..1 step -3]Beware of step that goes opposite direction:[10..1] is []Exclusive right end[1..<5]7212345678910135790.1.2.3.4.5.6.7.8.9107411234
Getting Info from Sequencesints = [1, 3, 5, 7, 9]sizeofintsis 5ints[0] is 1, ints[1] is 3, ..., ints[4] is 9ints[-1] is 0 (default value of Integer), so is ints[5]For a sequence of objects, the default is null7313579[0][1][2][3][4]
Getting Slices from Sequencesints = [1, 3, 5, 7, 9]ints[0..2] is [1, 3, 5]ints[0..<2] is [1, 3]ints[2..] is [5, 7, 9]ints[2..<] is [5, 7]ints[2..0], ints[-2..-1], ints[5..6] are all []s7413579[0][1][2][3][4]
Getting Subsets from Sequencesints = [1, 3, 5, 7, 9]ints[k | k > 6] is:[7, 9] (k > 6 is a condition)ints[k | indexof k < 2] is:[1, 3]ints[k | k > 10] is:[]7513579[0][1][2][3][4]
Inserting into Sequencesints = [1, 3, 5, 7, 9]insert 20 into intsinsert 30 before ints[2]insert 40 after ints[4]insert [50, 60] into ints1357913579201357920301357920304013579203040506076
Deleting from Sequencesints = [1, 3, 5, 7, 9]delete 7 from intsdelete ints[0]delete ints[0..1]delete ints: ints becomes []135791357913593599
Sequence PuzzlersWhat is the size of this sequence:[1..10 step -1]What does this evaluate to:[10..<20 step 2][k|k>17]What is the size of this sequence:sizeof [20..1 step -3]781A: 02A: [18]3A: 1
Module 3EXTENDING VISAGE ANDROID APIs79Become a Visage contributor!Join me in the Hackergartenafter the session

More Related Content

PPT
Webinar on Google Android SDK
PPTX
JCON 2020: Mobile Java Web Applications with MVC and OpenDDR
PDF
Android NDK: Entrando no Mundo Nativo
PDF
SFScon14: write java, run javascript: create enterprise html5 apps without “u...
PPTX
Dependency injection
PDF
The WebView Role in Hybrid Applications
PDF
TypeScript, Dart, CoffeeScript and JavaScript Comparison
DOCX
Abhishek_Kumar
Webinar on Google Android SDK
JCON 2020: Mobile Java Web Applications with MVC and OpenDDR
Android NDK: Entrando no Mundo Nativo
SFScon14: write java, run javascript: create enterprise html5 apps without “u...
Dependency injection
The WebView Role in Hybrid Applications
TypeScript, Dart, CoffeeScript and JavaScript Comparison
Abhishek_Kumar

What's hot (20)

PDF
Guice tutorial
PDF
Automated Historical Performance Analysis with kmemtracer
PPTX
Modern ASP.NET Webskills
PPT
Android SDK and PhoneGap
PDF
6 week training presentation
PDF
Efficient JavaScript Unit Testing, JavaOne China 2013
PPTX
[AnDevCon 2016] Mutation Testing for Android
PDF
Android Jump Start
PPTX
OpenDDR and Jakarta MVC - JavaLand 2021
PPTX
OpenDDR and Jakarta MVC - Java2Days 2020 Virtual
PDF
Golang vs node js 2022 which is the better choice for web development (1)
PDF
Level Up Your Android Build -Droidcon Berlin 2015
PPTX
Apache Cordova In Action
PDF
Modern JavaScript Applications: Design Patterns
PDF
Real World AngularJS recipes: beyond TodoMVC
PDF
Jwis2011 ruo ando
PPTX
Microservices for building an IDE - The innards of JetBrains Rider - NDC Oslo...
PDF
Android Development Workshop V2
PDF
Refactoring Wunderlist. UA Mobile 2016.
PDF
Midas - on-the-fly schema migration tool for MongoDB.
Guice tutorial
Automated Historical Performance Analysis with kmemtracer
Modern ASP.NET Webskills
Android SDK and PhoneGap
6 week training presentation
Efficient JavaScript Unit Testing, JavaOne China 2013
[AnDevCon 2016] Mutation Testing for Android
Android Jump Start
OpenDDR and Jakarta MVC - JavaLand 2021
OpenDDR and Jakarta MVC - Java2Days 2020 Virtual
Golang vs node js 2022 which is the better choice for web development (1)
Level Up Your Android Build -Droidcon Berlin 2015
Apache Cordova In Action
Modern JavaScript Applications: Design Patterns
Real World AngularJS recipes: beyond TodoMVC
Jwis2011 ruo ando
Microservices for building an IDE - The innards of JetBrains Rider - NDC Oslo...
Android Development Workshop V2
Refactoring Wunderlist. UA Mobile 2016.
Midas - on-the-fly schema migration tool for MongoDB.
Ad

Similar to Visage Android Hands-on Lab (20)

PDF
Visage Android Hands-on Lab (OSCON)
PPTX
Visage Android - Cleaner APIs, Cleaner UIs
PDF
How to add ar effects to an android app using vr face library
PDF
Understanding the Dalvik Virtual Machine
PDF
Programming Android
PPT
Industrial Training in Android Application
PPTX
Introduction To Google Android (Ft Rohan Bomle)
PDF
[1D6]RE-view of Android L developer PRE-view
DOCX
Notepad tutorial
PPTX
Mobile Application Development- Configuration and Android Installation
PDF
[Android] 2D Graphics
PPTX
Introduction to Android (before 2015)
PPT
Synapse india reviews on i phone and android os
PPT
Android development tutorial
PPT
Synapse india mobile apps update
PPTX
Android development tutorial
PPTX
Introduction to Android- A session by Sagar Das
PDF
Hacking JavaFX with Groovy, Clojure, Scala, and Visage: Stephen Chin
PDF
The best language in the world
Visage Android Hands-on Lab (OSCON)
Visage Android - Cleaner APIs, Cleaner UIs
How to add ar effects to an android app using vr face library
Understanding the Dalvik Virtual Machine
Programming Android
Industrial Training in Android Application
Introduction To Google Android (Ft Rohan Bomle)
[1D6]RE-view of Android L developer PRE-view
Notepad tutorial
Mobile Application Development- Configuration and Android Installation
[Android] 2D Graphics
Introduction to Android (before 2015)
Synapse india reviews on i phone and android os
Android development tutorial
Synapse india mobile apps update
Android development tutorial
Introduction to Android- A session by Sagar Das
Hacking JavaFX with Groovy, Clojure, Scala, and Visage: Stephen Chin
The best language in the world
Ad

More from Stephen Chin (20)

PPTX
DevOps Tools for Java Developers v2
PPTX
10 Ways Everyone Can Support the Java Community
PPTX
Java Clients and JavaFX: The Definitive Guide
PPTX
DevOps Tools for Java Developers
PPTX
Java Clients and JavaFX - Presented to LJC
PPTX
RetroPi Handheld Raspberry Pi Gaming Console
PPTX
JavaFX on Mobile (by Johan Vos)
PPTX
Confessions of a Former Agile Methodologist (JFrog Edition)
PPTX
Devoxx4Kids Lego Workshop
PPTX
Raspberry Pi with Java (JJUG)
PPTX
Confessions of a Former Agile Methodologist
PPTX
Internet of Things Magic Show
PPTX
Zombie Time - JSR 310 for the Undead
PPTX
JCrete Embedded Java Workshop
PPTX
Oracle IoT Kids Workshop
PPTX
OpenJFX on Android and Devices
PPTX
Java on Raspberry Pi Lab
PDF
Java 8 for Tablets, Pis, and Legos
PDF
DukeScript
PPTX
Devoxx4Kids NAO Workshop
DevOps Tools for Java Developers v2
10 Ways Everyone Can Support the Java Community
Java Clients and JavaFX: The Definitive Guide
DevOps Tools for Java Developers
Java Clients and JavaFX - Presented to LJC
RetroPi Handheld Raspberry Pi Gaming Console
JavaFX on Mobile (by Johan Vos)
Confessions of a Former Agile Methodologist (JFrog Edition)
Devoxx4Kids Lego Workshop
Raspberry Pi with Java (JJUG)
Confessions of a Former Agile Methodologist
Internet of Things Magic Show
Zombie Time - JSR 310 for the Undead
JCrete Embedded Java Workshop
Oracle IoT Kids Workshop
OpenJFX on Android and Devices
Java on Raspberry Pi Lab
Java 8 for Tablets, Pis, and Legos
DukeScript
Devoxx4Kids NAO Workshop

Recently uploaded (20)

PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Encapsulation theory and applications.pdf
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
Big Data Technologies - Introduction.pptx
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Machine learning based COVID-19 study performance prediction
PPTX
Spectroscopy.pptx food analysis technology
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
Spectral efficient network and resource selection model in 5G networks
Network Security Unit 5.pdf for BCA BBA.
MIND Revenue Release Quarter 2 2025 Press Release
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
20250228 LYD VKU AI Blended-Learning.pptx
Encapsulation theory and applications.pdf
Unlocking AI with Model Context Protocol (MCP)
The Rise and Fall of 3GPP – Time for a Sabbatical?
Big Data Technologies - Introduction.pptx
Group 1 Presentation -Planning and Decision Making .pptx
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Diabetes mellitus diagnosis method based random forest with bat algorithm
Assigned Numbers - 2025 - Bluetooth® Document
Reach Out and Touch Someone: Haptics and Empathic Computing
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Machine learning based COVID-19 study performance prediction
Spectroscopy.pptx food analysis technology
“AI and Expert System Decision Support & Business Intelligence Systems”
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Per capita expenditure prediction using model stacking based on satellite ima...

Visage Android Hands-on Lab

  • 1. Visage Android Hands-on LabStephen Chin – GXShttp://steveonjava.com/
  • 2. The Visage Language2“Visage is a domain specific language (DSL) designed for the express purpose of writing user interfaces.”Statically Compiled LanguageBased on F3 / JavaFX ScriptPlanning Support for Different Platforms:JavaFX 2.0AndroidApache PivotFlexJSF
  • 3. Language FeaturesDeclarative Object ConstructionCode looks like the UI it is representing. Data BindingVariables can be bound to UI state, allowing automatic updates and behavior to be triggered. Behavior EncapsulationVisage provides closures to make it easy to implement event handlers or other behavior-driven logic. Null SafetyApplication logic will proceed even if intermediate variables are undefined or null. 3
  • 4. Hello World VisageStage {  title: "Hello World"  Scene {    Text {      "Hello World"    }  }}4
  • 5. Visage on Android5Visage Runs as a Native App on AndroidFull Access to all the Android APIsDeclarative Layer on Top of Android APIs
  • 7. Language SimilaritiesJava is…Statically typedCompiled to bytecodesRuns on the JVMHas a large libraryVisage is…Statically typedCompiled to bytecodesRuns on the JVMCan call Java libraries7
  • 9. Integrating Visage and JavaCalling Java from VisageCan call Java interface or classes directlyAutomatic conversion to and from Arrays and CollectionsCan even extend Java interfaces and classesCalling Visage from JavaEasiest way is to create a Java interface that Visage extendsCan invoke Visage as a script and get results back9
  • 11. Exercise 1.A – Android SetupSetup and run the VirtualBox imageCreate an emulator instanceCreate a new Android project from the command lineRun the project in the emulator11
  • 12. Setting Up Your MachineCopy these files off the USB stick:VirtualBox for your platform (mac or windows)VisageLab folderDecompress VisageLab/Visage Dev2.vdi.zipInstall VirtualBoxOpen Visage Dev.vbox12
  • 13. Setting Up Your MachineDownload and Install the Android SDKhttp://developer.android.com/sdk/index.htmlDownload the Visage SDKhttp://code.google.com/p/visage/downloads/listInstall the Android/Visage SDKOn the USB stick13
  • 14. Set Up Your Device for DebuggingAnd mount it from:Devices > USB Devices > (your-device-name)1414
  • 15. Or Create a Virtual Android Device15Launch the AVD Manager by typing: android
  • 16. Setting Up Your ProjectProject creation command:android create project –t 1 –p HelloVisage –k org.test –a HelloVisageArguments:n : Project name (optional)t : Target ID of the new project (required)p : Project directory (required)k : Package name for the application (required)a : Name of the default Activity (required)16
  • 17. Android XML Code<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" ><TextViewandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:text="Hello World, HelloVisage"/></LinearLayout>17
  • 18. Plus some more Java…public class HelloVisage extends Activity {/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedIS) {super.onCreate(savedIS);setContentView(R.layout.main); }}18
  • 19. Run Your Projectcd HelloVisageant installOpen it in the applications menu19
  • 20. Exercise 1.B – All Java ConversionMake sure you have the basic project running firstConvert the XML Code to JavaRun the all Java projectYou should get identical results20
  • 21. Converted XML Code (simplified)public class HelloVisage extends Activity { @Override public void onCreate(Bundle savedIS) {super.onCreate(savedIS);Context context = getApplicationContext();LinearLayout layout = new LinearLayout(context);layout.setOrientation(LinearLayout.VERTICAL);TextView text = new TextView(context);text.setText("Hello World, Java Only");layout.addView(text);setContentView(layout);}}21
  • 22. (and here are the imports…)import android.app.Activity;import android.content.Context;import android.os.Bundle;import android.widget.LinearLayout;import android.widget.TextView;22
  • 23. Exercise 1.C – DDMS DebuggingSo you made a mistake in your code… the compiler can’t catch everything(even if you didn’t make a mistake, force one… a beautiful NullPointerException will do)Launch DDMS and select your emulator/device23
  • 24. Break the code (change in bold)public class HelloVisage extends Activity { @Override public void onCreate(Bundle savedIS) {super.onCreate(savedIS);Context context = getApplicationContext();LinearLayoutlayout = null;//new LinearLayout(context);layout.setOrientation(LinearLayout.VERTICAL);TextView text = new TextView(context);text.setText("Hello World, HelloVisage");layout.addView(text);setContentView(layout);}}24
  • 25. DDMS Displaying a Stack Trace25
  • 26. Exercise 1.D – Visage PortModify the build script to compile VisageCopy the Visage Runtime librariesConvert the Java code to VisageRun on device/emulator26
  • 27. Modify the Build Script (1)<target name="-post-compile"> <path id="android.classpath"> <filesetdir="./libs" includes="*.jar" /> <path refid="android.target.classpath"/> <pathelement location="${out.classes.absolute.dir}"/> </path> <pathconvertrefid="android.classpath" property="androidcpath"/> <path id="visage.sources"> <filesetdir="${source.absolute.dir}" includes="**/*.fx"/> </path>27
  • 28. Modify the Build Script (2) <pathconvertrefid="visage.sources" property="visagepath" pathsep=" "/> <exec executable="${visagehome}/bin/javafxc${binary.extension}" failonerror="true" logerror="true"> <arg value="-d"/> <arg value="${out.classes.absolute.dir}"/> <arg value="-cp"/> <arg value="${androidcpath}"/> <arg line="${visagepath}"/> </exec></target>28
  • 30. Copy Over the Runtime JARCopy:javafxrt.jarFrom:$visagehome/lib/shared/To:$projectdir/libs30
  • 31. Straight JavaFX Conversion...public class Test extends Activity { override function onCreate(savedInstanceState:Bundle) {super.onCreate(savedInstanceState);def context = getApplicationContext();def layout = new LinearLayout(context);layout.setOrientation(LinearLayout.VERTICAL);def text = new TextView(context);text.setText("Hello World, Hello Long Visage");layout.addView(text);setContentView(layout);}}31
  • 32. Rename your source file*.java -> *.fx32
  • 33. Exercise 1.E – Simplified VisageInclude the visage-android jarModify the Visage code to use the new APIsRun on device/emulator33
  • 34. Copy the visage-android JARCopy:visage-android.jarFrom:/home/visage/visage-android/dist/To:$projectdir/libs34
  • 35. Android JavaFX Codepublic class HelloVisage extends Activity { override var view = LinearLayout { orientation: Orientation.VERTICAL view: TextView { text: "Hello World, Beautified Visage" } }}35
  • 36. And change the imports…org.visage.android.app.Activity;org.visage.android.widget.LinearLayout;org.visage.android.widget.Orientation;org.visage.android.widget.TextView;36
  • 37. Working Hello Visage Application37
  • 40. Visage Operators40Multiplication and division of two durations is allowed, but not meaningful
  • 41. Underflows/Overflows will fail silently, producing inaccurate results
  • 42. Divide by zero will throw a runtime exceptionVisage Operators (continued)41
  • 44. Data BindingA variable or a constant can be bound to an expressionvar x = bind a + b;The bound expression is rememberedThe dependencies of the expression is watchedVariable is updated lazily when possible43
  • 46. Exercise 2.A – NetBeans IntegrationCreate a new JavaFXNetBeans projectMerge in build scripts from Android projectStart coding!45
  • 47. Create a new JavaFX ProjectFile > New Project…Name the project “ConfigReporter”In package "org.test"46
  • 48. Merging Project FoldersCopy these files over:*.propertiesAndroidManifest.xmlres/libs/proguard.cfgbuild.xml [replace]47
  • 49. Merging Build ScriptsUpdate the build.xml file:Set the project name to “ConfigReporter”Update the strings.xml file:Set the app_name to “ConfigReporter”Load the NetBeans property files (in build.xml):<property file="nbproject/private/config.properties"/><property file="nbproject/private/configs/${config}.properties"/><property file="nbproject/private/private.properties"/><property file="${user.properties.file}"/><property file="nbproject/configs/${config}.properties"/><property file="nbproject/project.properties"/>48
  • 50. Alias NetBeans Targets:<target name="launch" depends="install”> <exec executable="${adb}" failonerror="true"> <arg line="${adb.device.arg}"/> <arg value="shell"/> <arg value="am"/> <arg value="start"/> <arg value="-n"/> <arg value=”org.test/.ConfigReporter"/> <arg value="-a"/> <arg value="android.intent.action.MAIN"/> </exec></target><target name="jar" depends="compile"/><target name="run" depends="launch"/>49
  • 51. Update AndroidManifest.xmlChange project name to "ConfigReporter"50
  • 52. Modify Project PropertiesSet JavaFX Platform to “Visage_SDK”Add Libraries:“libs” folderandroid.jar51
  • 53. Update ConfigReporter.fxMake it extend the visage Activity classFor now, you can copy the logic from HelloVisage52
  • 54. Exercise 2.C – Android ControlsCreate a Text FieldCreate an Edit BoxWire them up using Binding53
  • 55. Bound Controls (1)override var view = LinearLayout {orientation: Orientation.VERTICALvarsecret:String;view: [EditText {hint: "Super Secret Text”password: truetext: bind secret with inverse54
  • 56. Bound Controls (2)}TextView {text: "Is Revealed!!!”}TextView {text: bind secret}]}55
  • 57. Exercise 2.D – Button HandlerCreate a Button ControlAdd an onClick handlerMake something happen (maybe a bind)56
  • 58. Button onClick handlerButton { text: "Launch Settings"onClick: function() {startActivity(new Intent(this, Settings.class)); setting = "Launching..."; }}TextView { text: "Setting is:"}TextView { text: bind setting}57
  • 59. Exercise 2.E – Android SettingsCreate a Settings ActivityPopulate it with the following preferences:TextPasswordListLaunch it from the Button control58
  • 60. Settings Classpublic class Settings extends PreferenceActivity {varusernamePref:EditTextPreference;varpasswordPref:EditTextPreference;varpollingPref:ListPreference; override var screen = PreferenceScreen { preferences: [ …59
  • 61. Text PreferencePreferenceCategory { title: "Preferences" preferences: [usernamePref = EditTextPreference { title: "Username" key: "usernamePref" summary: bind if (usernamePref.text == "") "Currently undefined" else "Current value: {usernamePref.text}"}60
  • 62. Password PreferencepasswordPref = EditTextPreference { title: "Password” key: "passwordPref” summary: bind passwordPref.text.replaceAll(".", "*");}61
  • 63. List PreferencepollingPref= ListPreference { title: "Polling Interval"key: "pollingPref"defaultValue: "60000"entries: ["30 seconds", "1 minute", "5 minutes", "10 minutes", "15 minutes", "30 minutes", "1 hour"]entryValues: ["30000", "60000", "300000", "600000", "900000", "1800000", "3600000"]summary: bind pollingPref.entry}62
  • 64. Service MetadataUpdate AndroidManifest.xml:<activity android:name=".Settings" android:label="@string/settings_label"/>Update string.xml:<string name="settings_label">Settings</string>63
  • 65. Invoke the new serviceIn the onClick handler:startActivity(new Intent(this, Settings.class));64
  • 68. What Bind Updatesvar x = bind if(a) then b else cx is updated if a or b or c changesvar x = bind for (i in [a..b]) { i * i }Not everything is recalculatedIf a = 1 and b = 2, x is [1, 4]If b changes to 3, only the added element is calculated67149
  • 69. Binding to ExpressionsBinding to a blockBound block may contain any number of defs followed by one expressionDependencies of block is backtraced from the expressionBinding to function invocation expressionRegular function: dependencies are parametersBound function: backtraced from final expression inside function68
  • 70. Binding to Object Literalsvar a = 3; var b = 4;var p = bind Point { x: a, y: b };var q = bind Point { x: bind a, y: b };var r = bind Point { x: bind a, y: bind b };When a changes:p gets a new instance of Pointq and r keep the old instance with a new x valuer will never get a new instance of Point(the outer bind in r is useless)69
  • 71. Visage SequencesRepresents collections of homogeneous dataA fundamental container data typeRich set of language facilitiesContributor to declarative syntaxAutomatic conversion to and from Java Arrays and Collections70
  • 72. Creating SequencesExplicit sequence expression[1, 3, 5, 7, 9]Elements are separated by commasComma may be omitted if element ends with brace7113579
  • 73. Creating SequencesNumeric sequence with range expressions:[1..10]Can have a step:[1..10 step 2][0.0..0.9 step 0.1]Can be decreasing:[10..1 step -3]Beware of step that goes opposite direction:[10..1] is []Exclusive right end[1..<5]7212345678910135790.1.2.3.4.5.6.7.8.9107411234
  • 74. Getting Info from Sequencesints = [1, 3, 5, 7, 9]sizeofintsis 5ints[0] is 1, ints[1] is 3, ..., ints[4] is 9ints[-1] is 0 (default value of Integer), so is ints[5]For a sequence of objects, the default is null7313579[0][1][2][3][4]
  • 75. Getting Slices from Sequencesints = [1, 3, 5, 7, 9]ints[0..2] is [1, 3, 5]ints[0..<2] is [1, 3]ints[2..] is [5, 7, 9]ints[2..<] is [5, 7]ints[2..0], ints[-2..-1], ints[5..6] are all []s7413579[0][1][2][3][4]
  • 76. Getting Subsets from Sequencesints = [1, 3, 5, 7, 9]ints[k | k > 6] is:[7, 9] (k > 6 is a condition)ints[k | indexof k < 2] is:[1, 3]ints[k | k > 10] is:[]7513579[0][1][2][3][4]
  • 77. Inserting into Sequencesints = [1, 3, 5, 7, 9]insert 20 into intsinsert 30 before ints[2]insert 40 after ints[4]insert [50, 60] into ints1357913579201357920301357920304013579203040506076
  • 78. Deleting from Sequencesints = [1, 3, 5, 7, 9]delete 7 from intsdelete ints[0]delete ints[0..1]delete ints: ints becomes []135791357913593599
  • 79. Sequence PuzzlersWhat is the size of this sequence:[1..10 step -1]What does this evaluate to:[10..<20 step 2][k|k>17]What is the size of this sequence:sizeof [20..1 step -3]781A: 02A: [18]3A: 1
  • 80. Module 3EXTENDING VISAGE ANDROID APIs79Become a Visage contributor!Join me in the Hackergartenafter the session