SlideShare a Scribd company logo
1 of 40
So you want to build Android apps… without Java? Nick Plante @zapnap (A brief introduction to Mirah and Pindah)
Who? Nick Plante (not a Java developer) Zerosum Labs Rails Rumble Rubydoc.info Chinaccelerator Contact me! @zapnap on Twitter http://github.com/zapnap
Why? Because you’re a Ruby developer (familiarity). Because Android is awesome. Because simplicity is elegance. “Think Different.”
Java vs Ruby Dynamic vs Static Simplicity vs Complexity & Verbosity Less Ceremony Java is a systems programming language, after all But… The JVM is an awesome platform Android’s use of the JVM (Dalvik) gives us options
Java Alternatives Android Scripting Environment (SL4A) Great for scripting; not great for applications Limited access to Android API / GUI Performance issues Other JVM-based languages: Scala Clojure JRuby Mirah Groovy?
JRuby & MrRuboto Ruboto is your friend! JRuby interface / framework for Android APIs http://ruboto.org But JRuby runtime overhead is a problem Slow startup (~10 seconds) Large APK size HelloWorld: 3.4MB compressed, 10MB installed
Introducing Mirah Mirah compiles straight to Java bytecode Very fast, no extra overhead Syntax is very Ruby-ish Statically-typed with local type inference “Ruby with type annotations” No runtime library Mix and match Java code
Warning! Mirah is still a very young language (v0.0.7) Tooling is very, very alpha Advantage: Eclipse (Java) Redcar looks promising Compilation errors are very, very not-so-fun NativeException: jmeta.SyntaxError: expected Ensure before ' { |a b| Inte' (at line: 16, char: 40)
One thing at a time We’ll get to Android in just a second First let’s see some basic Mirah syntax…
# fib.mirah def fib(a:int):int   if a < 2     a   else     fib(a-1) + fib(a-2)   end end puts fib(20) Ruby vsMirah Parameter type declaration??? SRSLY?  # fib.ruby def fib(a)   if a < 2     a   else     fib(a-1) + fib(a-2)   end end puts fib(20) Return type can often be inferred.
.class output Produces a java .class $ mirahcfib.mirah public static intfib(int) Can also produce .java code $ mirahc -jfib.mirah * I have no idea why you would want to do this.
.to_java => “ick” // Generated from hello.mirah public class Hello extends java.lang.Object { public static void main(java.lang.String[] argv) { java.io.PrintStream temp$1 = java.lang.System.out;     temp$1.println(Hello.fib(20));   }   public static intfib(int a) {     return (a < 2) ? (a) : ((Hello.fib((a - 1)) + Hello.fib((a - 2))));   } }
Challenges / Major Differences Java stdlib: both a blessing and a curse List, HashMap, etc arr.get(1) vs arr[0] Blocks work, but syntactic sugar required For example, List#eachcan be used (array) But HashMap#eachdoes not exist No optional arguments, no *splats, no ranges
Using Java’s Standard Library import java.util.Collections import java.util.HashMap import java.util.List class ListPrinter   def print(list:List)     puts "first item: #{list.get(0)}" list.each do |item|       puts "item: #{item}"     end    end  end class HashPrinter   def print(map:HashMap) map.keySet.each do |key|       puts "#{key}: #{map.get(key)}"     end    end  end map = { 'batman' => 'brucewayne', 'superman' => 'clarkkent' } HashPrinter.new.print(map) list = ['peter', 'stewie', 'brian'] ListPrinter.new.print(list)
Get Mirah # Install JRuby 1.6 if you haven’t already # (or rvm use jruby) $ jruby –S gem install mirah $ mirah-e "puts 'hello world'” > hello world
Now What?
Get the Android SDK Download and install it: http://developer.android.com/sdk/index.html Notes on building from the command line:  http://developer.android.com/guide/developing/projects/projects-cmdline.html Set up your environment (see above): Make sure to set JAVA_HOME, CLASSPATH, and put your platform-tools directory in your path
Android SDK / Virtual Devices
The anatomy of a typical Android application Activities Intents Manifest File XML Layouts (Views) Services Content Providers (Lots to learn)
Hello Pindah Garrett, Protoform, Mirahndroid => Pindah Goals Make it easy to get started with Android + Mirah Make day to day development tasks easier Provide project structure and conventions Application skeleton generator Rake tasks to hide Ant nastiness Because XML is pain Use Rake to compile / debug / install / etc
What Pindah Does NOT Do No “pretty” wrappers for Android APIs You must learn the APIs to work effectively Does not provide alternatives to XML-based Manifest or view layouts https://github.com/objo/droid-views
Get Pindah # For more information, see # http://github.com/mirah/pindah $ jruby –S gem installpindah # Generate an Android application skeleton $pindahcreate org.example.hello [/path/to/hello_world] [HelloActivity]
Android App Skeleton ├── AndroidManifest.xml ├── Rakefile ├── libs ├── res │   ├── drawable-hdpi │   │   └── ic_launcher.png │   ├── drawable-ldpi │   │   └── ic_launcher.png │   ├── drawable-mdpi │   │   └── ic_launcher.png │   ├── layout │   │   └── main.xml │   └── values │       └── strings.xml └── src     └── org         └── example             └── hello                 └── HelloActivity.mirah Managed for you by Pindah: ,[object Object]
build.properties
local.properties
build.xml,[object Object]
Android Activity Boilerplate # HelloActivity.mirah package org.example.hello import android.app.Activity class HelloActivity < Activity   def onCreate(state)     super state setContentViewR.layout.main   end end # HelloActivity.java package org.example.hello; import android.app.Activity; public class HelloActivity   extends Activity {   /** Called when the activity is first created. */   @Override  public void onCreate(     Bundle savedInstanceState)  { super.onCreate( savedInstanceState); setContentView( R.layout.main);  } }
Running the Example App $ cdhello_world $ rake install => WIN.
Well, that was boring
Slightly  More Interesting More expressive code == visible improvement Example application “Up or Down?” website testing app http://github.com/zapnap/upordown Questions: What do Android callbacks look like? How do I leverage 3rd party (Java) libraries? How do I handle exceptions? How does Mirah deal with scope? (it’s weird)
Up or Down? Down or Up?
Android Listeners (Java) // Sample button click listener in Java // Create an anonymous implementation of OnClickListener private OnClickListenermClickListener = new OnClickListener() {     public void onClick(Viewv) {       // handle click event   } }; protected void onCreate(BundlesavedValues) {     ...     // Capture our button from layout     Button mSubmit = (Button)findViewById(R.id.submit_btn);     // Register the onClick listener with theimpl above mSubmit.setOnClickListener(mClickListener);     ... }
StatusActivity + Listeners class StatusActivity < Activity   def onCreate(state)     super state setContentViewR.layout.main     @url = EditTextfindViewById(R.id.url_txt) @submit = Button findViewById(R.id.submit_btn) setListeners end   def setListeners     this = self     # SHORTCUT: click listener must implement onClick     @submit.setOnClickListener do |v|       status = this.checkSiteStatus(this.getUrl) this.showResult status     end   end Scoping for ivars and self is incomplete. Assign a local var within scope. Easy to add anonymous listeners with this syntax (implements a single method interface)
Using External Java Libraries Put jars in libs folder and import to use. Simple! (must import Android libs too) import java.net.URL import java.net.SocketTimeoutException import org.jsoup.Jsoup import org.jsoup.nodes.Document def checkSiteStatus(address:String):String return "Please specify a URL to test" if address.equals('') begin doc = Jsoup.connect(       "http://downforeveryoneorjustme.com/" + address     ).get res = doc.select("#container").first.text Log.d 'StatusActivity',           'Full response from server is: ' + res res.substring(0, res.indexOf('Check another')) rescue SocketTimeoutException => ex "Unable to contact the server. How ironic!” end end Exception handling works like it does in Ruby. Must import specific exceptions.
Wrapping Up: Dialog Example def getUrl @url.getText.toString end def showResult(message:String) alert = AlertDialog.Builder.new(self) alert.setTitle 'Site Test Results’ alert.setMessage message alert.setPositiveButton('OK') do |dialog, w| dialog.dismiss end alert.show end
Android XML Layouts (main.xml) <?xml version="1.0" encoding="utf-8"?> <RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">     <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content">         <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_horizontal" android:textSize="20sp" android:textStyle="bold" android:text="@string/app_title" />         <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_horizontal" android:textSize="18sp" android:textStyle="bold" android:layout_marginBottom="10dip" android:text="@string/app_subtitle" />         <EditTextandroid:id="@+id/url_txt" android:layout_width="fill_parent" android:singleLine = "true" android:layout_height="wrap_content" android:inputType="textUri" android:hint="@string/url_example" />         <Button android:id="@+id/submit_btn" android:layout_width="140dip" android:layout_marginTop="6dip" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" android:text="@string/submit_btn" />     </LinearLayout>     <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_horizontal" android:layout_alignParentBottom="true" android:autoLink="web" android:text="@string/powered_by" /> </RelativeLayout> <EditTextandroid:id="@+id/url_txt" android:layout_width="fill_parent" android:singleLine = "true" android:layout_height="wrap_content" android:inputType="textUri" android:hint="@string/url_example" /> more info app title [ url input ] [ button]
One More Thing Android Manifest lists top-level activities and required permissions Our app requires Internet access Add the permission to AndroidManifest.xml: <uses-permission android:name="android.permission.INTERNET" />
It Works!
Ideas for Next Steps Implement a ProgressDialog And perform the site check in an AsyncTask Record a log of website test history to a ListView Allow users to browse test history through a separate Activity Store test history to a local Sqlite database (and ListAdapter) Fork me at  http://github.com/zapnap/upordown

