Cheat Sheet

Java Programming for Android Developers For Dummies

Android is turning into the open source, Linux- and Java-based, software framework for mobile and portable devices. The Android operating system now powers nearly half of all smartphones in the world today. Android not only has a majority of users, but with the help of a (very well designed) Java-based software development kit (SDK, for short), developing apps van be straightforward and fun. This cheat sheet concentrates on commonly used code handy for any developer wishing to try their hand at building their own Android applications with the help of Java.

Commonly Used Java Code

"I have to create an enhanced for statement. Can someone remind me how to code an enhanced for statement? And while you're at it, how can I catch an exception? Where can I find all that Java stuff quickly?"

You find all that stuff right here in this cheat sheet. The Java program in this cheat sheet contains snippets of code representing many of Java's most important language features, including switches, strings, breaks, if . . . else statements, and arrays. As an added bonus, the program even contains a sly reference to that classic Marx Brothers movie, Animal Crackers. Enjoy!

package com.example.cheetsheet;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class CheatSheet {
  int myInt = 42;
  double myDouble = 27649.00;
  boolean myBoolean = true;
  public static void main(String[] args) {
    new CheatSheet();
  }
  public CheatSheet() {
    char myChar = 'B';
    String myString = "Hello";
    ArrayList<String> myList = new ArrayList<String>();
    String[] myArray = 
        { "This ", "is ", "an ", "array." };
    System.out.println(myInt);
    System.out.println(myChar);
    JOptionPane.showMessageDialog(null, myString);
    System.out.println
        (myInt + " " + myString + " " + myDouble);
    String stringIn = JOptionPane
        .showInputDialog("Enter a number from 1 to 10");
    try {
      myInt = Integer.parseInt(stringIn);
    } catch (NumberFormatException e) {
      e.printStackTrace();
    }
    if (myInt < 5) {
      System.out.println("Small");
    } else {
      System.out.println("Large");
    }
    if (myBoolean) {
      System.out.println("Yes");
    }
    switch (myInt) {
    case 1:
      System.out.println("One");
      break;
    case 2:
    case 3:
      System.out.println("A small number");
      break;
    default:
      System.out.println("A lot");
      break;
    }
    for (int i = 0; i < 10; i++) {
      System.out.print(i);
      System.out.print(" ");
    }
    System.out.println();
    
    int i = 0;
    while (i < 10) {
      System.out.print(i++ + " ");
    }
    System.out.println();
    
    int j = 0;
    do {
      System.out.print(j++);
      System.out.print(j <= 9?", ":"");
    } while (j < 10);
    System.out.println();
    
    myList.add("Three ");
    myList.add("cheers ");
    myList.add("for ");
    myList.add("Captain ");
    myList.add("Spaulding");
    for (String word : myList) {
      System.out.print(word);
    }
    System.out.println();
    System.out.println(addPeriod("Spaulding"));
    for (int n = 0; n < myArray.length; n++) {
      System.out.print(myArray[n]);
    }
    System.out.println();
  }
  String addPeriod(String string) {
    return string + ".";
  }
}

How to Create a Really Simple Android App

So, you want to see the fundamentals of Android app development in one small example? How about the app that Eclipse creates for you automatically? Too simple? How about adding a button and a menu?

This sample app has three states. At first, you see a button with the words Click me on its face. When you click the button, the button's text changes to I've been clicked.

On most newer Android devices, you invoke the activity's menu by clicking a small icon in a corner of the activity's screen. (Usually, the icon contains three dots in a vertical line.) When you click this menu icon, the simple activity shows you only one option — the option to Reset. In the sample app, when you then click Reset, the button's text reverts to Click me.

A simple app's main activity

This listing contains the app's main activity. The lines that you type yourself are set in boldface. The other lines (the line that Eclipse creates automatically when you start a new Android project) are set in normal font.

