Anda di halaman 1dari 62

Divya

Pavani
VIT UNIVERSITY
1
Android: Introduction
One of the most widely used mobile OS these days
is ANDROID.
Android is a software bunch comprising not only
operating system but also middleware and key
applications.
The AndroidSDK provides the tools and APIs
necessary to begin developing applications on the
Android platform using the Java programming
language.
2
Standalone ADT Installation
Download
Google provides a pre-packaged and configured
Eclipse based Android development environment. The
following link allows to download a archive file which
includes all required tools for Android development.

http://developer.android.com/sdk/index.html
3
Extract the zip file and start Eclipse from
the eclipse folder via the eclipse native launcher,
e.g. eclipse.exe under Windows.
Install a specific Android version

4
The dialog allows you to install and delete packages. Select Available
packages and open the Third Party Add-ons. Select the latest Google
API (highest number) of the SDK and press the Install button. Press
the Install button and confirm the license for all packages. After the
installation completes, restart Eclipse.
5

Create & Run Android Virtual Device
Create AVD
To define an Android Virtual Device (ADV) open the AVD
Manager dialog via Windows Android Virtual Device Manager and
press the New button.
6
Afterwards press the OK button. This will create the
AVD configuration and display it under the list of
available virtual devices.
7
Run AVD
To test if your setup is correct, select your new entry and press
the Start button. After some time your AVD starts. Do not interrupt this
startup process, as this might corrupt the AVD. After the AVD started, you
can use the AVD via the mouse and via the virtual keyboard of the
emulator.

8
Create a Project with Eclipse
Select "File/New/Project". In the "New Project" dialog,
select "Android application Project" and click "Next".
Fill in the form that appears:
9
Application Name is the app name that appears to users. For this project,
use "My First App.
Project Name is the name of your project directory and the name visible
in Eclipse.
Package Name is the package namespace for your app
Minimum Required SDK is the lowest version of Android that your app
supports, indicated using the API level.
Target SDK indicates the highest version of Android (also using the API
level) with which you have tested with your application.
Compile With is the platform version against which you will compile your
app.
Theme specifies the Android UI style to apply for your app.
Click Next.
On the next screen to configure the project, leave the default selections
and click Next.
The next screen can help you create a launcher icon for your app.
Click Next.
Now you can select an activity template from which to begin building your
app. For this project, select BlankActivity and click Next.
Leave all the details for the activity in their default state and click Finish.

10
Running Your App
Before you run your app, you should be aware of a few directories and
files in the Android project:
AndroidManifest.xml
The manifest file describes the fundamental characteristics of the app
and defines each of its components. One of the most important
elements your manifest should include is the <uses-sdk> element. This
declares your app's compatibility with different Android versions. Set
the android:targetSdkVersion as high as possible and test your app on
the corresponding platform version. For your first app, it should look
like this:

11
src/Directory for your app's main source files. By default, it includes
an Activity class that runs when your app is launched using the app icon.
res/Contains several sub-directories for app resources. Here are just a few:
drawable-hdpi/Directory for drawable objects (such as bitmaps) that are
designed for high-density (hdpi) screens. Other drawable directories contain
assets designed for other screen densities.
layout/Directory for files that define your app's user interface.
values/Directory for other various XML files that contain a collection of
resources, such as string and color definitions.
When you build and run the default Android app, the default Activity class starts
and loads a layout file that says "Hello World.
Run on the Emulator
Run from the toolbar.
In the Run as window that appears, select Android Application and
click OK.
Eclipse installs the app on your AVD and starts it.



12
13

Building a Simple User Interface
Two common layout attributes
android:layout_width, android:layout_height
match_parent (fill up space in enclosing View)
wrap_content (use natural size)

Lets build a simple interface which need to look like
this:

14
The given layout is currently designed with
the EditText and Button widgets.
For the text field, because the user might type something longer. So, it
would be nice to fill the unused screen width with the text field. You
can do this inside a LinearLayout with the weight property, which you
can specify using the android:layout_weight attribute.
The default weight for all views is 0, so if you specify any weight value
greater than 0 to only one view, then that view fills whatever space
remains after all views are given the space they require. So, to fill the
remaining space in your layout with the EditText element, give it a
weight of 1 and leave the button with no weight.
In order to improve the layout efficiency when you specify the weight,
you should change the width of the EditText to be zero (0dp). Setting
the width to zero improves layout performance.
15
Heres a complete layout file should now look:
16
Respond to the Send Button
To respond to the button's on-click event, open
theactivity_main.xml layout file and add theandroid:onClick attribute
to the <Button> element:



The android:onClick attributes value, "sendMessage", is the name of a
method in your activity that the system calls when the user clicks the
button.

