SlideShare a Scribd company logo
Who are you?
def speaker = new SZJUG.Speaker(
name: 'Alexey Zhokhov',
employer: 'Scentbird',
occupation: 'Grails Developer',
github: 'donbeave',
email: 'alexey@zhokhov.com',
site: 'http://www.zhokhov.com',
description: """whole-stack engineer
(back-end, front-end, mobile, UI/UX)"""
)
Android on Gradle
Groovy is inside the Gradle
You probably know Groovy through Gradle already.
Groovy is a superset of Java.
It contains lots of cool stuff that makes Java fun!
So,
Why can Groovy be
Android' Swift?
Android N supports Java 8
"Android is in the Java stone age state"
But not released
Multi-faceted language:
Object-oriented
Dynamic
Functional
Static
Groovy is
Straightforward integration with Java.
Java on Android is very verbose
public class FeedActivity {
TextView mTextView;
void updateFeed() {
new FeedTask().execute("http://path/to/feed");
}
class FeedTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost(params[0]);
InputStream inputStream = null;
String result = null;
1/4
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
2/4
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (Exception squish) {
}
}
StringBuilder speakers = null;
try {
JSONObject jObject = new JSONObject(result);
JSONArray jArray = jObject.getJSONArray("speakers");
speakers = new StringBuilder();
for (int i = 0; i < jArray.length(); i++) {
speakers.append(jArray.getString(i));
speakers.append(" ");
}
3/4
} catch (JSONException e) {
// do something?
}
return speakers.toString();
}
@Override
protected void onPostExecute(String s) {
mTextView.setText(s);
}
}
}
4/4
So now,
let’s see the equivalent in Groovy
(no kidding either)
class FeedActivity {
TextView mTextView
void updateFeed() {
Fluent.async {
def json = new JsonSlurper().parse([:], new URL('http://path/to/feed'), 'utf-8')
json.speakers.join(' ')
} then {
mTextView.text = it
}
}
}
Because I'm lazy, I don't like to write a lot of code.
And Groovy helps me with that.
It's not only for writing less code,
it's also for cool features and good readability.
very consice language, actually
Semicolons
Parenthesis
return keyword
public keyword
Optional
Sugar syntax
1) Groovy truth
// if (s != null && s.length() > 0) { ...}
if (s) { ... }
// easy check for empty maps, list, empty strings
2) Elvis
def name = person.name ?: "unknown"
3) Save navigation
order?.lineItem?.item?.name
Where I have seen it?
Right, Apple's Swift
language was inspired by Groovy
4) List, maps (Groovy)
def shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
def occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
def emptyMap = [:]
def emptyList = []
4) List, maps (Swift)
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
var emptyMap = [:]
var emptyList = []
5) Named parameters (Groovy)
def triangleAndSquare =
new TriangleAndSquare(size: 10, name: "another test shape")
5) Named parameters (Swift)
var triangleAndSquare =
TriangleAndSquare(size: 10, name: "another test shape")
6) @Lazy annotation (Groovy)
class DataManager {
@Lazy importer = new DataImporter()
}
6) @Lazy annotation (Swift)
class DataManager {
@lazy var importer = DataImporter()
}
7) Closure (Groovy)
numbers.collect { int number ->
def result = 3 * numbers
return result
}
7) Closure (Swift)
numbers.map({
(number: Int) -> Int in
let result = 3 * number
return result
})
What else is cool in Groovy?
8) Builders import groovy.json.*
def json = new JsonBuilder()
json.conference {
name 'SZJUG'
subject 'Groovy on Android'
date 2016
time ['13:00', '16:00']
address {
place 'GRAPE 联合创业空间'
street '布吉街道吉华路247号下水径商业大厦三层 3/f'
district '龙岗区'
city '深圳市'
country '中国'
}
}
{
"conference": {
"name": "SZJUG",
"subject": "Groovy on Android",
"date": 2016,
"time": [
"13:00",
"16:00"
],
"address": {
"place": "GRAPE 联合创业空间",
"street": "布吉街道吉华路247号下水径商业大厦三层 3/f'",
"district": "龙岗区",
"city": "深圳市",
"country": "中国"
}
}
}
JSON
7) Immutability
@Immutable(copyWith = true)
class User {
String username, email
}
7) Immutability
// Create immutable instance of User.
def paul = new User('PaulVI', 'paul.verest@live.com')
// will throw an exception on
// paul.email = 'pupkin@mail.com'
def tomasz = mrhaki.copyWith(username: 'Tomasz')
8) String interpolation
def level = "badly"
println "I love SZJUG $level"
// Java
TextView view =
new TextView(context);
view.setText(name);
view.setTextSize(16f);
view.setTextColor(Color.WHITE);
TextView view =
new TextView(context)
view.with {
text = name
textSize = 16f
textColor = Color.WHITE
}
->
How to read text file from SD card?
def f = new FIle("/sdcard/dir/f.txt")
if (f.exists() && f.canRead()) {
view.text = f.text
}
You have to write a lot of anonymous classes EVERYWHERE
// Java
button.setOnClickListener(new View.OnClickListener() {
@Override
void onClick(View v) {
startActivity(intent);
}
})
button.onClickListener = { startActivity(intent) }
->
No native support for generating classes
at runtime
Focus on @CompileStatic
Problems
Generate bytecode, that runs
at the same speed as java files
How to start?
Gradle plugin
buildscript {
dependencies {
classpath 'com.android.tools.build:gradle:1.5.0'
classpath 'org.codehaus.groovy:gradle-groovy-android-plugin:0.3.10'
}
}
apply plugin: 'groovyx.grooid.groovy-android'
dependencies {
compile 'org.codehaus.groovy:groovy:2.4.6:grooid'
}
Performance
Groovy jar 4.5 MB
Application size 2 MB
ProGuard only 1 MB!
~8.2 MB of RAM
for @CompileStatic
if not - slower and more RAM
Frameworks
SwissKnife
http://arasthel.github.io/SwissKnife/
def "should display hello text"() {
given:
def textView = new TextView(RuntimeEnvironment.application)
expect:
textView.text == "Hello"
}
Familiar with that?
Spock
http://robospock.org/
?