package org.allyourcode.simpleactivity;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
  Button button;
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button = (Button) findViewById(R.id.button1);
  }
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
  }
  public void whenButtonClicked(View view) {
    button.setText(R.string.ive_been_clicked);
  }
  
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.menu_reset) {
       button.setText(R.string.click_me);
    }
    return super.onOptionsItemSelected(item);
  }
}

To make this code work, you have to define a few extra goodies. In particular, you need the following:

  • A button on your main activity's layout

  • A layout file for your menu

  • A few string values

You can create all these things with Eclipse's point-and-click tools, but here, you can see the code. (Sometimes, it's easier to type code than to do lots of pointing and clicking.)

The main activity's layout file

This listing contains the code for the main activity's layout.

<RelativeLayout xmlns:android=
        "http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom=
        "@dimen/activity_vertical_margin"
    android:paddingLeft=
        "@dimen/activity_horizontal_margin"
    android:paddingRight=
        "@dimen/activity_horizontal_margin"
    android:paddingTop=
        "@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="32dp"
        android:onClick="whenButtonClicked"
        android:text="@string/click_me" />
</RelativeLayout>

You put the code in Listing 2 in your project's res/layout/activity_main.xml file. Many variations on the code in Listing 2 work equally as well. In Listing 2, the important elements are the ones in boldface type — an id for the button (@+id/button1 or @+id/whatever), the name of the method to handle a button click, and the text on the button's face.

The menu's layout file

The layout for the menu belongs in your project's res/menu directory. This listing contains the code.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android=
      "http://schemas.android.com/apk/res/android">
  <item android:id="@+id/menu_reset" 
        android:title="@string/reset" />
</menu>

A menu's layout file contains one or more item elements. In this article's simple app, the menu has only one option. So the layout file has only one item element.

The example's item element has two attributes:

  • The android:id attribute identifies the item.

    In the main activity, the android:id value decides whether the user has or hasn't clicked this menu item:

if (item.getItemId() == R.id.menu_reset)

  • The android:title attribute determines the text that appears along with the menu option.

    In Listing 3, the name @string/reset refers to an element added to the project's strings.xml file.

The project's text strings

The strings.xml file lives in the project's res/values directory. In the strings.xml file, all the text labels used in the code are defined. (See the following listing.)

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="app_name">Simple Activity</string>
  <string name="action_settings">Settings</string>
  <string name="hello_world">Hello world!</string>
  <string name="click_me">Click me</string>
  <string 
    name="ive_been_clicked">I\'ve been clicked</string>
  <string name="reset">Reset</string>
</resources>

Elsewhere in the project, the name attributes in this Listing is used instead of the strings Click me, I've been clicked, and Reset. For example, the names R.string.click_me and R.string.ive_been_clicked appear in the main activity listing and the main activity's layout file. And the reference @string/reset appears in the menu's layout file listing.

A double-quote mark has a special meaning in XML documents. For example, in the text strings listing, the quotation marks in name="click_me" tell you where the name attribute's value begins and ends. In the same way, a single quotation mark (without the backslash) has a special meaning in XML. So, in the text strings, you use the combination \' to put an apostrophe in the word I've. The combination \' is called an escape sequence. The escape sequence tells the computer that you're using an ordinary single quotation mark, with no special meaning intended.

Turning Standard Oracle Java into Android Java

