Sei sulla pagina 1di 54

Your Android Book

If youre reading this, you are then interested in developing Android apps! I got the same feeling then so
I made this book to help you get started.
But first, check the following requirements:

You must already have knowledge in Java programming.


You must at least have knowledge in application development.

BEGIN HERE
To start, download the ADT Bundle perfect for your computer (whether 32-bit or 64-bit). It includes the
essential Android SDK components and a version of the Eclipse IDE with built-in ADT (Android Developer
Tools) for your Android app development. Visit http://developer.android.com/sdk/index.html to
download.
The Eclipse ADT bundle comes with:
Eclipse + ADT plugin
Android SDK Tools
Android Platform-tools
A version of the Android platform
A version of the Android system image for the emulator
Your computer must also have JDK (Java Development Kit) installed. For the Eclipse ADT, a minimum
version of JDK6 is required. If you still do not have JDK6 or above on your computer, download it first.
Google it, download, unzip, and install it to use the Eclipse ADT.
Once the JDK has installed, unzip your downloaded ADT Bundle, find the Eclipse application icon and
create a shortcut on your desktop.

My Android Book | MARICAR R. SUCALDITO

Table of Contents
Setting-up your Android Working Environment ....................................................................................... 2
Getting Started With Eclipse ADT............................................................................................................. 3
The Android IDE ...................................................................................................................................... 7
Running Your First Android App ............................................................................................................. 10
Working-out the Android App User Interface......................................................................................... 14
Creating an Android App with Two Activities ......................................................................................... 15
Exercise 1.0 ....................................................................................................................................... 16
Exercise 1.1 ....................................................................................................................................... 17
Using Variables and Operations ............................................................................................................. 18
Exercise 2 .......................................................................................................................................... 20
Exercise 2.1 ....................................................................................................................................... 22
Android Widgets ................................................................................................................................... 23
Exercise 3 .......................................................................................................................................... 26
Splash Screen, Scroll View, and Global Variables.................................................................................... 28
Creating Database in Android ................................................................................................................ 43
History of Android ................................................................................................................................. 49
Android Versions and Release Date ....................................................................................................... 50
Android System Architecture ................................................................................................................. 51
Android Activity Life Cycle ..................................................................................................................... 52
The Google Play Store ........................................................................................................................... 53

My Android Book | MARICAR R. SUCALDITO

Setting-up your Android Working Environment


In developing an Android app, you need to create a new Android Application Project which is the
compilation of all the files, source codes, design layouts, objects, and classes included in your app. You
have to specify the location where your project is. The place where projects are stored is called the
Workspace. A workspace can contain one or more projects.
1. Double-click the Eclipse shortcut from your desktop.

2. The Workspace Launcher dialog box shall appear for the first time.

3. Specify a location for your projects workspace. Click Browse button, if necessary. The check box
on the bottom that says Use this as the default and do not ask again will make the chosen
location to store your Android projects automatically.
4. Click OK to open Eclipse ADT.

My Android Book | MARICAR R. SUCALDITO

Getting Started With Eclipse ADT


1. Create a new Android Application project by clicking File New Android Application Project.
The New Android Application dialog box shall appear:

2. Type My First Android App as the Application Name, as shown above. The Application Name
will be the name of the app that will be seen on the Android phone when the app is installed.
3. Leave the Project Name as is, so it will be easier to remember which project the app is. The
Project Name must be a valid identifier so spaces for the name are not allowed.
4. The Package Name identifies which organization your project belongs. So have a Package Name
same for all your Android app projects. The package name is in the reverse format of your
organizations domain name plus the project identifier or the project name. For example, you
want to publish My First Android App at AndroidAppsHere.com then you shall use
com.AndroidAppsHere.myfirstandroidapp. In the example above, ICAISoft.com has been used as
the organizations domain.
The Minimum Required SDK refers to the oldest Android Version your app supports.
The Target SDK refers to the most recent Android Version your app supports.
Compile With identifies which Android Version you want your app to test compiling with.
The Theme refers to the base theme or basic appearance your app will have as its look.
5. Click Next button to continue.

My Android Book | MARICAR R. SUCALDITO