More Related Content

Viewers also liked

Metaprogramming with Groovy
Metaprogramming with GroovyMetaprogramming with Groovy
Metaprogramming with Groovy
Ali Tanwir
 
Groovy in the Cloud
Groovy in the CloudGroovy in the Cloud
Groovy in the Cloud
Daniel Woods
 
Ci for-android-apps
Ci for-android-appsCi for-android-apps
Ci for-android-apps
Anthony Dahanne
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvm
Arnaud Giuliani
 
Spring one 2012 Groovy as a weapon of maas PaaSification
Spring one 2012 Groovy as a weapon of maas PaaSificationSpring one 2012 Groovy as a weapon of maas PaaSification
Spring one 2012 Groovy as a weapon of maas PaaSification
Nenad Bogojevic
 
We thought we were doing continuous delivery and then...
We thought we were doing continuous delivery and then... We thought we were doing continuous delivery and then...
We thought we were doing continuous delivery and then...
Suzie Prince
 
Java collections the force awakens
Java collections  the force awakensJava collections  the force awakens
Java collections the force awakens
RichardWarburton
 
Groovy for java developers
Groovy for java developersGroovy for java developers
Groovy for java developers
Puneet Behl
 
Reactive Streams and the Wide World of Groovy
Reactive Streams and the Wide World of GroovyReactive Streams and the Wide World of Groovy
Reactive Streams and the Wide World of Groovy
Steve Pember
 
Be More Productive with Kotlin
Be More Productive with KotlinBe More Productive with Kotlin
Be More Productive with Kotlin
Brandon Wever
 
Building an Extensible, Resumable DSL on Top of Apache Groovy
Building an Extensible, Resumable DSL on Top of Apache GroovyBuilding an Extensible, Resumable DSL on Top of Apache Groovy
Building an Extensible, Resumable DSL on Top of Apache Groovy
jgcloudbees
 
Java 8 and 9 in Anger
Java 8 and 9 in AngerJava 8 and 9 in Anger
Java 8 and 9 in Anger
Trisha Gee
 
Kotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyKotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRready
MobileAcademy
 
Groovyscriptingformanualandautomationtestingusingrobotframework 141221014703-...
Groovyscriptingformanualandautomationtestingusingrobotframework 141221014703-...Groovyscriptingformanualandautomationtestingusingrobotframework 141221014703-...
Groovyscriptingformanualandautomationtestingusingrobotframework 141221014703-...
Bhaskara Reddy Sannapureddy
 
Java 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useJava 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually use
Sharon Rozinsky
 
Java 9 Functionality and Tooling
Java 9 Functionality and ToolingJava 9 Functionality and Tooling
Java 9 Functionality and Tooling
Trisha Gee
 
