Official website for Linux User & Developer
FOLLOW US ON:
Aug
17

Android development with Java

by Tam Hanna

There are untold riches awaiting those who can create smartphone apps – luckily getting started with Android is really easy

Developers seeking to create apps for Google’s popular smartphone operating system needn’t bother themselves with learning complex and often obscure custom versions of C++ like the one used by the once-famous Symbian OS. Instead, Android applications tend to be written in Java, with native modules added in for convenience and speed.

This ease of development has led to a flood of apps hitting the Play Store, so making a living from a well-made app is not as easy as it used to be. The large selection means that well-planned marketing and a great-looking user interface are now of paramount importance.

Creating apps, however, is not limited to people seeking to publish their products in app stores. Instead, a custom app can also be helpful when it comes to solving everyday tasks. For example, let’s say there’s a person working as a trader. Their stockbroker recently introduced a new feature that could save them a lot of time, but it requires some complex mathematical computations. Creating an app that solves the equations on the fly would be pretty useful here.

Java mode is used for editing the source code of your application
Java mode is used for editing the source code of your application

Even though such a program is unlikely to sell on Google Play, having it on hand can save a lot of time. From a workflow point of view, creating this application is not that different from the process used when building a larger product.

Find me tools!

Developing applications for mobile phones is done with a cross-compiler. Fortunately, operating system vendors provide software development kits that contain all of the necessary modules developers require. In the case of Android, the product is based on the well-liked Eclipse code editing system.

Usually, Eclipse users need to assemble their toolchain out of individual building blocks. Google solves this problem by providing users with a ready-made package containing the integrated development environment, the necessary plug-ins and an emulator.

Most of the tools are based on Java. This means that your machine needs to be equipped with a Java development kit – installing it is as straightforward as entering the following command into a terminal window:

$ sudo apt-get install openjdk-6-jdk

When working with a 64-bit version of Linux, additional packets need to be installed. More information on the specific instructions needed by the various distributions can be found through a quick search if need be.

In the next step, visit Google’s SDK download page. Scroll down until you find a table labelled ADT Bundle and click the corresponding file in order to download it to your machine. Extract it to a convenient location of your choice – keep in mind that development environments are IO-heavy, so it is recommended that you use the fastest disk installed on your machine.

Your zip file is made up of two subfolders. /eclipse/ contains the files needed for the graphical development environment, whereas /sdk/ is made up of system files that usually don’t need to be modified. Starting the Android Developer Tools can be accomplished by running the ‘eclipse’ file found in the /eclipse/ subfolder. Eclipse will ask you for a working directory. This folder will contain both settings and projects – back it up in order to save your entire workspace.

A first project

Starting Eclipse can take a minute or two. Once the process is completed, the product will present you with a screen similar to the one shown across the page. The two toggles at the top right-hand side of the display allow you to change the mode: click ‘Debug’ in order to activate the screen for finding errors. Then, click ‘Java’ to return to editing.

New projects can be created by opening the generation wizard found under New>Android Application Project. In the first step, the IDE will ask you for further information about the name, package and versioning of the project in question (see boxout).

Our example will be called TrailingStopp, and is located in the package ‘com.tamoggemon. trailingstopp’. Google provides reasonable values for the rest of the wizard, which can be completed by clicking Next multiple times. When done, a new project will have been created.

Android applications can be broken down into three types of file. First of all, resources are stored in XML format. ‘AndroidManifest.xml’ has special priority in this regard as it acts as an application descriptor, providing the operating system with further information about the app. Here’s our sample structure:

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.tamoggemon.trailingstopp"
   android:versionCode="1"
   android:versionName="1.0" > 

   <uses-sdk
      android:minSdkVersion="8"
      android:targetSdkVersion="19" /></pre>

Manifest files start out by declaring the SDK version and the package names required by the application. This information enables the operating system to assess whether the application is compatible with the current hardware.

In the next step, the actual application is declared along with any activities:

<application
   android:allowBackup="true"
   android:icon="@drawable/ic_launcher"
   android:label="@string/app_name"
   android:theme="@style/AppTheme" >
   <activity
      android:name="com.tamoggemon.trailingstopp.MainActivity"
      android:label="@string/app_name" >
      <intent-filter>
         <action android:name="android.intent.action.MAIN" />

         <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>

Google opted to call forms Activities and we will get to those in a minute.
Interprocess communication takes place via Intents. Our application informs the system that the LAUNCHER-Intent is to be handled by the Activity MainActivity. Finally, the open tags are closed in order to create a valid XML file.

      </activity>
   </application>

</manifest>

Even though the manifest can be edited with a graphical editor, developers should be aware of its role and structure. Many advanced features can only be activated by hand. Furthermore, most tutorial authors simply provide their readers with a summary of the necessary changes to the file structure.

Activities and layouts

By default, a newly-created application consists of but one form. In our case, the activity’s structure is declared in a file called ActivityMain.xml. Double-clicking it in the Package explorer usually opens a WYSIWYG editor such as the one shown over the page. Should your version of Eclipse display code, just click the little tab labelled ‘Graphical Layout’ to fix the problem.