More Related Content

What's hot

ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developers
Bartosz Kosarzycki
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developers
Bartosz Kosarzycki
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Language
intelliyole
 
(ThoughtWorks Away Day 2009) one or two things you may not know about typesys...
(ThoughtWorks Away Day 2009) one or two things you may not know about typesys...(ThoughtWorks Away Day 2009) one or two things you may not know about typesys...
(ThoughtWorks Away Day 2009) one or two things you may not know about typesys...
Phil Calçado
 
JDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easyJDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easy
José Paumard
 

What's hot (20)

Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2
 
ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developers
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developers
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
Kotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime PerformanceKotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime Performance
 
Kotlin as a Better Java
Kotlin as a Better JavaKotlin as a Better Java
Kotlin as a Better Java
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Language
 
Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
 
Kotlin hands on - MorningTech ekito 2017
Kotlin hands on - MorningTech ekito 2017Kotlin hands on - MorningTech ekito 2017
Kotlin hands on - MorningTech ekito 2017
 
Lisp Macros in 20 Minutes (Featuring Clojure)
Lisp Macros in 20 Minutes (Featuring Clojure)Lisp Macros in 20 Minutes (Featuring Clojure)
Lisp Macros in 20 Minutes (Featuring Clojure)
 
Kotlin
KotlinKotlin
Kotlin
 