17
Open the MainActivity class (located in the project's src/ directory)
and add the corresponding method:




In order for the system to match this method to the method name
given to android:onClick, the signature must be exactly as shown.
Specifically, the method must:
o Be public
o Have a void return value
o Have a View as the only parameter (this will be the View that was
clicked)

18
Build an Intent
An Intent is an object that provides runtime binding between separate components (such as
two activities). The Intent represents an apps "intent to do something." You can use intents for
a wide variety of tasks, but most often theyre used to start another activity.
In order for the next activity to query the extra data, you should define the key for your intent's
extra using a public constant. So add the EXTRA_MESSAGE definition to the top of
the MainActivity class:





To start an activity, call startActivity() and pass it your Intent. The system receives
this call and starts an instance of the Activity specified by the Intent.




Create the DisplayMessageActivity class in order for this to work.

19
Create the Second Activity
Create a new file namedDisplayMessageActivity.java in the
project's src/ directory, next to the original MainActivity.java file.
Update your DisplayMessageActivity class with the below code:
20
Add the new activity's title to the strings.xml file:


All activities must be declared in your manifest
file, AndroidManifest.xml, using an <activity> element.
21
The complete onCreate() method
for DisplayMessageActivity now looks like this:







Run the app. When it opens, type a message in the
text field, click Send, and the message appears on the
second activity.
22
23
Image Button
24
25
Radio Button



CheckBox



26
Toggle Button
-- android:textOn, android:textOff
The text for the two states. If you omit this, then the text is automatically ON
and OFF (in caps)le Button.

27
28
29
Layout
A layout defines the visual structure for a user interface, such as the
UI for an activity .
Declare a layout in two ways:
1.Declare UI elements in XML.
Android provides a straightforward XML vocabulary that
corresponds to the View classes and subclasses, such as those for widgets and
layouts.
2.Instantiate layout elements at runtime.
Your application can create View and ViewGroup objects (and
manipulate their properties) programmatically.

30
Here we are going to declare a layout in XML:
It enables you to better separate the presentation of your application from the
code that controls its behavior.
UI descriptions are external to your application code, which means that you can
modify or adapt it without having to modify your source code and recompile.
Able to create XML layouts for different screen orientations, different device
screen sizes, and different languages.
It is easier to debug problems.
31
Some layouts are pre-defined by Android
Some of these are
LinearLayout
RelativeLayout
TableLayout
FrameLayout
AbsoluteLayout
A layout could be declared inside another layout
32
Linear Layout:
Dispose views on a single row or column, depending on
android:layout_orientation
Shows nested View elements
The orientation could also be declared via setOrientation(int
orientation)
orientation is one of HORIZONTAL or VERTICAL
Has two other attributes:
gravity
weight


33
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" > <!-- Also horizontal -->
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/buttonString1" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/buttonString2" />
</LinearLayout>
34
Orientation=vertical Orientation=horizontal
35
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/buttonString1" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="@string/buttonString2" />
</LinearLayout>
36
37
Relative Layout:
Disposes views according to the container or according to other views
The gravity attribute indicates what views are more important to define the
layout
Useful to align views
38
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent" >

<EditText
android:id="@+id/username" android:text="username"
android:inputType="text"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_toRightOf="@+id/usernameLabel" >
</EditText>

<TextView
android:id="@+id/usernameLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/username"
android:text="Username" />
39
<EditText
android:id="@+id/password" android:text="password"
android:inputType="textPassword"
android:layout_below="@+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/username"
android:layout_alignParentRight="true"
android:layout_toRightOf="@+id/usernameLabel" >
</EditText>

<TextView
android:id="@+id/passwordLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/password"
android:text="Password" />
</RelativeLayout>
40
Table Layout:
As the name say, similar to a Table
Has some attributes to customize the layout:
android:layout_column
android:layout_span
android:stretchColumns
android:shrinkColumns
android:collapseColumns
Each row is inside a <TableRow> element
41
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<TableRow>
<Button
android:id="@+id/backbutton"
android:text="Back"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow>
<TextView
android:text="First Name
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1" />
<EditText
android:width="100px
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow>
<TextView
android:text="Last Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1" />
<EditText
android:width="100px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
</TableLayout>
42
Frame Layout:
Display a single item at a time.
Can have multiple elements within a Frame Layout.
Elements that overlap will be displayed overlapping.
Adds an attribute, android:visibility
Makes the user able to define layouts managing the visibility of views
43
<FrameLayout
android:layout_width="fill_parent
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:src="@drawable/icon"
android:scaleType="fitCenter"
android:layout_height="fill_parent
android:layout_width="fill_parent"/>
<TextView
android:text="Learn-Android.com
android:textSize="24sp
android:textColor="#000000
android:layout_height="fill_parent
android:layout_width="fill_parent"
android:gravity="center"/>
</FrameLayout>
44
Absolute Layout:
Placing each control at an absolute position.
Specify the exact x and y coordinates on the screen for each
control.
Deprecated-since absolutely positioning every element on the
screen makes an inflexible UI that is much more difficult to
maintain.
Pay attention to different resolutions
45
<AbsoluteLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent
android:layout_height="fill_parent">
<Button
android:id="@+id/backbutton"
android:text="Back
android:layout_x="10px
android:layout_y="5px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_x="10px
android:layout_y="110px
android:text="First Name
android:layout_width="wrap_content
android:layout_height="wrap_content" />
<EditText
android:layout_x="150px
android:layout_y="100px
android:width="100px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_x="10px
android:layout_y="160px
android:text="Last Name
android:layout_width="wrap_content
android:layout_height="wrap_content" />
<EditText
android:layout_x="150px
android:layout_y="150px
android:width="100px
android:layout_width="wrap_content
android:layout_height="wrap_content" />
</AbsoluteLayout>
46
Adapters:
Used to visualize data
Make a ViewGroup to interact with data
Some methods:
isEmpty()
getItem(int position)
getCount()
getView()
Some subclasses:
ListView
GridView
Spinner
Gallery

47
ListView:
Displays a list of scrollable items.
The list items are automatically inserted to the list using an
Adapter that pulls content from a source such as an array or database
query and converts each item result into a view that's placed into the
list.
48
GridView:
Displays items in a two-dimensional, scrollable grid.
The grid items are automatically inserted to the layout using a
ListAdapter.
49
Using SQLite Database with Android
Android default Database engine is Lite.
SQLite is a lightweight transactional database engine that
occupies a small amount of disk storage and memory.
Things to consider when dealing with SQLite:
o Data type integrity is not maintained in SQLite, you can
put a value of a certain data type in a column of another
datatype (put string in an integer and vice versa).
o Referential integrity is not maintained in SQLite, there is
no FOREIGN KEY constraints or JOIN statements.
o SQLite Full Unicode support is optional and not installed
by default.


50
Lets create a simple database application to store
employees data. the DB has:
Tables
Employees
Dept
Views
ViewEmps: to display employees and their relative
departments.

51
Creating SQLite Database
By default, SQLite on Android does not have a
management interface or an application to create and
manage databases from, so we're going to create the
database ourselves by code. First, we will create a class that
handles all the operations required to deal with the
database such as creating the database, creating tables,
inserting and deleting records and so on. The first step is to
create a class that inherits from SQLiteOpenHelper class.
This class provides two methods to override to deal with
the database:
onCreate(SQLiteDatabase db): invoked when the database
is created, this is where we can create tables and columns to
them, create views or triggers.
onUpgrade(SQLiteDatabse db, int oldVersion, int
newVersion): invoked when we make a modification to the
database such as altering, dropping , creating new tables.

52
Our class will have the following members:





The Constructor: The constructor of the super class
has the following parameters:
Context , dataBaseName, CursorFactory, Version

53
Creating the Database
The method creates tables with columns, a view and a trigger. The method is
invoked when the database is created. So we create our table and specify the
columns. This method is invoked when the database does not exist on the disk,
its executed only once on the same device the first time the application is run
on the device.
54
Upgrading the Database
Managing Foreign-Key Constraints
UPDATE
Executing SQL Statements
You can execute any SQL statement that is not a query whether it
isinsert, delete, update or anything using db.execSQL(String
statement) method like when we did when creating the database tables:





55
Inserting Records




Notice that we need to call this.getWritableDatabase() to
open the connection with the database
forreading/writing. The ContentValues.put has two
parameters: Column Name and the value to be inserted.
Also, it is a good practice to close the database after
executing statements.
56
Updating Values
To execute an update statement, we have two ways:
To execute db.execSQL
To execute db.update method:





The update method has the following parameters:
String Table, ContentValues cv, String where clause, String[] args

57
Deleting Rows



The delete method has the same parameters as the update method.
Executing Queries



The rawQuery method has two parameters:
String query: The select statement
String[] selection args: The arguments if a WHERE clause is included
in the select statement

58
Another way to perform a query is to use a db.query method. A query to
select all employees in a certain department from a view would be like
this:




The db.query has the following parameters:
String Table Name: The name of the table to run the query against
String [ ] columns: The projection of the query, i.e., the columns to retrieve
String WHERE clause: where clause, if none pass null
String [ ] selection args: The parameters of the WHERE clause
String Group by: A string specifying group by clause
String Having: A string specifying HAVING clause
String Order By by: A string Order By by clause

59
Managing Cursors
Result sets of queries are returned in Cursor objects. There are some
common methods that you will use with cursors:
boolean moveToNext(): moves the cursor by one record in the
result set, returns false if moved past the last row in the result
set.
boolean moveToFirst(): moves the cursor to the first row in the
result set, returns false if the result set is empty.
boolean moveToPosition(int position): moves the cursor to a
certain row index within the boolean result set, returns false if
the position is un-reachable
boolean moveToPrevious(): moves the cursor to the previous row
in the result set, returns false if the cursor is past the first row.
boolean moveToLast(): moves the cursor to the lase row in the
result set, returns false if the result set is empty.

60
To check the position of a cursor: boolean
isAfterLast(), isBeforeFirst,isFirst, isLast and isNull(col
umnIndex).
Cursor.getColumnIndex(String ColumnName) to get
the index of a column.
To get the value of a certain column, we
have Cursor.getInt(int ColumnIndex) method.

Also there are getShort, getString, getDouble, getBlob to
return the value as a byte array. It's a good practice
to close() the cursor after using it.

61
To find this sqlite tutorial, the url is
http://www.codeproject.com/Articles/119293/Using-
SQLite-Database-with-Android

To download this sample application, you can find in
this url.

http://uploading.com/files/e67f2719/Database%2Bde
mo.rar/
62

Anda mungkin juga menyukai