Here's the scenario: You have a killer app, written in Java. The app runs on the Windows and Macintosh operating systems. The app doesn't run on a mobile device (because Java SE programs don't run on mobile devices).

You want to know how the app looks when it runs on an Android device. And here's one more thing: You don't want to do any serious thinking. That would involve too much stress!

A Java program for a desktop or laptop computer

Can you quickly and mechanically turn the app into an Android app? You can. Start with the simple program in this listing.

package com.allmycode.tickets;
import javax.swing.JOptionPane;
public class TicketPrice {
  public static void main(String[] args) {
    String ageString;
    int age;
    String price;
    
    ageString = JOptionPane.showInputDialog("Age?");
    age = Integer.parseInt(ageString);
    
    if (age < 18 || 65 <= age) { 
      price = "$7.00";
    } else {
      price = "$10.00";
    }
    
    JOptionPane.showMessageDialog(null, 
        price, "Ticket price", 
        JOptionPane.INFORMATION_MESSAGE);
  }
}

The code in this listing prompts the user for a number (the user's age). If the user is a child or a senior, the ticket price is only $7.00. Otherwise, the ticket price is $10.00.

To convert this listing into an Android app, do the following:

  1. Using Eclipse, create an Android project.

  2. In the main activity's layout file, create at least three widgets: an EditText widget, a Button widget, and a TextView widget.

A res/layout/activity_main.xml file

Here's a sample layout file.

<RelativeLayout xmlns:android=
    "http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:paddingBottom="@dimen/activity_vertical_margin"
  android:paddingLeft="@dimen/activity_horizontal_margin"
  android:paddingRight=
    "@dimen/activity_horizontal_margin"
  android:paddingTop="@dimen/activity_vertical_margin"
  tools:context=".MainActivity" >
  <EditText
      android:id="@+id/editText1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="16dp"
      android:ems="10"
      android:hint="@string/enter_age"
      android:inputType="number" >
      <requestFocus />
  </EditText>
  <Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/editText1"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="18dp"
    android:onClick="whenButtonClicked"
    android:text="@string/submit" />
  <TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/button1"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="29dp"
    android:text="@string/ticket_price"
    android:textAppearance=
      "?android:attr/textAppearanceMedium" />
</RelativeLayout>

In this listing, the editText1 field is where the user enters his or her age. The user clicks the button1 widget to tell the app to calculate a ticket price, and then the ticket price appears in the textView1 field.

In the next step, you give meaning to the @string things from this second listing.    

A res/values/strings.xml file

Add string elements to the app's strings.xml file, as shown in this listing.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Ticket Price</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="enter_age">Enter your age here</string>
    <string name="submit">Submit</string>
    <string name="ticket_price">Ticket price</string>
</resources>

The boldface lines in this listing provide meanings for the names @string/enter_age, @string/submit, and @string/ticket_price in the activity's layout file.

This is your chance to make your app usable for readers all around the world. For example, to create the French translation of your app, add a res/values-fr directory to the project. In a strings.xml file in the res/values-fr directory, use the same name attributes (enter_age, submit, and ticket_price). But between each start tag and end tag, put the French translation of the text that appears on the user's screen. When French-speaking customers use your app, they see the text in their native tongue.    

The main activity

Add code to the main activity's Java file, as shown in this listing.

package com.example.ticketprice;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
  EditText editText;
  TextView textView;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    editText = (EditText) findViewById(R.id.editText1);
    textView = (TextView) findViewById(R.id.textView1);
  }
  public void whenButtonClicked(View view) {
    String ageString;
    int age;
    String price;
    ageString = editText.getText().toString();
    age = Integer.parseInt(ageString);
    if (age < 18 || 65 <= age) {
      price = "$7.00";
    } else {
      price = "$10.00";
    }
    textView.setText(price);
  }
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
  }
}

In Listing 2, the button's onClick attribute has value whenButtonClicked. So in Listing 4, you respond to a click of the button with your new whenButtonClicked method. This whenButtonClicked method contains most of the statements that were in your original standard Java program. The big difference is the way you get text from the user, and the way you display results on the user's screen.

  • In the standard Java program you use JOptionPane to create dialog boxes. The boxes prompt the user for input, and display the program's results.

  • In the Android Java program, you use the widgets on the activity's screen for input and output. Having declared editText near the start of the code, you call editText.getText().toString() to fetch the user's input. And having declared textView near the start of the code, you call textView.setText(price) to display the program's results.

And there you have it — an Android program from a standard Java program!

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.