A Re-Introduction to JavaScript
A Re-Introduction to JavaScriptA Re-Introduction to JavaScript
A Re-Introduction to JavaScript
 
Kotlin in action
Kotlin in actionKotlin in action
Kotlin in action
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
Alfresco the clojure way
Alfresco the clojure wayAlfresco the clojure way
Alfresco the clojure way
 
Java 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelizationJava 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelization
 
(ThoughtWorks Away Day 2009) one or two things you may not know about typesys...
(ThoughtWorks Away Day 2009) one or two things you may not know about typesys...(ThoughtWorks Away Day 2009) one or two things you may not know about typesys...
(ThoughtWorks Away Day 2009) one or two things you may not know about typesys...
 
JDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easyJDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easy
 

Viewers also liked

RubyConf Brazil 2010 - Mirah
RubyConf Brazil 2010 - MirahRubyConf Brazil 2010 - Mirah
RubyConf Brazil 2010 - Mirah
Charles Nutter
 
超絶技巧プログラミングと Ruby 3.0 (大江戸 Ruby 会議 05 コミッタ LT)
超絶技巧プログラミングと Ruby 3.0 (大江戸 Ruby 会議 05 コミッタ LT)超絶技巧プログラミングと Ruby 3.0 (大江戸 Ruby 会議 05 コミッタ LT)
超絶技巧プログラミングと Ruby 3.0 (大江戸 Ruby 会議 05 コミッタ LT)
mametter
 