The Palette window on the left side of the form contains controls that can be added by dragging and dropping. Eclipse’s rendering is relatively accurate – things like layouts get considered during the generation of the preview.

As outlined in the callout, our algorithm requires a total of three input parameters. Collecting data tends to be done with text fields and Android’s GUI stack contains a good dozen text fields. We will use a control that is limited to the input of decimal numbers – the Palette lists it as ‘42.0’; its tooltip calls it Number (Decimal). In an ideal world, we could simply drag the controls onto the form and be done with it – but Android phones are offered with a large variety of screen sizes. Google addresses this problem via a layout system that was inspired by the one used in Qt.

Arranging our widgets above one another requires us to use a LinearLayout (vertical). Thus, your first change involves dragging said control into the form area. Due to their invisible nature, the layout will not show up in the preview. Should you ever need to find it, use the Outline window in order to track it down.
In the next step, the three text boxes can be dragged in. Eclipse will automatically arrange them above one another. Clicking any of them allows you to edit its properties in the list on the bottom right-hand side of the screen. We would recommend that you change the names of the widgets and provide them with a Hint text that will show up if the user has not entered data. Very diligent individuals can go further, adding in three labels describing the data to be entered in the text box below. Finally, drag in a button. It will be used for triggering the actual computation process. The resulting XML file will look like this:

<FrameLayout xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:tools=”http://schemas.android.com/tools”
android:id=”@+id/container”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
tools:context=”com.tamoggemon.trailingstopp.MainActivity”
tools:ignore=”MergeRootFrame” >

<LinearLayout
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:orientation=”vertical” >

Controls are assigned to layouts by enclosing them between the opening and closing tag. Feel free to nest layouts as deep as you see fit – but please keep in mind that the amount of layouts directly affects the performance of the GUI stack.

The actual widgets are declared in a HTMLesque fashion. The string assigned to @id is used for finding the controls in the source code: by using a string that starts with a plus, we ‘add’ the name of the widget to the list of elements stored in id.

      <EditText
         android:id="@+id/editText1"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:ems="10"
         android:inputType="numberDecimal" >

         <requestFocus />
      </EditText>

      <EditText
         android:id="@+id/editText2"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:ems="10" android:inputType="numberDecimal" />

      <EditText
         android:id="@+id/editText3"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:ems="10"
         android:inputType="numberDecimal" />

      <Button
         android:id="@+id/button1"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="Button" />

   </LinearLayout>

</FrameLayout>

Change the code

With that, the resource file is ready. Its intelligence can be found in the Activity class, which resides in ‘/src/ /MainActivity. java’. Our application wants to be notified whenever the button is pressed – this can be accomplished by changing the body of the onCreate() method:

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);

   Button clickButton = (Button)findViewById(R.id.button1);
   clickButton.setOnClickListener(this);
}

Android instantiates activities by providing them with XML content – this is handled in the setContentView function that had already been provided by the framework. The next step involves finding the button by using the ID that was assigned to it in the XML file we mentioned above.

onClickListener needs to implement an interface. Eclipse will offer autocompletion tools – using them leads to a skeleton structure:

public class MainActivity extends ActionBarActivity implements
OnClickListener
{
   @Override
   public void onClick(View arg0) {
      // TODO Auto-generated method stub
   }

With that, we can proceed to implementing the actual calculation method. The final version of onClick looks like this:

public void onClick(View arg0) {
   // TODO Auto-generated method stub
   EditText myTextLast=(EditText)findViewById(R.id.editText1);
   EditText myTextDelta=(EditText)findViewById(R.id.editText2);
   EditText myResult=(EditText)findViewById(R.id.editText3);

   float myLastCourse=Float.parseFloat(myTextLast.getText().toString());
   float myDelta=Float.parseFloat(myTextDelta.getText().toString());
   Float myResultF=myLastCourse-(myLastCourse/100*myDelta);

   myResult.setText(myResultF.toString());
}

This routine starts out by retrieving pointers to the three text boxes from the R array. The rest of the code is made up of normal Java code, which is run as is. With that, we are done – our calculator is ready for deployment!

Test your app

Sadly, an app that works on paper does not help our friend with the stockbroker. They want to use the app on their phone. Furthermore, real-life programs tend to be complex enough to ensure that some errors will pop up – finding them is much easier if you can see the app working on a phone.

Every Android phone can be used as a debug target as long as it is connected to your PC and has its developer mode enabled. Sadly, Google changed the way the activation works in recent versions of the operating system, so we cannot give you a universally valid sequence. Connect your handset to your PC and click the Play or the Debug buttons – Eclipse will do the rest.

Sometimes, carrying around a phone and its accompanying data cable isn’t feasible. If this is the case, Google offers an emulator that provides a pretty decent (albeit very slow) representation of a real handset. It’s worth remembering that virtual machines need to be set up before use. This can be accomplished easily by opening up the AVD manager, located at Window>Android Virtual Device Manager.

Want to learn more Android development tips? Subscribe to the magazine to get more Android tutorials every month.

Tags: , ,
  • Tell a Friend
  • Follow our Twitter to find out about all the latest Linux news, reviews, previews, interviews, features and a whole more.