Migrating to IntelliJ IDEA from Eclipse
Migrating to IntelliJ IDEA from EclipseMigrating to IntelliJ IDEA from Eclipse
Migrating to IntelliJ IDEA from Eclipse
Trisha Gee
 
Continuous integration and delivery for java based web applications
Continuous integration and delivery for java based web applicationsContinuous integration and delivery for java based web applications
Continuous integration and delivery for java based web applications
Sunil Dalal
 
Docker and java
Docker and javaDocker and java
Docker and java
Anthony Dahanne
 
Fabulous Tests on Spock and Groovy
Fabulous Tests on Spock and GroovyFabulous Tests on Spock and Groovy
Fabulous Tests on Spock and Groovy
Yaroslav Pernerovsky
 

Viewers also liked (20)

Metaprogramming with Groovy
Metaprogramming with GroovyMetaprogramming with Groovy
Metaprogramming with Groovy
 
Groovy in the Cloud
Groovy in the CloudGroovy in the Cloud
Groovy in the Cloud
 
Ci for-android-apps
Ci for-android-appsCi for-android-apps
Ci for-android-apps
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvm
 
Spring one 2012 Groovy as a weapon of maas PaaSification
Spring one 2012 Groovy as a weapon of maas PaaSificationSpring one 2012 Groovy as a weapon of maas PaaSification
Spring one 2012 Groovy as a weapon of maas PaaSification
 
We thought we were doing continuous delivery and then...
We thought we were doing continuous delivery and then... We thought we were doing continuous delivery and then...
We thought we were doing continuous delivery and then...
 
Java collections the force awakens
Java collections  the force awakensJava collections  the force awakens
Java collections the force awakens
 
Groovy for java developers
Groovy for java developersGroovy for java developers
Groovy for java developers
 
Reactive Streams and the Wide World of Groovy
Reactive Streams and the Wide World of GroovyReactive Streams and the Wide World of Groovy
Reactive Streams and the Wide World of Groovy
 
Be More Productive with Kotlin
Be More Productive with KotlinBe More Productive with Kotlin
Be More Productive with Kotlin
 
Building an Extensible, Resumable DSL on Top of Apache Groovy
Building an Extensible, Resumable DSL on Top of Apache GroovyBuilding an Extensible, Resumable DSL on Top of Apache Groovy
Building an Extensible, Resumable DSL on Top of Apache Groovy
 
Java 8 and 9 in Anger
Java 8 and 9 in AngerJava 8 and 9 in Anger
Java 8 and 9 in Anger
 
Kotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyKotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRready
 
Groovyscriptingformanualandautomationtestingusingrobotframework 141221014703-...
Groovyscriptingformanualandautomationtestingusingrobotframework 141221014703-...Groovyscriptingformanualandautomationtestingusingrobotframework 141221014703-...
Groovyscriptingformanualandautomationtestingusingrobotframework 141221014703-...
 
Java 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useJava 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually use
 
Java 9 Functionality and Tooling
Java 9 Functionality and ToolingJava 9 Functionality and Tooling
Java 9 Functionality and Tooling
 
Migrating to IntelliJ IDEA from Eclipse
Migrating to IntelliJ IDEA from EclipseMigrating to IntelliJ IDEA from Eclipse
Migrating to IntelliJ IDEA from Eclipse
 
Continuous integration and delivery for java based web applications
Continuous integration and delivery for java based web applicationsContinuous integration and delivery for java based web applications
Continuous integration and delivery for java based web applications
 
Docker and java
Docker and javaDocker and java
Docker and java
 
Fabulous Tests on Spock and Groovy
Fabulous Tests on Spock and GroovyFabulous Tests on Spock and Groovy
Fabulous Tests on Spock and Groovy
 

Similar to Groovy on Android

Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume LaforgeGroovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Guillaume Laforge
 
An Introduction to Groovy for Java Developers
An Introduction to Groovy for Java DevelopersAn Introduction to Groovy for Java Developers
An Introduction to Groovy for Java Developers
Kostas Saidis
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
David Padbury
 
GroovyFX - Groove JavaFX
GroovyFX - Groove JavaFXGroovyFX - Groove JavaFX
GroovyFX - Groove JavaFX
sascha_klein
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
loffenauer
 
Gradle in 45min - JBCN2-16 version
Gradle in 45min - JBCN2-16 versionGradle in 45min - JBCN2-16 version
Gradle in 45min - JBCN2-16 version
Schalk Cronjé
 
