Todo List Example

In this example you'll be creating a new Android application from scratch. This simple example creates a new to-do list application using native Android View controls. It's designed to illustrate the basic steps involved in starting a new project.

Don't worry if you don't understand everything that happens in this example. Some of the features used to create this application, including ArrayAdapters, Listviews, and KeyListeners, won't be introduced properly until later chapters, where they'll be explained in detail. You'll also return to this example later to add new functionality as you learn more about Android.

1. Start by creating a new Android project. Within Eclipse, select File O New O Project..., then choose Android (as shown in Figure 2-10) before clicking Next.

; New Project I I B M^T

Select a wizard

Wizards:

type filter text

> General j Android

Android Project jjj1 Android Test Project 6 & CVS

> Qy Examples

(?) | < Bach || Next?

Finish

Cancel

2. In the dialog box that appears (shown in Figure 2-11), enter the details for your new project. The "Application name'' is the friendly name of your application, and the "Create Activity'' field lets you name your Activity. With the details entered, click Finish to create your new project.

FIGURE 2-11

3. Before creating your debug and run configurations, take this opportunity to create a virtual device to test your apps with.

Select Window O Android SDK and AVD Manager. In the resulting dialog (shown in Figure 2-12), select Virtual Devices from the left panel and click the New... button.

Enter a name for your device, and choose an SDK target and screen resolution. Set the SD Card size to larger than 8 MB: enter 12 into the text-entry box as shown in Figure 2-13.

Prepared for ASHLEE KABAT, email: [email protected] Order number: 56760408 This PDF is for the purchaser's personal use in accordance with the Wrox Terms of Service and under US copyright as stated on this book's copyright page. If you did not purchase this copy, please visit www.wrox.com to purchase your own copy.

Android SDK and AVO Manager

Virtual Devices

Installed Packages Available Packages

List of existing Android Virtual Devices:

List of existing Android Virtual Devices:

AVDName

Target Name

Platform

API Level

^ ExpertAndroid

Google APIs (Google Inc.)

1.5

Î

VG1

Android 2.0

2.0

5

ProAndrold

Google APIs (Google fnc.)

1.5

Refresh v A valid Android Virtual Device.

X An Android Virtual Device that failed to load. Click Details' to seethe error.

Refresh v A valid Android Virtual Device.

X An Android Virtual Device that failed to load. Click Details' to seethe error.

FIGURE 2-12

FIGURE 2-13

4. Now create your debug and run configurations. Select Run O Debug Configurations... and then Run O Run Configurations..., creating a new configuration for each specifying the Todo_List project and selecting the virtual device you created in Step 3. You can leave the launch action as Launch Default Activity, or explicitly set it to launch the new ToDoList Activity, as shown in Figure 2-14.

5. Now decide what you want to show the users and what actions they'll need to perform. Design a user interface that will make these actions as intuitive as possible.

In this example we want to present users with a list of to-do items and a text entry box to add new ones. There's both a list and a text-entry control available from the Android libraries. (You'll learn more about the Views available in Android, and how to create new ones, in Chapter 4.)

The preferred method for laying out your UI is using a layout resource file. Open the main.xml layout file in the res/layout project folder, as shown in Figure 2-15.

6. Modify the main layout to include a Listview and an EditText within a LinearLayout. It's important to give both the Edit Text and List view an ID so you can get references to them both in code.

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <EditText android:id="@+id/myEditText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="New To Do Item"

<ListView android:id="@+id/myListView" android:layout_width="fill_parent" android:layout_height="wrap_content"

</LinearLayout>

7. With your user interface defined, open the ToDoList Activity from your project's source folder. In this example you'll make all your changes by overriding the onCreate method. Start by inflating your UI using setContentView and then get references to the Listview and EditText using findViewByld.

public void onCreate(Bundle savedlnstanceState) { super.onCreate(savedlnstanceState);

// Inflate your view setContentView(R.layout.main);

Name: Chapter2_Todo_List

Pi Android IP Target □ Common

Project:

Chapter2_Sarnple_Todo_List | Browse... j

Launch Action: © Launch Delault Activity

id'Launch: | com. pa ad. tod olist.ToDoList ^

© Do Nothing

Apply Revert

FIGURE 2-14

ft Packaa Hierarc

C h a pte r2_ S a m pi e_Tod o_Li st a $ com.paad.todolhst

[> gen [Generated Java Files]

a Hndroidr.1am1est.xml [2 defauit.properties

FIGURE 2-15

// Get references to UI widgets

ListView myListView = (ListView)findViewByld(R.id.myListView); final EditText myEditText = (EditText)findViewByld(R.id.myEditText);

8. Still within onCreate, define an ArrayList of Strings to store each to-do list item. You can bind a ListView to an ArrayList using an ArrayAdapter, so create a new ArrayAdapter instance to bind the to-do item array to the ListView. (We'll return to ArrayAdapters in Chapter 5.)

public void onCreate(Bundle savedlnstanceState) { super.onCreate(savedlnstanceState); setContentView(R.layout.main);

ListView myListView = (ListView)findViewByld(R.id.myListView); final EditText myEditText = (EditText)findViewByld(R.id.myEditText);

// Create the array list of to do items final ArrayList<String> todoItems = new ArrayList<String>(); // Create the array adapter to bind the array to the listview final ArrayAdapter<String> aa; aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoItems); // Bind the array adapter to the listview. myListView.setAdapter(aa);

9. The final step to make this to-do list functional is to let users add new to-do items. Add an onKeyListener to the EditText that listens for a "D-pad center button'' click before adding the contents of the EditText to the to-do list array and notifying the ArrayAdapter of the change. Then clear the EditText to prepare for another item.

public void onCreate(Bundle savedlnstanceState) { super.onCreate(savedlnstanceState); setContentView(R.layout.main);

ListView myListView = (ListView)findViewByld(R.id.myListView); final EditText myEditText = (EditText)findViewByld(R.id.myEditText);

final ArrayList<String> todoItems = new ArrayList<String>(); final ArrayAdapter<String> aa; aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoItems);

myListView.setAdapter(aa);

myEditText.setOnKeyListener(new OnKeyListener() {

public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN) if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER){

todoItems.add(0, myEditText.getText().toString()); aa.notifyDataSetChanged(); myEditText.setText(""); return true;

return false;

10. Run or debug the application and you'll see a text entry box above a list, as shown in Figure 2-16.

11. You've now finished your first "real" Android application. Try adding breakpoints to the code to test the debugger and experiment with the DDMS perspective.

All code snippets in this example are part of the Chapter 2 To-do List project, available for download at Wrox.com.

As it stands, this to-do list application isn't spectacularly useful. It doesn't save to-do list items between sessions, you can't edit or remove an item from the list, and typical task-list items like due dates and task priority aren't recorded or displayed. On balance, it fails most of the criteria laid out so far for a good mobile application design.

You'll rectify some of these deficiencies when you return to this example in later chapters.

Write Killer Mobile App

Learn Android

FIGURE 2-16

App Gangster

App Gangster

Get All The Support And Guidance You Need To Be A Success At Dominating Apps. This Book Is One Of The Most Valuable Resources In The World When It Comes To Becoming The Godfather Of Smart Phone Apps.

Get My Free Ebook


Post a comment