blob: 6ad90e18feed295e90d64705d481e7d8776079df [file] [log] [blame]
<?php
/*******************************************************************************
* Copyright (c) 2015 Eclipse Foundation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Eric Poirier (Eclipse Foundation) - Initial implementation
*******************************************************************************/
?>
<h1 class="article-title"><?php echo $pageTitle; ?></h1>
<p>
Android is an amazing operating system that combines technical
innovation with high popularity among the end-consumers. In spite
of fragmentation, there is a large amount of developers across the
world who enjoy developing applications for Android. Today, most
Android applications are written in Java. Unfortunately, Java is
known to be deficient in some modern language concepts and idioms
like conciseness, declarativity, modularity mechanisms, the
map/reduce pattern or immutable data. Wouldn't it be great if
there was a more advanced programming language for Android
development? Luckily, there is one and it integrates seamlessly
with Java. This language is <a href="http://www.eclipse.org/xtend">Xtend</a>.
</p>
<p>
Xtend is a statically-typed programming language that compiles to
Java. Xtend has a clear and concise syntax. Although lambda
expressions will be finally introduced in Java 8, Xtend's syntax
for them is significantly more readable. Another feature that
makes Xtend a functional language is the absence of statements.
Code written in Xtend is executed by evaluating expressions.
Operator overloading in form of an operator-to-method mapping
allows to fully customize operator semantics. Extension methods
enhance existing types with new functionality. Other powerful
features like the type-based switch expression, shorthand property
access and local type inference make programming in Xtend real
fun. Even more important than the language features is the
seamless, bidirectional interoperability with Java, a low learning
curve for Java developers, comprehensible and efficient generated
Java source code and the great IDE support. All this makes Xtend
ready for immediate use in every environment where Java and
Eclipse are used for development. If you are new to Xtend, check
out its <a href="http://www.eclipse.org/xtend/documentation.html">documentation</a>.
</p>
<p>
In this tutorial, we will write an Android application in Xtend,
build an APK and run it on the Android emulator. We will implement
a simple application called <i>Is Following?</i> which lets us
check if a Twitter user follows another Twitter user.
</p>
<img
src="/community/eclipse_newsletter/2013/march/images/android_screenshot1.jpg"
alt="Screenshot of the app 'Is Following?'" />
<p>To be able to follow the tutorial, you need to be acquainted with
Android development and the Eclipse IDE.</p>
<h3>Setting Up The IDE</h3>
<p>First, we'll install and configure the IDE and create a project.
You can skip the first three steps, if you already have an Eclipse
installation that you use for Android development.</p>
<ul>
<li>Download and install Eclipse IDE with built-in Android
Developer Tools from <a
href="http://developer.android.com/sdk/index.html">http://developer.android.com/sdk/index.html</a>.
<li>Follow the instructions at <a
href="http://developer.android.com/sdk/installing/bundle.html">http://developer.android.com/sdk/installing/bundle.html</a>
to set up your Android SDK for the first time.
<li>Alternatively, you can use an existing Eclipse installation
and set it up as described at <a
href="http://developer.android.com/sdk/installing/index.html">http://developer.android.com/sdk/installing/index.html</a>.
<li>After you have Eclipse, the Android SDK and the ADT plugin
ready, install version 2.4 of Xtend. To do so, go to Help ->
Install New Software… and paste the Xtend update site <a
href="http://download.eclipse.org/modeling/tmf/xtext/updates/composite/releases">http://download.eclipse.org/modeling/tmf/xtext/updates/composite/releases</a>
into the field labeled <i>Work with</i>.
<li>Choose Xtend 2.4.
<li>Disable the checkbox <i>Contact all update sites during
install to find required software</i>, to avoid unwanted
updates of other Eclipse plug-ins.
<li>Click <i>Finish</i> and follow the instructions of the
installation wizard.
</ul>
<h3>Creating A Project</h3>
<p>
Now, we'll create a project and start writing the application. You
can download the complete source code from <a
href="https://github.com/nossipova/isfollowing">https://github.com/nossipova/isfollowing</a>.
</p>
<ul>
<li><p>Create a new Android Application Project with a blank
activity MainActivity.</p> <img
src="/community/eclipse_newsletter/2013/march/images/android_screenshot2.jpg"
alt="New Android project" />
<li>The compiler compliance level of the project needs to be set
to 1.6.
</ul>
<h3>Creating A Layout</h3>
<p>Create a simple layout that consists of:</p>
<ul>
<li>an editable field for each of both Twitter names,
<li>a button to start the request and
<li><p>a text view that will show a result.</p> <img
src="/community/eclipse_newsletter/2013/march/images/android_screenshot3.jpg"
alt="The Layout" />
</ul>
<h3>Writing The Application</h3>
<p>Our application will have an activity to interact with the user
and a communicator which will send requests to Twitter and process
its responses. The communication with Twitter will be performed
asynchronously. Let's implement these components.</p>
<ul>
<li>Delete the class <code>MainActivity.java</code> that was
automatically generated through the project creation.
<li>To create a new Xtend class, select <i>New -> Xtend Class</i>
from the project context menu in the <i>Package Explorer</i>.
<li>On the first page of the creation wizard, type <code>MainActivity</code>
in the <i>Name</i> field and select <code>android.app.Activity</code>
as a superclass.
<li>Click <i>Finish</i>.
<li><p>The class we've just created will show an error:
<pre>
Mandatory library bundle 'org.eclipse.xtext.xbase.lib' 2.3.0 or higher not found on the classpath.
</pre> Use the available quick fix to add Xtend libraries to the
classpath.
<li><p>
<code>MainActivity</code>
will have two methods:
<code>onCreate(Bundle)</code>
and
<code>showResult(Object)</code>
. The first method
<code>onCreate(Bundle)</code>
prepares the content view and registers the click listener
callback of the <i>Check</i> button. In the callback, we
initialize the communicator, use its method
<code>isNetworkAvailable(Context)</code>
to test the connectivity and execute the communicator
asynchronously. The second method
<code>showResult(Object)</code>
updates the UI with the response received from the
communicator by setting the text value in the result text
view.
</p> <pre class="prettyprint lang-xtend">
package de.nataliaossipova.isfollowing
import android.app.Activity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import static de.nataliaossipova.isfollowing.R$id.*
import static de.nataliaossipova.isfollowing.R$layout.*
import static de.nataliaossipova.isfollowing.R$string.*
class MainActivity extends Activity implements AsyncDelegate {
override onCreate(Bundle it) {
super.onCreate(it)
contentView = activity_main
val Button button = getView(Button01)
button.onClickListener = [
var communicator = new TwitterCommunicator
communicator.delegate = this
if (communicator.isNetworkAvailable(this)) {
val EditText editText1 = getView(EditText01)
val EditText editText2 = getView(EditText02)
communicator.execute(editText1.text.toString, editText2.text.toString)
}
]
}
override showResult(Object it) {
var TextView resultView = getView(ResultView)
resultView.text = if ('true' == it) {
getString(yes).toUpperCase
} else {
getString(no).toUpperCase
}
}
def &lt;T extends View&gt; T getView(int id) {
findViewById(id) as T
}
}
</pre>
<li><p>
Create a new Xtend class
<code>TwitterCommunicator</code>
as a subclass of
<code>android.os.AsyncTask</code>
. The subclass implements two methods:
<code>doInBackground(Params...)</code>
and
<code>onPostExecute(Result)</code>
. In
<code>doInBackground(Params…)</code>
method, we create a new Twitter URL from both Twitter names
passed in as parameters. After that, we open an HTTP
connection and read the input stream from it. The second
method passes the data read from the input stream to the main
activity.
<pre class="prettyprint lang-xtend">
package de.nataliaossipova.isfollowing
import android.content.Context
import android.net.ConnectivityManager
import android.os.AsyncTask
import com.google.common.io.CharStreams
import java.io.InputStream
import java.io.InputStreamReader
import java.net.URL
class TwitterCommunicator extends AsyncTask&lt;String, Void, String&gt; {
AsyncDelegate delegate
override protected doInBackground(String... params) {
new URL('https://api.twitter.com/1/friendships/exists.json?screen_name_a='
+ params.get(0) + '&amp;screen_name_b=' + params.get(1))
.openConnection.inputStream.readStream
}
override onPostExecute(String result) {
if (delegate != null) {
delegate.showResult(result)
}
}
def setDelegate(AsyncDelegate delegate) {
this.delegate = delegate
}
def isNetworkAvailable(Context it) {
val networkInfo = (getSystemService(Context::CONNECTIVITY_SERVICE)
as ConnectivityManager).activeNetworkInfo
return networkInfo != null &amp;&amp; networkInfo.connected
}
def private readStream(InputStream in) {
return CharStreams::toString(new InputStreamReader(in))
}
}
</pre>
<li><p>
To avoid tight coupling between the activity and the
communicator, we will make use of the delegate pattern. Create
a new Xtend interface
<code>AsyncDelegate</code>
. The interface declares only one method
<code>showResult(Object)</code>
. We will call this method from the post execute callback of
<code>TwitterCommunicator</code>
.
<pre class="prettyprint lang-xtend">
package de.nataliaossipova.isfollowing
interface AsyncDelegate {
def void showResult(Object it)
}
</pre></li></ul>
<p>The <code>MainActivity</code> already implements the <code>AsyncDelegate</code>
interface.
</p>
<h3>Build And Run</h3>
<p>
Now, when we are done with writing source code, add
permissions
<code>android.permission.INTERNET</code>
and
<code>android.permission.ACCESS_NETWORK_STATE</code>
to the Android manifest and let's build an APK and run it on
an AVD.
</p>
<p>
We need to tell ADT how to export the Xtend libraries. Choose
<i>Properties -> Java Build Path</i> from the project context
menu and go to the <i>Order and Export</i> tab. Select the
checkbox beside <i>Xtend library</i>.
</p> <img
src="/community/eclipse_newsletter/2013/march/images/android_screenshot4.jpg"
alt="New Android project" />
<p>After closing the Properties window, you can launch the
application on an existing AVD or a device.</p>
<h3>Where To Go From Here</h3>
<p>Now that you know how to use Xtend for Android development,
go and create awesome Android apps in this sophisticated
programming language!</p>
<p>Don't hesitate to let me know if anything of the above is
confusing to you or if you'd like me to go into more detail.</p>
<script
src="http://www.eclipse.org/xtend/google-code-prettify/prettify.js"
type="text/javascript"></script> <script
src="http://www.eclipse.org/xtend/google-code-prettify/lang-xtend.js"
type="text/javascript"></script> <script
type="text/javascript">
prettyPrint();
</script>
<div class="bottomitem">
<h3>About the Authors</h3>
<div class="row">
<div class="col-sm-12">
<div class="row">
<div class="col-sm-8">
<img class="author-picture"
src="/community/eclipse_newsletter/2013/march/images/natalia_ossipova1.jpg"
alt="Natalia Ossipova" />
</div>
<div class="col-sm-16">
<p class="author-name">
Natalia Ossipova <br /> <a
href="http://nataliaossipova.wordpress.com/">Freelance
Software Architect</a>
</p>
<ul class="author-link">
<li><a href="http://nataliaossipova.wordpress.com/">Blog</a></li>
<li><a href="https://twitter.com/nossipova">Twitter</a></li>
<li><a href="http://www.linkedin.com/in/nataliaossipova">LinkedIn</a></li>
<li><a href="<?php echo $original_url; ?>">Original Article</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>