Viewers also liked (12)

Rejectkaigi 2010
Rejectkaigi 2010Rejectkaigi 2010
Rejectkaigi 2010
 
RubyConf Brazil 2010 - Mirah
RubyConf Brazil 2010 - MirahRubyConf Brazil 2010 - Mirah
RubyConf Brazil 2010 - Mirah
 
JavaとRubyのすてきな関係
JavaとRubyのすてきな関係JavaとRubyのすてきな関係
JavaとRubyのすてきな関係
 
Opal - Ruby Style!! Ruby in the browser
Opal - Ruby Style!!  Ruby in the browserOpal - Ruby Style!!  Ruby in the browser
Opal - Ruby Style!! Ruby in the browser
 
Rubyの拡張をCrystalで書いてみる
Rubyの拡張をCrystalで書いてみるRubyの拡張をCrystalで書いてみる
Rubyの拡張をCrystalで書いてみる
 
LSTM (Long short-term memory) 概要
LSTM (Long short-term memory) 概要LSTM (Long short-term memory) 概要
LSTM (Long short-term memory) 概要
 
Opal chapter 4_a_new_hope
Opal chapter 4_a_new_hopeOpal chapter 4_a_new_hope
Opal chapter 4_a_new_hope
 
Learning to forget continual prediction with lstm
Learning to forget continual prediction with lstmLearning to forget continual prediction with lstm
Learning to forget continual prediction with lstm
 
Ruby 風シンタックスな静的言語 Crystal の紹介
Ruby 風シンタックスな静的言語 Crystal の紹介Ruby 風シンタックスな静的言語 Crystal の紹介
Ruby 風シンタックスな静的言語 Crystal の紹介
 
超絶技巧プログラミングと Ruby 3.0 (大江戸 Ruby 会議 05 コミッタ LT)
超絶技巧プログラミングと Ruby 3.0 (大江戸 Ruby 会議 05 コミッタ LT)超絶技巧プログラミングと Ruby 3.0 (大江戸 Ruby 会議 05 コミッタ LT)
超絶技巧プログラミングと Ruby 3.0 (大江戸 Ruby 会議 05 コミッタ LT)
 
ユーザーストーリー駆動開発で行こう。
ユーザーストーリー駆動開発で行こう。ユーザーストーリー駆動開発で行こう。
ユーザーストーリー駆動開発で行こう。
 
JSON Schema と API テスト YAPC::Asia Tokyo 2014
JSON Schema と API テスト YAPC::Asia Tokyo 2014JSON Schema と API テスト YAPC::Asia Tokyo 2014
JSON Schema と API テスト YAPC::Asia Tokyo 2014
 

Similar to Building native Android applications with Mirah and Pindah

Testing of javacript
Testing of javacriptTesting of javacript
Testing of javacript
Lei Kang
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpm
som_nangia
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpm
wilburlo
 
Baruco 2014 - Rubymotion Workshop
Baruco 2014 - Rubymotion WorkshopBaruco 2014 - Rubymotion Workshop
Baruco 2014 - Rubymotion Workshop
Brian Sam-Bodden
 

Similar to Building native Android applications with Mirah and Pindah (20)

Developing cross platform desktop application with Ruby
Developing cross platform desktop application with RubyDeveloping cross platform desktop application with Ruby
Developing cross platform desktop application with Ruby
 