Groovy And Grails Introduction
Groovy And Grails IntroductionGroovy And Grails Introduction
Groovy And Grails Introduction
Eric Weimer
 
Go react codelab
Go react codelabGo react codelab
Infinum android talks_10_getting groovy on android
Infinum android talks_10_getting groovy on androidInfinum android talks_10_getting groovy on android
Infinum android talks_10_getting groovy on android
Infinum
 
NodeJS
NodeJSNodeJS
NodeJS
Alok Guha
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
Guillaume Laforge
 
淺談 Groovy 與 AWS 雲端應用開發整合
淺談 Groovy 與 AWS 雲端應用開發整合淺談 Groovy 與 AWS 雲端應用開發整合
淺談 Groovy 與 AWS 雲端應用開發整合
Kyle Lin
 
eXo EC - Groovy Programming Language
eXo EC - Groovy Programming LanguageeXo EC - Groovy Programming Language
eXo EC - Groovy Programming LanguageHoat Le
 
Javaone2008 Bof 5102 Groovybuilders
Javaone2008 Bof 5102 GroovybuildersJavaone2008 Bof 5102 Groovybuilders
Javaone2008 Bof 5102 Groovybuilders
Andres Almiray
 
Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007
Guillaume Laforge
 
Groovy a Scripting Language for Java
Groovy a Scripting Language for JavaGroovy a Scripting Language for Java
Groovy a Scripting Language for Java
Charles Anderson
 
UIWebView Tips
UIWebView TipsUIWebView Tips
UIWebView Tips
Katsumi Kishikawa
 
WebSocket JSON Hackday
WebSocket JSON HackdayWebSocket JSON Hackday
WebSocket JSON HackdaySomay Nakhal
 
Meetup#1: 10 reasons to fall in love with MongoDB
Meetup#1: 10 reasons to fall in love with MongoDBMeetup#1: 10 reasons to fall in love with MongoDB
Meetup#1: 10 reasons to fall in love with MongoDBMinsk MongoDB User Group
 
GroovyFX - groove JavaFX Gr8Conf EU 2017
GroovyFX - groove JavaFX Gr8Conf EU 2017GroovyFX - groove JavaFX Gr8Conf EU 2017
GroovyFX - groove JavaFX Gr8Conf EU 2017
sascha_klein
 

Similar to Groovy on Android (20)

Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume LaforgeGroovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
 
An Introduction to Groovy for Java Developers
An Introduction to Groovy for Java DevelopersAn Introduction to Groovy for Java Developers
An Introduction to Groovy for Java Developers
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
GroovyFX - Groove JavaFX
GroovyFX - Groove JavaFXGroovyFX - Groove JavaFX
GroovyFX - Groove JavaFX
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
 
Gradle in 45min - JBCN2-16 version
Gradle in 45min - JBCN2-16 versionGradle in 45min - JBCN2-16 version
Gradle in 45min - JBCN2-16 version
 
Groovy And Grails Introduction
Groovy And Grails IntroductionGroovy And Grails Introduction
Groovy And Grails Introduction
 
Go react codelab
Go react codelabGo react codelab
Go react codelab
 
Infinum android talks_10_getting groovy on android
Infinum android talks_10_getting groovy on androidInfinum android talks_10_getting groovy on android
Infinum android talks_10_getting groovy on android
 
NodeJS
NodeJSNodeJS
NodeJS
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
 
淺談 Groovy 與 AWS 雲端應用開發整合
淺談 Groovy 與 AWS 雲端應用開發整合淺談 Groovy 與 AWS 雲端應用開發整合
淺談 Groovy 與 AWS 雲端應用開發整合
 
eXo EC - Groovy Programming Language
eXo EC - Groovy Programming LanguageeXo EC - Groovy Programming Language
eXo EC - Groovy Programming Language
 
Javaone2008 Bof 5102 Groovybuilders
Javaone2008 Bof 5102 GroovybuildersJavaone2008 Bof 5102 Groovybuilders
Javaone2008 Bof 5102 Groovybuilders
 
Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007
 
Groovy a Scripting Language for Java
Groovy a Scripting Language for JavaGroovy a Scripting Language for Java
Groovy a Scripting Language for Java
 
UIWebView Tips
UIWebView TipsUIWebView Tips
UIWebView Tips
 