6. Make sure Create custom launcher icon is checked so you may customize your app icon. Let the
Create activity checked. An activity is a single instance of a complete Android app user interface.
Leave Create Project in Workspace checked to include your project in your workspace.
7. Click Next button to continue.

My Android Book | MARICAR R. SUCALDITO

8. For the Launcher Icon, the default Android App icon is used. You can select the Foreground by
clicking Browse button and locate your desired launcher icon, or, select from the available
clipart. You can also have a text foreground icon launcher. For this example, just use the Android
app icon.
9. Choose Center for the Foreground Scaling.
10. Leave Shape to None and Background Color to the default White. Click Next button to continue.

11. Leave Create Activity checked, make sure Blank Activity is selected then click Next button.

12. Leave the default name given for the Activity Name, Layout Name, and the Fragment Layout
Name. The Activity Name will be the name of the Java source code file of your Android app,
Layout Name is the name of the activity interface layout, and the Fragment Layout Name is the
name of the layout of a specific fragment in your activity interface. One activity interface can
have one or more fragments. Click Finish button to create the Android Application new project.

My Android Book | MARICAR R. SUCALDITO

You will notice from the status bar at the bottom that the project is being loaded up:

Wait until the status bar turn into this:


whole Android Application project has been fully loaded up.

This means that the

13. Close the Android IDE Welcome Message if necessary. Your working environment shall be like
this:

My Android Book | MARICAR R. SUCALDITO

The Android IDE


Here are some parts of the Eclipse ADT (Android IDE) that you will most likely use:

1. Package Explorer lets you view the contents of your


workspace in a hierarchy. Through this you can easily
access each parts, files, and folders included in your
Android app project.
Whenever you create a new Android Application Project,
two folders/directories are immediately added, in the
Package Explorer: your projects source directory, and
the appcompat (application compatibility) version. These
two needed each other so be careful not to delete any of
them.
In case you need to open a project, you have to switch
the workspace to where the project you want to open is
located. To do it, just click File Switch Workspace,
then select the workspace you want to use.

My Android Book | MARICAR R. SUCALDITO

2. Graphical Layout this is your working area. It shows the graphical view of your activity. On its
left side is the Palette that includes the graphical tools (like TextView, TextField, Button, Spinner,
CheckBox, RadioButton, etc) which you can drag into your activity user interface (UI).

By default, your activitys UI shows the name of your app and your apps icon on its title bar, and
a TextView with a string of Hello world!
Above your activitys UI are options for the screen to (default is Nexus One) into which you
design your app, Android version use when rendering layouts in Eclipse, the Application Theme,
zoom in and out, and some other design options.
3. Outline Window lets you view the layout of your design in an outline or tree view. This helps
you access and change properties of each parts or objects of your UI quickly.

The default activity layout in Eclipse ADT is Relative Layout. This aligns all objects in the layout,
vertically and horizontally with respect to the other objects that surrounds it.

My Android Book | MARICAR R. SUCALDITO

4. Problems Window located at the bottom, immediately shows problems with your syntax, use
of objects, and lack of necessary requirements so you can run your application smoothly.
If you saw problems in red mark, you have to fix it in order to run your program. Right-click the
problem and select Quick Fix to give you suggestions to fix the problems. Problems in yellow
mark are just warnings and you can still continue running your app even with yellow marked
problems.

My Android Book | MARICAR R. SUCALDITO

Running Your First Android App


All Android apps are run on an emulator or the Android Virtual Device (AVD) to examine how it behaves
on an Android phone. You can set a particular AVD from which to run your Android app.
1. Continuing with your My First Android App project, click Window menu and select Android
Virtual Device Manager.

2. Click the New button to create a new AVD.

You can create different AVD and name it the way you want by specifying the AVD Name.
The Device lets you choose which among the Android phone/device to run your app.
My Android Book | MARICAR R. SUCALDITO

10

The Target and the CPU/ABI usually displays the default based on the device you chose.
3. Type Phone1 as AVD Name. Choose the Nexus 7 (2012) (800 x 1280) under Device. Choose the
default Target and CPU/ABI. For the Skin, choose HVGA, no front camera. Lower down the RAM
to 32 and Internal Storage to 16. All these settings are set to minimum to make the AVD load
and run the fastest.
4. Click OK. Phone1 is now included into your list of AVDs. You can have many AVD with different
settings so you just choose which to test and run your app.