How to code to code less
How to code to code lessHow to code to code less
How to code to code less
 
Ruby conf2012
Ruby conf2012Ruby conf2012
Ruby conf2012
 
Demystifying Maven
Demystifying MavenDemystifying Maven
Demystifying Maven
 
Plack - LPW 2009
Plack - LPW 2009Plack - LPW 2009
Plack - LPW 2009
 
Adventurous Merb
Adventurous MerbAdventurous Merb
Adventurous Merb
 
Introduction to Software Development
Introduction to Software DevelopmentIntroduction to Software Development
Introduction to Software Development
 
Javalecture 1
Javalecture 1Javalecture 1
Javalecture 1
 
Testing of javacript
Testing of javacriptTesting of javacript
Testing of javacript
 
Using Ruby in Android Development
Using Ruby in Android DevelopmentUsing Ruby in Android Development
Using Ruby in Android Development
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpm
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpm
 
All a flutter about Flutter.io
All a flutter about Flutter.ioAll a flutter about Flutter.io
All a flutter about Flutter.io
 
Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end Framework
 
ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...
ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...
ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...
 
Griffon: Re-imaging Desktop Java Technology
Griffon: Re-imaging Desktop Java TechnologyGriffon: Re-imaging Desktop Java Technology
Griffon: Re-imaging Desktop Java Technology
 
Griffon - Making Swing Fun Again
Griffon - Making Swing Fun AgainGriffon - Making Swing Fun Again
Griffon - Making Swing Fun Again
 
Baruco 2014 - Rubymotion Workshop
Baruco 2014 - Rubymotion WorkshopBaruco 2014 - Rubymotion Workshop
Baruco 2014 - Rubymotion Workshop
 
Griffon Presentation
Griffon PresentationGriffon Presentation
Griffon Presentation
 
Building End to-End Web Apps Using TypeScript
Building End to-End Web Apps Using TypeScriptBuilding End to-End Web Apps Using TypeScript
Building End to-End Web Apps Using TypeScript
 

Recently uploaded

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Recently uploaded (20)

Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 