WebSocket JSON Hackday
WebSocket JSON HackdayWebSocket JSON Hackday
WebSocket JSON Hackday
 
Meetup#1: 10 reasons to fall in love with MongoDB
Meetup#1: 10 reasons to fall in love with MongoDBMeetup#1: 10 reasons to fall in love with MongoDB
Meetup#1: 10 reasons to fall in love with MongoDB
 
GroovyFX - groove JavaFX Gr8Conf EU 2017
GroovyFX - groove JavaFX Gr8Conf EU 2017GroovyFX - groove JavaFX Gr8Conf EU 2017
GroovyFX - groove JavaFX Gr8Conf EU 2017
 

Recently uploaded

WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
AafreenAbuthahir2
 
addressing modes in computer architecture
addressing modes  in computer architectureaddressing modes  in computer architecture
addressing modes in computer architecture
ShahidSultan24
 
Vaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdfVaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdf
Kamal Acharya
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdfCOLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
Kamal Acharya
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
seandesed
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
AhmedHussein950959
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
Jayaprasanna4
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 
Automobile Management System Project Report.pdf
Automobile Management System Project Report.pdfAutomobile Management System Project Report.pdf
Automobile Management System Project Report.pdf
Kamal Acharya
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
ankuprajapati0525
 
Courier management system project report.pdf
Courier management system project report.pdfCourier management system project report.pdf
Courier management system project report.pdf
Kamal Acharya
 
Halogenation process of chemical process industries
Halogenation process of chemical process industriesHalogenation process of chemical process industries
Halogenation process of chemical process industries
MuhammadTufail242431
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
karthi keyan
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 

Recently uploaded (20)

WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
addressing modes in computer architecture
addressing modes  in computer architectureaddressing modes  in computer architecture
addressing modes in computer architecture
 
Vaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdfVaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdf
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdfCOLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 
Automobile Management System Project Report.pdf
Automobile Management System Project Report.pdfAutomobile Management System Project Report.pdf
Automobile Management System Project Report.pdf
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
 
Courier management system project report.pdf
Courier management system project report.pdfCourier management system project report.pdf
Courier management system project report.pdf
 
Halogenation process of chemical process industries
Halogenation process of chemical process industriesHalogenation process of chemical process industries
Halogenation process of chemical process industries
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 

