Tutorial details

Android Programming | App Code for Sale | Preview

Android Programming - | Android Tutorial

Android Programming - Stanford University Course to teach basic Android programming for an audience with moderate programming experience.

Overview PAGE TOP

Here we walk through the most basic parts of an Android app. Also, homework 1 is at the end of this page.

Step 0 - Installing the Android SDK PAGE TOP

Everything below assume the Android SDK is installed and an AVD (Android Virtual Device) set up so the emulator can work -- there are links for those first steps below for homework 1 at the end of this doc.

First Android Project PAGE TOP

In class I'll create the android default project, and look around to see the important components.

  • In Eclipse, New - Other... Android Project
  • Name like "hello", package like "edu.stanford.LELANDID", select an SDK level such as 2.3.x. Leave everything else at its default setting.
  • Run with the run menu: Run as ... Android Application. See what this trivial application looks like in the phone emulator -- it's just some text sitting on the screen. (The emulator takes long as a few minutes time to boot up the first time. Do not exit the emulator; once it's running, it gets re-used again and again to run your app.)

Manifest Now we'll look at the sources behind this simple app; then we'll add some features to it. Look at default manifest.xml -- there's one Application and it can contain any number of Activities. Lots of other information about an application is declared in its manifest.xml, so this is just our first simple example.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="edu.stanford.nick"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="10" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".HelloActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

"@string/app_name" forms refer to data in the res part of the project. The Activity "android:name" refers to the class name that implements the activity -- ".HelloActivity" (the . means in the current package). The MAIN/LAUNCHER intent provides the app icon to launch this activity. Later we'll see many more examples of intents as a way to invoke an activity.

Activity Source Code

package edu.stanford.nick;

import android.app.Activity;
import android.os.Bundle;

public class HelloActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

The one interesting line at this point is the setContentView() call which installs the UI defined in res/layout/main.xml

main.xml Layout PAGE TOP

  • Linear layout, vertical and horizontal
  • fill_parent = fill out to the size of the parent
  • wrap_content = just big enough to hold our own contents
  • @string/hello = refer to data centralized in res/values/strings.xml. Change some strings there and run again to see how the UI gets those values dynamically.
  • Copy/paste to create a second TextView in the layout and give it some text
  • Note the extensive error-check and auto-complete in xml (ctrl-space to auto-complete)

Graphical Layout PAGE TOP

  • This is a new SDK feature -- neat!
  • Widget types used today: LinearLayout, TextView (text without editing), EditText, Button
  • Use the Graphical Layout button at lower left to switch between the Graphical/XML views of the layout
  • Click on a widget, see its properties below, right click on a widget also accesses properties
  • Need to set the phone screen size and the SDK level in the graphical view (such as Nexus S and SDK 2.3)
  • Add EditText and Button inside the vertical layout
  • By default get ids of the form "@+id/editText1" -- gives the element an id which is available in the source code with the form R.id.exitText1
  • The point: compile time checking that all the various IDs line up right. Eliminates an easy and tedious form of bug.

Now Add Activity Code PAGE TOP

public class HelloActivity extends Activity {

    // Store pointer to EditText widget
    private EditText editText1;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


        // Store a pointer to editText1. Set up button1 to add a !.
        editText1 = (EditText) findViewById(R.id.editText1);
        Button button = (Button) findViewById(R.id.button1);
        button.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
            // Lines inside this onClick() method are run
            // when the button is clicked.
        editText1.setText(editText1.getText() + "!");
      }
    });
    ...
  • findViewbyId -- get pointer to something. Cast the pointer to its real type
  • Demo compile errors if ids etc. do not match
  • button.setOnClickListener(... -- put in code to run when button is clicked. This is a Java "anonymous inner class" -- sorry the syntax is kind of nasty, but at least the format is fixed, so you can get used it. There is also an alternative way to wire some code to button we'll later.

Seeing Crash Trace - LogCat PAGE TOP

  • If the app crashes.. (or you can put in a Null Pointer exception to force a crash)
  • Switch to Debug view (upper right of Eclipse). See the LogCat at lower right (double click it to make it big)
  • Click the "E" in LogCat to see just errors vs. the many other info messages
  • Double clicking a line in the stack trace goes to that line in the source code

Add Image Resource and ImageView PAGE TOP

  • Add a foo.jpg in the location res/drawable/foo.jpg
  • In code, the image is known as R.drawable.foo
  • Drag out an ImageView into the vertical layout, set it to use your image. Maybe adjust its max size.
  • It works in the preview .. you don't really have to run to see it.

Nested Surf LinearLayout PAGE TOP

  • Goal here is to have an "open url" button
  • Add a horizontal LinearLayout
  • Inside place a Button "Surf" and an EditText "http://news.google.com"

Surf Code PAGE TOP

// Start a "web url" intent with editText2 editText2 = (EditText) findViewById(R.id.editText2); Button button2 = (Button) findViewById(R.id.button2); button2.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_VIEW); // most common intent.setData(Uri.parse(editText2.getText().toString())); HelloActivity.this.startActivity(intent); } });

  • Intents -- the mechanism by which various screens/components invoke each other. This is just a first, simple example.
  • Intent has an action and data. Here we specify the "open url" intent .. which will launch the appropriate new activity for that. The "back button" from there comes back to us.

Dial Code PAGE TOP

Here is the intent code to invoke the dialer. As above, add a button/EditText in a nested horizontal layout to dial the number in the text field.

Intent intent = new Intent(Intent.ACTION_DIAL); // vs. _CALL
                intent.setData(Uri.parse("tel:" + editText3.getText().toString()));
                // uri form should be "tel:555-555-5555"
                HelloActivity.this.startActivity(intent);

Homework 1 PAGE TOP

  • The official android developer site is http://developer.android.com, and that's a good first place to look for instructions, docs, examples etc.
  • Install the Android SDK, Eclipse, and ADK Eclipse plugin. See Android SDK Install docs
  • Before running, you also have to set up an Android Virtual Device (AVD) for the emulator -- see AVD setup

Now for homework 1: create an app somewhat similar to the demo app (as far as we got in lecture). In general, we expect homework to be done before the next class, although in this case we're not going to collect the homework; it's just for you to get some practice.

  • Have at least one LinearLayout nested in another LinearLayout
  • Have at least one each of: Button, EditText, TextView
  • You should have at least one button that does something when clicked -- it could manipulate the text as in lecture, or try something else, like changing the color or size of one of the widgets.
  • As shown in lecture, you can practice putting in a Null Pointer bug of some sort, so you can look at the exception trace using LogCat in the Debug view in Eclipse.
  • The exact appearance and function of your app is up to you. We're not going to ask you to turn this one in .. so just go through the steps so you see how it works.

License and Attribution PAGE TOP

http://www.stanford.edu

0 Comments Leave a comment

Please login in order to leave a comment.

Newest first
!

Sign-in to your Chupamobile Account.

The Easiest way to Launch your next App or Game.

Join Chupamobile and get instant access to thousands of ready made App and Game Templates.

Creating an account means you’re okay with Chupamobile’s Terms of Service and Privacy Policy.