5. Select Phone1 then click Start to launch the Phone1 AVD.

6. On the Launch Options, you can check Scale display to real size and set your desired screen size
to test. You can also check Wipe user data so every time you run the AVD, the previously
installed run are wiped out or cleaned up.
7. Click Launch button to start your AVD.
8. Wait until the AVD is loaded up then you can now close the AVD Manager.

My Android Book | MARICAR R. SUCALDITO

11

9. Minimize the Phone1 AVD while working with your project.


10. Before running your app, make sure everything is set correctly. Right-click MyFirstAndroidApp
project from the Package Explorer, select Properties.
11. If necessary, click Java Build Path. Make sure everything in the options are checked like this:

12. Click OK.


13. Do the same with the appcompat folder from the Package Explorer.
14. You can now run your app. Right-click MyFirstAndroidApp project from the Package Explorer
then choose Run As, select Android Application.
My Android Book | MARICAR R. SUCALDITO

12

15. You will notice the status bar displays the launching updates. The LogCat window may appear
for its first use. If the prompt to open the LogCat window appears, just select Yes. The LogCat
provides the detailed running of threads and processes of the Android project so it will be easier
to trace errors if they exist.
16. Check your AVD. For some, the AVD automatically opens the running app but if not, find the
installed app and click it to open.

There it is! You have now successfully run your first Android app!

My Android Book | MARICAR R. SUCALDITO

13

Designing the Android App User Interface


While AVD is still running, edit your Android App project:
1.

My Android Book | MARICAR R. SUCALDITO

14

Creating an Android App with Two Activities


Lesson: Getting Started with Android Application Development

My Android Book | MARICAR R. SUCALDITO

15

Exercise 1.0
Objectives:

Familiarize with Eclipse IDE.


Create a new Android Application Project.
Set-up Android Virtual Device.
Design application interface using XML.
Use Java language to add functionality to the program.
Run the completed app in the emulator.

Definition of Laboratory Activity:


Mobile applications make information more accessible to people nowadays. In this activity, the
student shall create an Android Application named as Rental Property that consists of two views:

Rental Property

Flora Village

Rental Property

Apartment Finder
Address of Flora Village
104 Sampaguita Road
Camatsile, 2150
Phone: (555) 365-7700

Apartment Details

When the user clicks the Apartment Details button, the second view (Apartment Finder) shall be
displayed.

My Android Book | MARICAR R. SUCALDITO

16

Exercise 1.1
Objectives:

Familiarize with Eclipse IDE.


Create a new Android Application Project.
Set-up Android Virtual Device.
Design application interface using XML.
Use Java language to add functionality to the program.
Run the completed app in the emulator.

Definition of Laboratory Activity:


Mobile applications make information more accessible to people nowadays. In this exercise, the
student shall create an Android Application named as Pet Store that consists of two views:

Pet Store
Gorgeous baby white
rabbits. Eating and
drinking independently.
Babies handled daily by
our 4 and 8 year old
children

Pet Store

Price List
Baby Rabbits

Php 120.00 each

Tiger Pack

Php 20,000.00 each

Our Hotline:

(046) 851-2165

Tiger Pack:
A 5 months old
female tiger with the
original HELLO TIGER
guide and three tiger
toys

View Prices

Shop Address:
#75 Sampalok St., Manggahan,
Gen.Trias, Cavite

When the user clicks View Prices button, the Price List shall be displayed.

My Android Book | MARICAR R. SUCALDITO

17

Using Variables and Operations


When important data are involved in an application, for example, getting user input, processing it,
and displaying the results, using variables to temporarily store values is of great use. Follow the steps
below to learn how to use variables and operations in Android using Java programming language.
1. Create a new Android Application Project named Math Operators.
2. Include the following on the xml layout:
Text View for the Direction.
2 Number (Decimal) Text Fields for the Input. Change layout_width to 50sp
1 Text View below the button for the Output.

Math Operators
Direction: Enter digits on the
text fields then click Compute
button.

Compute

3. Add android:onClick=Compute on the button.