Groovy on Android

  • 1.
  • 3. def speaker = new SZJUG.Speaker( name: 'Alexey Zhokhov', employer: 'Scentbird', occupation: 'Grails Developer', github: 'donbeave', email: 'alexey@zhokhov.com', site: 'http://www.zhokhov.com', description: """whole-stack engineer (back-end, front-end, mobile, UI/UX)""" )
  • 5. Groovy is inside the Gradle You probably know Groovy through Gradle already. Groovy is a superset of Java. It contains lots of cool stuff that makes Java fun!
  • 6. So, Why can Groovy be Android' Swift?
  • 7. Android N supports Java 8 "Android is in the Java stone age state" But not released
  • 9. Java on Android is very verbose
  • 10. public class FeedActivity { TextView mTextView; void updateFeed() { new FeedTask().execute("http://path/to/feed"); } class FeedTask extends AsyncTask<String, Void, String> { protected String doInBackground(String... params) { DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams()); HttpPost httppost = new HttpPost(params[0]); InputStream inputStream = null; String result = null; 1/4
  • 11. try { HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); inputStream = entity.getContent(); // json is UTF-8 by default BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line).append("n"); } result = sb.toString(); } catch (Exception e) { // Oops 2/4
  • 12. } finally { try { if (inputStream != null) { inputStream.close(); } } catch (Exception squish) { } } StringBuilder speakers = null; try { JSONObject jObject = new JSONObject(result); JSONArray jArray = jObject.getJSONArray("speakers"); speakers = new StringBuilder(); for (int i = 0; i < jArray.length(); i++) { speakers.append(jArray.getString(i)); speakers.append(" "); } 3/4
  • 13. } catch (JSONException e) { // do something? } return speakers.toString(); } @Override protected void onPostExecute(String s) { mTextView.setText(s); } } } 4/4
  • 14. So now, let’s see the equivalent in Groovy (no kidding either)
  • 15. class FeedActivity { TextView mTextView void updateFeed() { Fluent.async { def json = new JsonSlurper().parse([:], new URL('http://path/to/feed'), 'utf-8') json.speakers.join(' ') } then { mTextView.text = it } } }
  • 16. Because I'm lazy, I don't like to write a lot of code. And Groovy helps me with that.
  • 17. It's not only for writing less code, it's also for cool features and good readability. very consice language, actually
  • 20. 1) Groovy truth // if (s != null && s.length() > 0) { ...} if (s) { ... } // easy check for empty maps, list, empty strings
  • 21. 2) Elvis def name = person.name ?: "unknown"
  • 23. Where I have seen it?
  • 24. Right, Apple's Swift language was inspired by Groovy
  • 25. 4) List, maps (Groovy) def shoppingList = ["catfish", "water", "tulips", "blue paint"] shoppingList[1] = "bottle of water" def occupations = [ "Malcolm": "Captain", "Kaylee": "Mechanic", ] occupations["Jayne"] = "Public Relations" def emptyMap = [:] def emptyList = []
  • 26. 4) List, maps (Swift) var shoppingList = ["catfish", "water", "tulips", "blue paint"] shoppingList[1] = "bottle of water" var occupations = [ "Malcolm": "Captain", "Kaylee": "Mechanic", ] occupations["Jayne"] = "Public Relations" var emptyMap = [:] var emptyList = []
  • 27. 5) Named parameters (Groovy) def triangleAndSquare = new TriangleAndSquare(size: 10, name: "another test shape")
  • 28. 5) Named parameters (Swift) var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape")
  • 29. 6) @Lazy annotation (Groovy) class DataManager { @Lazy importer = new DataImporter() }
  • 30. 6) @Lazy annotation (Swift) class DataManager { @lazy var importer = DataImporter() }
  • 31. 7) Closure (Groovy) numbers.collect { int number -> def result = 3 * numbers return result }
  • 32. 7) Closure (Swift) numbers.map({ (number: Int) -> Int in let result = 3 * number return result })
  • 33. What else is cool in Groovy?
  • 34. 8) Builders import groovy.json.* def json = new JsonBuilder() json.conference { name 'SZJUG' subject 'Groovy on Android' date 2016 time ['13:00', '16:00'] address { place 'GRAPE 联合创业空间' street '布吉街道吉华路247号下水径商业大厦三层 3/f' district '龙岗区' city '深圳市' country '中国' } }
  • 35. { "conference": { "name": "SZJUG", "subject": "Groovy on Android", "date": 2016, "time": [ "13:00", "16:00" ], "address": { "place": "GRAPE 联合创业空间", "street": "布吉街道吉华路247号下水径商业大厦三层 3/f'", "district": "龙岗区", "city": "深圳市", "country": "中国" } } } JSON
  • 36. 7) Immutability @Immutable(copyWith = true) class User { String username, email }
  • 37. 7) Immutability // Create immutable instance of User. def paul = new User('PaulVI', 'paul.verest@live.com') // will throw an exception on // paul.email = 'pupkin@mail.com' def tomasz = mrhaki.copyWith(username: 'Tomasz')
  • 38. 8) String interpolation def level = "badly" println "I love SZJUG $level"
  • 39. // Java TextView view = new TextView(context); view.setText(name); view.setTextSize(16f); view.setTextColor(Color.WHITE); TextView view = new TextView(context) view.with { text = name textSize = 16f textColor = Color.WHITE } ->
  • 40. How to read text file from SD card? def f = new FIle("/sdcard/dir/f.txt") if (f.exists() && f.canRead()) { view.text = f.text }
  • 41. You have to write a lot of anonymous classes EVERYWHERE // Java button.setOnClickListener(new View.OnClickListener() { @Override void onClick(View v) { startActivity(intent); } }) button.onClickListener = { startActivity(intent) } ->
  • 42. No native support for generating classes at runtime Focus on @CompileStatic Problems Generate bytecode, that runs at the same speed as java files
  • 44. Gradle plugin buildscript { dependencies { classpath 'com.android.tools.build:gradle:1.5.0' classpath 'org.codehaus.groovy:gradle-groovy-android-plugin:0.3.10' } } apply plugin: 'groovyx.grooid.groovy-android' dependencies { compile 'org.codehaus.groovy:groovy:2.4.6:grooid' }
  • 46. Groovy jar 4.5 MB Application size 2 MB ProGuard only 1 MB! ~8.2 MB of RAM for @CompileStatic if not - slower and more RAM
  • 49. def "should display hello text"() { given: def textView = new TextView(RuntimeEnvironment.application) expect: textView.text == "Hello" } Familiar with that?
  • 51. ?