Building native Android applications with Mirah and Pindah

  • 1. So you want to build Android apps… without Java? Nick Plante @zapnap (A brief introduction to Mirah and Pindah)
  • 2. Who? Nick Plante (not a Java developer) Zerosum Labs Rails Rumble Rubydoc.info Chinaccelerator Contact me! @zapnap on Twitter http://github.com/zapnap
  • 3. Why? Because you’re a Ruby developer (familiarity). Because Android is awesome. Because simplicity is elegance. “Think Different.”
  • 4. Java vs Ruby Dynamic vs Static Simplicity vs Complexity & Verbosity Less Ceremony Java is a systems programming language, after all But… The JVM is an awesome platform Android’s use of the JVM (Dalvik) gives us options
  • 5. Java Alternatives Android Scripting Environment (SL4A) Great for scripting; not great for applications Limited access to Android API / GUI Performance issues Other JVM-based languages: Scala Clojure JRuby Mirah Groovy?
  • 6. JRuby & MrRuboto Ruboto is your friend! JRuby interface / framework for Android APIs http://ruboto.org But JRuby runtime overhead is a problem Slow startup (~10 seconds) Large APK size HelloWorld: 3.4MB compressed, 10MB installed
  • 7. Introducing Mirah Mirah compiles straight to Java bytecode Very fast, no extra overhead Syntax is very Ruby-ish Statically-typed with local type inference “Ruby with type annotations” No runtime library Mix and match Java code
  • 8.
  • 9. Warning! Mirah is still a very young language (v0.0.7) Tooling is very, very alpha Advantage: Eclipse (Java) Redcar looks promising Compilation errors are very, very not-so-fun NativeException: jmeta.SyntaxError: expected Ensure before ' { |a b| Inte' (at line: 16, char: 40)
  • 10. One thing at a time We’ll get to Android in just a second First let’s see some basic Mirah syntax…
  • 11. # fib.mirah def fib(a:int):int if a < 2 a else fib(a-1) + fib(a-2) end end puts fib(20) Ruby vsMirah Parameter type declaration??? SRSLY?  # fib.ruby def fib(a) if a < 2 a else fib(a-1) + fib(a-2) end end puts fib(20) Return type can often be inferred.
  • 12. .class output Produces a java .class $ mirahcfib.mirah public static intfib(int) Can also produce .java code $ mirahc -jfib.mirah * I have no idea why you would want to do this.
  • 13. .to_java => “ick” // Generated from hello.mirah public class Hello extends java.lang.Object { public static void main(java.lang.String[] argv) { java.io.PrintStream temp$1 = java.lang.System.out; temp$1.println(Hello.fib(20)); } public static intfib(int a) { return (a < 2) ? (a) : ((Hello.fib((a - 1)) + Hello.fib((a - 2)))); } }
  • 14. Challenges / Major Differences Java stdlib: both a blessing and a curse List, HashMap, etc arr.get(1) vs arr[0] Blocks work, but syntactic sugar required For example, List#eachcan be used (array) But HashMap#eachdoes not exist No optional arguments, no *splats, no ranges
  • 15. Using Java’s Standard Library import java.util.Collections import java.util.HashMap import java.util.List class ListPrinter def print(list:List) puts "first item: #{list.get(0)}" list.each do |item| puts "item: #{item}" end end end class HashPrinter def print(map:HashMap) map.keySet.each do |key| puts "#{key}: #{map.get(key)}" end end end map = { 'batman' => 'brucewayne', 'superman' => 'clarkkent' } HashPrinter.new.print(map) list = ['peter', 'stewie', 'brian'] ListPrinter.new.print(list)
  • 16. Get Mirah # Install JRuby 1.6 if you haven’t already # (or rvm use jruby) $ jruby –S gem install mirah $ mirah-e "puts 'hello world'” > hello world
  • 18. Get the Android SDK Download and install it: http://developer.android.com/sdk/index.html Notes on building from the command line: http://developer.android.com/guide/developing/projects/projects-cmdline.html Set up your environment (see above): Make sure to set JAVA_HOME, CLASSPATH, and put your platform-tools directory in your path
  • 19. Android SDK / Virtual Devices
  • 20. The anatomy of a typical Android application Activities Intents Manifest File XML Layouts (Views) Services Content Providers (Lots to learn)
  • 21. Hello Pindah Garrett, Protoform, Mirahndroid => Pindah Goals Make it easy to get started with Android + Mirah Make day to day development tasks easier Provide project structure and conventions Application skeleton generator Rake tasks to hide Ant nastiness Because XML is pain Use Rake to compile / debug / install / etc
  • 22. What Pindah Does NOT Do No “pretty” wrappers for Android APIs You must learn the APIs to work effectively Does not provide alternatives to XML-based Manifest or view layouts https://github.com/objo/droid-views
  • 23. Get Pindah # For more information, see # http://github.com/mirah/pindah $ jruby –S gem installpindah # Generate an Android application skeleton $pindahcreate org.example.hello [/path/to/hello_world] [HelloActivity]
  • 24.
  • 27.
  • 28. Android Activity Boilerplate # HelloActivity.mirah package org.example.hello import android.app.Activity class HelloActivity < Activity def onCreate(state) super state setContentViewR.layout.main end end # HelloActivity.java package org.example.hello; import android.app.Activity; public class HelloActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate( Bundle savedInstanceState) { super.onCreate( savedInstanceState); setContentView( R.layout.main); } }
  • 29. Running the Example App $ cdhello_world $ rake install => WIN.
  • 30. Well, that was boring
  • 31. Slightly More Interesting More expressive code == visible improvement Example application “Up or Down?” website testing app http://github.com/zapnap/upordown Questions: What do Android callbacks look like? How do I leverage 3rd party (Java) libraries? How do I handle exceptions? How does Mirah deal with scope? (it’s weird)
  • 32. Up or Down? Down or Up?
  • 33. Android Listeners (Java) // Sample button click listener in Java // Create an anonymous implementation of OnClickListener private OnClickListenermClickListener = new OnClickListener() { public void onClick(Viewv) { // handle click event } }; protected void onCreate(BundlesavedValues) { ... // Capture our button from layout Button mSubmit = (Button)findViewById(R.id.submit_btn); // Register the onClick listener with theimpl above mSubmit.setOnClickListener(mClickListener); ... }
  • 34. StatusActivity + Listeners class StatusActivity < Activity def onCreate(state) super state setContentViewR.layout.main @url = EditTextfindViewById(R.id.url_txt) @submit = Button findViewById(R.id.submit_btn) setListeners end def setListeners this = self # SHORTCUT: click listener must implement onClick @submit.setOnClickListener do |v| status = this.checkSiteStatus(this.getUrl) this.showResult status end end Scoping for ivars and self is incomplete. Assign a local var within scope. Easy to add anonymous listeners with this syntax (implements a single method interface)
  • 35. Using External Java Libraries Put jars in libs folder and import to use. Simple! (must import Android libs too) import java.net.URL import java.net.SocketTimeoutException import org.jsoup.Jsoup import org.jsoup.nodes.Document def checkSiteStatus(address:String):String return "Please specify a URL to test" if address.equals('') begin doc = Jsoup.connect( "http://downforeveryoneorjustme.com/" + address ).get res = doc.select("#container").first.text Log.d 'StatusActivity', 'Full response from server is: ' + res res.substring(0, res.indexOf('Check another')) rescue SocketTimeoutException => ex "Unable to contact the server. How ironic!” end end Exception handling works like it does in Ruby. Must import specific exceptions.
  • 36. Wrapping Up: Dialog Example def getUrl @url.getText.toString end def showResult(message:String) alert = AlertDialog.Builder.new(self) alert.setTitle 'Site Test Results’ alert.setMessage message alert.setPositiveButton('OK') do |dialog, w| dialog.dismiss end alert.show end
  • 37. Android XML Layouts (main.xml) <?xml version="1.0" encoding="utf-8"?> <RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_horizontal" android:textSize="20sp" android:textStyle="bold" android:text="@string/app_title" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_horizontal" android:textSize="18sp" android:textStyle="bold" android:layout_marginBottom="10dip" android:text="@string/app_subtitle" /> <EditTextandroid:id="@+id/url_txt" android:layout_width="fill_parent" android:singleLine = "true" android:layout_height="wrap_content" android:inputType="textUri" android:hint="@string/url_example" /> <Button android:id="@+id/submit_btn" android:layout_width="140dip" android:layout_marginTop="6dip" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" android:text="@string/submit_btn" /> </LinearLayout> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_horizontal" android:layout_alignParentBottom="true" android:autoLink="web" android:text="@string/powered_by" /> </RelativeLayout> <EditTextandroid:id="@+id/url_txt" android:layout_width="fill_parent" android:singleLine = "true" android:layout_height="wrap_content" android:inputType="textUri" android:hint="@string/url_example" /> more info app title [ url input ] [ button]
  • 38. One More Thing Android Manifest lists top-level activities and required permissions Our app requires Internet access Add the permission to AndroidManifest.xml: <uses-permission android:name="android.permission.INTERNET" />
  • 40. Ideas for Next Steps Implement a ProgressDialog And perform the site check in an AsyncTask Record a log of website test history to a ListView Allow users to browse test history through a separate Activity Store test history to a local Sqlite database (and ListAdapter) Fork me at http://github.com/zapnap/upordown
  • 41. Conclusions (or lack thereof) Mirah is a nice midpoint between Ruby and Java Well-suited for Dalvik JVM work But still very immature / not yet practical for daily use Opportunity to help push mobile dev forward Lack of good IDE support Makes working with the (massive) Android API difficult Debugging is a pain in the butt ADB (Rake logcat) is incredibly useful; learn to use it I personally still prefer mobile web development ;-) but sometimes native is the way to go!
  • 42.