Android Cheat Sheet

Android Cheat Sheet

This cheat sheet is designed as a helpful guide for Treehouse's Build an Android Crystal Ball App project and other basic Android development. Tips for using Eclipse, the recommended IDE for Android development, are also included.


Table of Contents


Android

The Android developer site contains fantastic documentation about everything you need to know to create Android apps. One of the most useful sections is the API Documentation. You can easily search for a specific API simply by Googling the Android class name plus " api" (ex. "Activity api").

The screen of an Android app is made up of two parts: the layout, which is how it looks on the screen, and the Activity, which is the Java code that controls how the layout behaves and reacts to user input.

Layouts

Eclipse includes a drag-and-drop Graphical Layout Editor to design and edit layout files. Layouts are encoded in XML and are stored in the res/layout directory of an Android project. Some of the basic layouts are as follows.

LinearLayout

Child elements are added to this type of layout in a linear fashion (horizontally or vertically). The following shows a text field followed by a button:

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

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

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

</LinearLayout>

RelativeLayout

RelativeLayouts are used to position child elements relative to the layout borders and/or other child elements. The following layout gives a centered text label that says "I love Treehouse!":

<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="top" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center_horizontal"
        android:text="I love Treehouse!" />

</RelativeLayout>

Setting Width and Height

Most views in a layout have width and height parameters that need to be set. For example, the following XML sets a TextView to span the width of the parent but only be as high as it needs to be for the text:

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

Units for Sizes

Don't use pixels for sizes in Android apps. Instead, use:

Activities

Activities are hooked to layouts, and their code is called when events occur. Events can either be a part of the Android Activity Lifecycle (such as when an app first starts, is interrupted by a phone call, etc.), or by user input, like a tap or swipe.

Activity is a subclass of Context, and Context is king in Android. Context has a lot of useful methods that are consequently available in the Activity class, too.

Much of the work in an Activity class is often done in the onCreate() method:

01  public void onCreate(Bundle savedInstanceState) {
02      super.onCreate(savedInstanceState);
03      setContentView(R.layout.activity_main);
04
05      TextView nameLabel = (TextView) findViewById(R.id.nameLabel);
06  }

The onCreate() method is called when the Activity is first created, i.e. when starting the app or navigating to a new Activity. In each lifecycle method like this, you almost always want to call the method from the parent class, like in line 02 of this example.

The layout is hooked up by the setContentView() method, as shown in line 03.

The Activity findViewById method is used to hook views from the layout to objects in code. In line 05 a TextView object named 'nameLabel' references the TextView in the layout with the ID 'nameLabel'.

Resources

The res directory in an Android project contains the resources for an app like images, sounds, and layouts, among other things.

Drawables

Images and other visual files are stored in one or more drawable directories. If only in one directory, Android will scale the image as needed. If more than one directory is used, Android will select the appropriately sized image.

XML files can also be written and stored as drawables. These kinds of files can control when multiple images are to be used based on the state of a view, or other visual settings like gradients, borders, etc.

Strings

String values in Android are typically stored in a separate file called strings.xml in the res/values directory. This allows the Strings to be defined in one place and used throughout the app, and it also allows developers to swap out entire files for different language versions.

Example:

<resources>
    <string name="company_name">Treehouse</string>
    <string name="url">http://www.teamtreehouse.com</string>
    <string name="twitter_handle">@treehouse</string>
</resources

These String values can be referenced in both Java and XML:

Java: R.string.string_name
The Context object (and hence, Activities) has a method called getString(int resId) that is used to get a String from the resource file:

String companyName = getString(R.string.company_name);

XML: @string/string_name

<TextView
    android:id="@+id/companyNameLabel"
    android:text="@string/company_name" />

Arrays of Strings can also be stored in the strings.xml file:

<resources>
    <string-array name="planets_array">
        <item>Mercury</item>
        <item>Venus</item>
        <item>Earth</item>
        <item>Mars</item>
    </string-array>
</resources>

Example:

String[] planets = getResources().getStringArray(R.array.planets_array);

Styles

Android UI elements can be styled, much like CSS styles for web pages. Styles are defined in XML files and are typically stored in res/values/styles.xml

Example:

<resources>
    <style name="CodeFont" parent="@android:style/TextAppearance.Medium">
        <item name="android:layout_width">fill_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textColor">#00FF00</item>
        <item name="android:typeface">monospace</item>
    </style>
</resources>

Styles can then be applied to XML layout files like this:

<TextView
    style="@style/CodeFont"
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="int dogYears;" />

Raw

Raw audio/video resource files can be stored in the res/raw directory. These can include things like mp3s and mp4s.

Logging

Write to the log using the Log class and one of the static methods. Each method has two parameters: the tag and the message:

The tag is used to denote where this message was logged (typically the name of the class). This is useful for filtering messages in the logcat view.

The message is the information to be written to the log.

The log is viewed using the logcat view, which is available in Eclipse or as a separate app you can install on your device. The logcat view can be filtered by things like the tag or text to search for.

Toasts