4. Enter the following highlighted codes into your java file.

My Android Book | MARICAR R. SUCALDITO

18

5. To change the cursor focus, move the <requestFocus /> on the xml layout.
6. Run your app.

My Android Book | MARICAR R. SUCALDITO

19

Exercise 2.0
Lesson: Getting User Input, Declaring Variables and Use in Operations in Java
Specific Topics: Android User Input, Variables, and Operations
Objectives:

Develop user interface using Text Fields


Declare variables to hold data.
Use Java language to add functionality to the program.
Run the completed app in the emulator.

Definition of Laboratory Activity:


Mobile applications serve as tool for some computational operations. In this activity, the student
shall create an Android Application named as Survey Monkey that consists of two views:

RSS Survey Inc.

Survey Monkey

RSS Survey Inc.

Q: Are you in favor


of RH Bill?
Responses:

YES
NO

45
55

Total

Poll for the Week

100
Percentage
45%
55%
YES
NO
Calculate

Package Name: com.YourLastNameExercise.surveymonkey


Activity Name: SurveyMonkey
Layout Name: survey_activity
Fragment Layout Name: survey_fragment
The first view shall appear first then when the user clicks Poll for the Week button, second view
shall be displayed. The second view shall allow the user to enter the number of responses to YES and
My Android Book | MARICAR R. SUCALDITO

20

NO, and then when Calculate button is clicked, the Total and the Percentage values shall be
automatically computed. Use the following formulas:
Total = Number of YES + Number of NO
Percentage of YES = (Number of YES / Total) * 100
Percentage of NO = (Number of NO / Total) * 100

My Android Book | MARICAR R. SUCALDITO

21

Exercise 2.1
Objectives:

Develop user interface using Text Fields


Declare variables to hold data.
Use Java language to add functionality to the program.
Run the completed app in the emulator.

Definition of Laboratory Activity:


Mobile applications serve as tool for some computational operations. In this activity, the student
shall create an Android Application named as TM Discount that consists of two views:

TM Discount

Todays
Techno Market
Discount
is

10%

TM Discount

Items

Price
50.00

Card Reader
Flash Drive
External HD

180.00
5000.00

Compute

Total
Discounted Price

5230.00
4707.00

Buy Now!

The application shall allow the user to enter the Prices, and then it shall automatically compute
the Total and the Discounted Price. The Discounted Price is 10% less the Total Price.

My Android Book | MARICAR R. SUCALDITO

22

Android Widgets
1. Open Eclipse. Set your folder as the workspace.
2. Create a new Android Application Project with
Application Name: Widgets
Project Name: Widgets
Package Name: com.YourLastNameExer3.widgets
Choose your own icon
Activity Name: Widgets
Layout Name: activity_widgets
Frame Layout Name: fragment_widgets
3. After the project has been fully loaded, open strings.sml under values folder of resdirectory.
4. Change hello_world properties into:
Name: TextViewString
Value*: This is an example of a TextView. It displays a static text.
Save the changes you made to strings.xml
5. Open fragment_widgets.xml.On the android:text code of the TextView, change hello_world to
TextViewString. Save the changes. Your View should look like this:

6. Add a button and place it under the TextView, on the center of the View.
7. On fragment_widgets.xml, change the button text into I'm a Button.
8. On the Graphical Layout, right-click the button and select Other Properties > All By Name>
Background.
9. Open Drawable, select ic_launcher, then click Ok. Your View should look like this now:

My Android Book | MARICAR R. SUCALDITO

23

10. On the fragment_widgets.xml, add ClickMe on the onClick property of the Button. Save the
changes.
11. Go to Widgets.java and add the following function:

12. Run your app.


13. Change the ClickMe function into:

14. Point the cursor on Gravity and import Gravity widgets to remove error. Run your app.
15. Change xOffset and yOffset of the message gravity from 0, 0 to 100, 100. Run your app.
16. Add two checkboxes, change text into First CheckBox and Second Check Box as follows:

17. Create function CheckBoxClick and instantiate the two check boxes as MyChkBox1 and
MyChkBox2, and the textView as Label in the .java file, just like below:

18. Add a codes to display First CheckBox has been chosen on the TextView when MyChkBox1 is
checked, display nothing on the TextView if unchecked.Display Second CheckBox has been
chosen on the TextView when MyChkBox2 is checked, and so on, as follows:

My Android Book | MARICAR R. SUCALDITO

24

19.
20.
21.
22.

Set onClick methods on the xml layout of the two check boxes.
Run your app.
Drag a spinner widget on the View.
Open strings.xml and add the following:

23. Add the following to the xml of the spinner:


android:entries=@array/Colors
24. Then add the following to your java codes on the ClickMe function:

25. Run your app.

My Android Book | MARICAR R. SUCALDITO

25

Exercise 3
Objectives:

Develop user interface using TextView, Button, Check Box, and Spinner
Declare variables to hold data.
Use Java language to add functionality to the program.
Use formatting techniques for processed data.
Run the completed app in the emulator.

Definition of Laboratory Activity:


In this activity, the student shall create an Android Application named as Check Out that consists of:
Three Checkboxes for each item, TextViews for each prices, TextView for Total Amount and Net Amount,
Spinner for Cash and Check options, and a Button for Compute.

Check Out
Items

Price

PC Unit

25,000.00

HP Printer

7,000.00

Router

1,500.00

Total Amount

33,500.00

Mode of Payment:
Cash
Check

Compute

The application shall allow the user to Check or Uncheck items that will be included. The Price
shall be automatically displayed when the item is selected, if not, the price of 0.00 shall be displayed.
Then the user selects the Mode of Payment, if Cash, the Net Amount is 20% less than the Total Amount,
if Check, the Net Amount is 5% more than the Total Amount. All computations shall be displayed after
the user clicks the Compute button.
Study the following codes:

My Android Book | MARICAR R. SUCALDITO

26

Import the necessary package. Format all numbers in the application into Philippine Peso
format.

My Android Book | MARICAR R. SUCALDITO

27

Splash Screen, Scroll View, and Global Variables


1. Create a new Android Application Project with the following info:

2. Choose the following for the icon:

3. Create the following activity:

My Android Book | MARICAR R. SUCALDITO

28

Your UI must be like this:

4. Run your AVD to prepare running of your app.


5. Change the following property on the xml layout.

6. Add the remaining widgets and apply the xml properties as follows:
My Android Book | MARICAR R. SUCALDITO

29

TextField

My Android Book | MARICAR R. SUCALDITO

30

My Android Book | MARICAR R. SUCALDITO

31

7. Add a new activity on the MyPersonalInfoKeeper

My Android Book | MARICAR R. SUCALDITO

32

8. Change the Splash Theme to Theme.Holo.Light.Dialog.NoActionBar just like:

My Android Book | MARICAR R. SUCALDITO

33

9. Move the Hello World! Text to the center.


10. Add an image view with the ic_launcher as the image.
11. Your Splash shall be look like this:

12. Open your AndroidManifest.xml file and make your SplashActivity as Launcher activity by
moving the intent filter.
From this:

My Android Book | MARICAR R. SUCALDITO

34

To this:

13. Open styles.xml and add the following:

14. On the AndroidManifest.xml, add:

My Android Book | MARICAR R. SUCALDITO

35

15. Change the title of the name of the app by:

16. Click the main layout. On the Properties window, click ... on the Background. Open Drawable
then select ic_launcher. (You can have your own image for a better UI). Click ok.
17. On SplashActivity.java, add the following codes:

18. Run your app.


19. Continue you work. Remove the background image (optional).
Add the following to your main layout:

My Android Book | MARICAR R. SUCALDITO

36

20. Switch to fragment_main.xml and add ScrollView tag, cut and paste some of the properties of
the relative layout as follows. Also, change the layout_height of the RelativeLayout.

21. At the end of the xml code, close the ScrollView tag:

My Android Book | MARICAR R. SUCALDITO

37

22. Run your app.


23. Continue your work. Click File, New Class. New Java Class dialog shall appear.

24. Type GVariables as the Name. Make sure you have the same settings as above then click Finish.
25. Add the following to GVariables class:

My Android Book | MARICAR R. SUCALDITO

38

26. On the AndroidManifest, set the application name:

27. On MainActivity:
Add the function Next

28. Create the Last Activity:

29. Delete the hello world textView, then add textView1 and textView2. Dont forget to always save.

My Android Book | MARICAR R. SUCALDITO

39

30. On AndroidManifest, change the LastActivity label:

31. On the LastActivity.java, add the following function:

32. Go back to MainActivity.java and add the following code:

33. Set Next to the onClick property of the button

My Android Book | MARICAR R. SUCALDITO

40

34. Run and test your app:

35. Now, get all the data from MainActivity and place it on the LastActivity like this:

My Android Book | MARICAR R. SUCALDITO

41

You have successfully saved the


following Personal Information!
First Name:
Middle Name:
Last Name:
Cellphone No:
Telephone No:
BirthDate:
City:

Juan
Reyes
Dela Cruz
098787898767
4162272
August 8, 1993
Marikina

36. Run your app.

My Android Book | MARICAR R. SUCALDITO

42

Incorporating Database in an Android App


1. Open Eclipse. Set your folder as the workspace.
2. Run your emulator/AVD.
3. Create a new Android Application Project with the following:

4. Leave the rest of the settings to create a Blank Activity with MainActivity class.
5. Remove the default TextView with HelloWorld string and add the following widgets:
2 TextView, 2 EditText (TextFieldPlain Text), and 2 Button
Set the textSize of the 2 TextView to 20sp.
Set the layout_width of the 2 EditText to 180sp, ems to 8.
Run your app, it should look like this:

6. To create a database, we will use SQLiteOpenHelper by extending it to a java class.


Create a new class by right-clicking MyBooks project New Class

My Android Book | MARICAR R. SUCALDITO

43

7. Set the new class name as MySQLiteHelper just like below. Leave it as public
and click Finish button.

8. Extend SQLiteOpenHelper to the newly creates MySQLiteHelper class. Hover the


cursor above SQLiteOpenHelperand import
android.database.sqlite.SQLiteOpenHelper

My Android Book | MARICAR R. SUCALDITO

44

9. Add two important variables, the databaseName and the databaseVersion:

10. Notice the class MySQLiteHelper asks for its constructor. So add the following constructor.

11. The MySQLiteHelper asks for two unimplemented methods, so add onCreate and onUpgrade
methods as follows.

The onCreate method creates the table Books, while the onUpgrade method drops the old
Books table and replaces it with a new one.
My Android Book | MARICAR R. SUCALDITO

45

12. Add four variables, one for the table name, and three for the three column headings / field
names. Add an array String column:

13. Add three variables for the contents of the fields, make it public so it can be accessed by
MainActivity class.

14. Now add the addBook method which needs arguments for book title and book author such as:

Import the necessary package for the ContentValues. Since Id is AutoIncrement, we do not put
values to it.
15. Next, add the getBook method:

Import Cursor package. The Cursor returns the row of data as the result of the query. If the
query result is not empty, cursor.moveToFirst() places the cursor to read the first record, then
assigns contents to rId, rTitle, and rAuthor. Try.. Catch.. Statement has been added to capture
NullPointerException when executing the query.
Here are the complete codes of MySQLiteHelper.java:

My Android Book | MARICAR R. SUCALDITO

46

}
My Android Book | MARICAR R. SUCALDITO

47

16. Now go to theMainActivity.java and add the following method:

This method gets Title and Author of the Book from the user input through EditText, calls
addBook method of MySQLiteHelper and add book information to the database.
17. On the fragment_main.xml, set android:onClick=addBookClick on button1
18. Add another method in the MainActivity.java

This method searches for the book information based on the Title entered by the user. It
displays the Title and Author of the book searched.
19. On the fragment_main.xml, set android:onClick=getBookClick on button2
20. Test, Debug, and Run your app.

My Android Book | MARICAR R. SUCALDITO

48

History of Android

My Android Book | MARICAR R. SUCALDITO

49

Android Versions and Release Date

My Android Book | MARICAR R. SUCALDITO

50

Android System Architecture

My Android Book | MARICAR R. SUCALDITO

51

Android Activity Life Cycle

My Android Book | MARICAR R. SUCALDITO

52

The Google Play Store

My Android Book | MARICAR R. SUCALDITO

53

Potrebbero piacerti anche