A Toast is a notification that pops up on the screen for a limited time. The makeText() method creates the Toast, and the show() method shows it. These two methods are usually chained together, like this:

Toast.makeText(this, "Text to toast!", Toast.LENGTH_LONG).show();

The first parameter of makeText() is the context. The keyword this can be used inside an Activity. The second paremeter is the text to appear in the Toast notification, and the third parameter is the length of time (in milliseconds) before the Toast disappears.


Eclipse

Keyboard Shortcuts

Windows Mac Result
Ctrl+S Cmd+S Save
Ctrl+Shift+S Cmd+Shift+S Save All
Ctrl+Shift+O Cmd+Shift+O Organize Imports
Ctrl+Space Ctrl+Space Bring up Intellisense
Ctrl+Shift+F Cmd+Shift+F Auto-format code
Ctrl+F Cmd+F Open Find/Replace Dialog
Ctrl+K Cmd+K Find Next
Ctrl+Shift+K Cmd+Shift+K Find Previous
Ctrl+/ Cmd+/ Comment/Uncomment code
Alt+Shift+R Alt+Cmd+R Refactor > Rename

Running an App

You can run an app in an emulator (Android Virtual Device) or on an actual device connected via USB. Click on the Run button in the toolbar or right-click on a project in Package Explorer and select Run As > Android Application. Running an app will launch an appropriate emulator if none are already running.

Debugging

Add breakpoints in code by double-clicking in the gutter next to the line where you want the breakpoint set, or by selecting Run > Toggle Breakpoint. Start the debugger by clicking on the Debug icon in the toolbar or right-click on a project in Package Explorer and select Debug As > Android Application. The debugger uses a separate perspective (called "Debug").

Stepping Through Code

Some of the important buttons when debugging are:

Debug buttons

  1. Resume - continue processing after stopping at a breakpoint
  2. Terminate - Stop the debugger and app
  3. Disconnect - Disconnect the debugger from the running app
  4. Step Into - Step into the next method call on the current line (if any; otherwise acts the same as Step Over)
  5. Step Over - Step past the current line to the next one
  6. Step Return - Step to the end of the current enclosing method

When the debugger is paused on at a breakpoint, you can examine variables in the code through Intellisense


Java

For a quick overview of some of the basic Java concepts necessary for Android development, check out the series of blog posts on the Treehouse blog starting with Java Basics for Android Development - Part 1.

Variables

To declare a variable, provide the data type and a name for the variable, followed by a semicolon:

String myName;

Assign values to a variable using the equals sign operator:

String myName = "Ben";

For member variables in classes, an access modifier controls who can access the variable.

Access Modifiers Same Class Same Package Subclass Other Packages
public Y Y Y Y
protected Y Y Y N
private Y N N N
no access modifier Y Y N N

Example usage:

public String mName;
private String mAppKey;

Methods

A method is a section of code that we can call from elsewhere in our code, and the method will perform some action or return some kind of result that we can use.

To declare a method, provide an access modifier, the data type of the object or value returned from the method (void if nothing is returned), a name, and parameters (empty parenthesis if none). The code of the method is placed inside curly braces:

Example:

public int addTwoIntegers(int a, int b) {
    int result = a + b;
    return result;
}

Calling a method:

int sum = addTwoIntegers(1, 2); // sum will be 3

Arrays

Arrays are structured lists of pieces of data where each piece of data is referenced by its position in the array.

Declare an array of a type of object or data by adding square brackets after the data type:

String[] colors;

There are a few ways to initialize an array:

String[] colors = { "Red", "White, "Black" };
String[] shapes = new String[3]; // The parameter in the brackets is the size of the array

Values for array items can be accessed and assigned using the index in the array. Arrays in Java start with an index of zero:

String[] colors = new String[3];
colors[0] = "Red";
colors[1] = "White";
colors[2] = "Black";
String favoriteColor = colors[0]; // favoriteColor will be "Red"

The length of an array is accessed using the length property:

int highScores = new int[10];
int numberOfHighScores = highScores.length;

Classes and Objects

Java code is typically organized into classes and packages. Classes contain pieces of data (member variables) and methods. Packages are simply groups of related classes.

public class Book {

    // Member variables
    private String mTitle;
    private String mAuthor;
    private String mPublisher;

    // Methods
    public String getTitle() {
        return mTitle;
    }
)

Classes are like blueprints for objects. Objects can be instantiated from classes, usually by using the new keyword:

Book myBook = new Book();

Casting

Sometimes (especially in Android) you need to convert a generic object to a more specific subclass. For example, the method findViewById() returns a generic View object, but the same method is used to get Buttons, EditTexts, TextViews, and other subclasses of View. When you know what object type it should be, you can add a cast in parenthesis:

Button myButton = (Button) findViewById(R.id.button1); 

Without the cast to (Button), this line of code tries to force a View into the myButton variable, which will result in a compile-time error.

Comments

Comments have no affect on how the code runs. They are there for reference when you or another developer is reading the code.

// This is a single-line comment

/* This is a comment
   that spans multiple
   lines */