Sie sind auf Seite 1von 40

TRAINING REPORT ON

ANDROID MOBILE OPERATING SYSTEM


Guided By
Mr. Raghvendra Sharma

Centre Director, Aptech Computer Education, Civil Lines, Sagar(M.P.)

Submitted By
Praveen vishwakarma
Enrollment No.

0601IT091041
In partial fulfillment of the award for the
Bachelor of Engineering
In
Information technology and Engineering
RAJEEV GANDHI PROUDYOGIKIVISHWAVIDYALAYA,
BHOPAL (M.P.)

Session- 2012

ACKNOWLEDGEMENT
There always remains a pleasure to acknowledge the assistance of several
individuals to the accomplishment of our goal and completion of the
training: Java Micro Edition- Android, that is commonly known as Java
Mobile Application Development.
My heartiest thanks extended to Mr.M.R. AHIRWAR, Head of the Department,
I.G.E.C. Sagar(M.P.). Last but not the least, we are thankful to the whole
computer science faculty, who directly or indirectly helped and advised us
at every step to complete this project work.
I also thank Aptech Computer Education, Sagar Faculty and staff for
providing with a helpful environment and support through the course of my
training.

Submitted By:
Praveen vishwakarma
Enrollment No.0601IT091041

Contents
1. Training Certificate
2. Acknowledgement
3. Company Profile
4. Day - wise Status of Training
5. Bibliography

COMPANY PROFILE
APTECH LIMITED
Aptech Limited, a Global Learning Solutions Company with a presence across 5 continents,
is playing a key role in helping individuals, organizations and nations adapt to the changing
requirements of a knowledge-driven world. Aptech commenced its IT education & training
business in 1986 and has trained over 4.5 million students globally.
Aptech is an ISO 9001:2000 organization and was the first IT training and education
organization in Asia to receive the ISO 9001 quality certification for Education Support Services in
1993.
Aptechs System Wide Revenue was in excess of Rs. 9226.70 million (208.75 Million USD)
in 2006. Aptech is listed on the Bombay Stock Exchange and National Stock Exchange, India.
BUSINESS LINES :
IT Education & Training

Animation & Multimedia Education & Training

Aptech Computer Education


:

Arena

Animation,

Maya

Certified Hardware & Networking Programs

N - Power

Aviation Training

Avalon Aviation Academy

Softskills

Offshore Content Development

Aptech Learning Services

e-learning

onlinevarsity.com

Aptech Training Solutions & ATTEST

Academy

English Express

Training & Assessment Solutions for


Corporate & Institutions

Day No.: 1 to 4

Date :

Topic - Introduction of java


1. Java Mobile Application Development
2. Java Micro Edition

Java Micro Edition


Advantages of JME
Java offers a number of advantages to developers.
1. Java is simple:

Java Mobile Applications

Java can be used to create two types of programs: applications and applets. An
application is a program that runs on your computer, under the operating system of that
computer. That is, an application created by Java is more or less like one created using C
or C++. When used to create applications, Java is not much different from any other
computer language. Rather, it is Javas ability to create applets that makes it important.
An applet is an application designed to be transmitted over the Internet and executed by
a Java-compatible Web browser. An applet is actually a tiny Java program, dynamically
downloaded across the network, just like an image, sound file, or video clip. The
important difference is that an applet is an intelligent program, not just an animation or
media file. In other words, an applet is a program that can react to user input and
dynamically changenot just run the same animation or sound over and over.
As exciting as applets are, they would be nothing more than wishful thinking if Java were
not able to address the two fundamental problems associated with them: security and
portability.

Eclipse
The NetBeans IDE is an open-source integrated development environment. NetBeans
IDE supports development of all Java application types (Java SE including JavaFX, (Java
ME, web, EJB and mobile applications) out of the box. Among other features are an Antbased project system, Maven support, refactoring, version control (supporting CVS,
Subversion, Mercurial and Clearcase).
Modularity: All the functions of the IDE are provided by modules. Each module provides
a well - defined function, such as support for the Java language, editing, or support for
the CVS versioning system, and SVN. NetBeans contains all the modules needed for Java
development in a single download, allowing the user to start working immediately.
Modules also allow NetBeans to be extended. New features, such as support for other
programming languages, can be added by installing additional modules. For instance,
Sun Studio, Sun Java Studio Enterprise, and Sun Java Studio Creator from Sun
Microsystems are all based on the NetBeans IDE.
5

License: From July 2006 through 2007, NetBeans IDE was licensed under Sun's Common
Development and Distribution License (CDDL), a license based on the Mozilla Public
License (MPL). In October 2007, Sun announced that NetBeans would henceforth be
offered under a dual license of the CDDL and the GPL version 2 licenses, with the GPL
linking exception for GNU Classpath.

Integrated modules
These modules are part of the NetBeans IDE.

NetBeans Profiler
The NetBeans Profiler is a tool for the monitoring of Java applications: It helps
developers find memory leaks and optimize speed. Formerly downloaded separately, it is
integrated into the core IDE since version 6.0.
The Profiler is based on a Sun Laboratories research project that was named JFluid. That
research uncovered specific techniques that can be used to lower the overhead of
profiling a Java application. One of those techniques is dynamic bytecode
instrumentation, which is particularly useful for profiling large Java applications. Using
dynamic bytecode instrumentation and additional algorithms, the NetBeans Profiler is
able to obtain runtime information on applications that are too large or complex for other
profilers. NetBeans also support Profiling Points that let you profile precise points of
execution and measure execution time.

GUI design tool


Formerly known as project Matisse, the GUI design-tool enables developers to prototype
and design Swing GUIs by dragging and positioning GUI components.The GUI builder also
has built-in support for JSR 296 (Swing Application Framework), and JSR 295 (Beans
Binding technology).

NetBeans JavaScript editor


The NetBeans JavaScript editor provides extended support for JavaScript, Ajax, and CSS.
JavaScript editor features comprise syntax highlighting, refactoring, code completion for
native objects and functions, generation of JavaScript class skeletons, generation of Ajax
callbacks from a template; and automatic browser compatibility checks.
CSS editor features comprise code completion for styles names, quick navigation through
the navigator panel, displaying the CSS rule declaration in a List View and file structure
in a Tree View, sorting the outline view by name, type or declaration order (List & Tree),
creating rule declarations (Tree only), refactoring a part of a rule name (Tree only).

Day No.: 5 to 10

Date :

Topic Introduction to Android


Android
Android applications are written in the Java programming language. The Android SDK tools compile the codealong
with any data and resource filesinto an Android package, an archive file with an .apksuffix. All the code in a
single .apk file is considered to be one application and is the file that Android-powered devices use to install the
application.
Once installed on a device, each Android application lives in its own security sandbox:

The Android operating system is a multi-user Linux system in which each


application is a different user.

By default, the system assigns each application a unique Linux user ID (the ID is
used only by the system and is unknown to the application). The system sets
permissions for all the files in an application so that only the user ID assigned to that
application can access them.

Each process has its own virtual machine (VM), so an application's code runs in
isolation from other applications.

By default, every application runs in its own Linux process. Android starts the
process when any of the application's components need to be executed, then shuts
down the process when it's no longer needed or when the system must recover
memory for other applications.
In this way, the Android system implements the principle of least privilege. That is, each
application, by default, has access only to the components that it requires to do its work
and no more. This creates a very secure environment in which an application cannot
access parts of the system for which it is not given permission.

However, there are ways for an application to share data with other applications and for
an application to access system services:
It's possible to arrange for two applications to share the same Linux user ID, in
which case they are able to access each other's files. To conserve system resources,
applications with the same user ID can also arrange to run in the same Linux process
and share the same VM (the applications must also be signed with the same
certificate).

An application can request permission to access device data such as the user's
contacts, SMS messages, the mountable storage (SD card), camera, Bluetooth, and
more. All application permissions must be granted by the user at install time.
That covers the basics regarding how an Android application exists within the system.
The rest of this document introduces you to:

The core framework components that define your application.

Application Components
7

Application components are the essential building blocks of an Android application. Each
component is a different point through which the system can enter your application. Not
all components are actual entry points for the user and some depend on each other, but
each one exists as its own entity and plays a specific roleeach one is a unique building
block that helps define your application's overall behavior.
There are four different types of application components. Each type serves a distinct
purpose and has a distinct lifecycle that defines how the component is created and
destroyed.
Here are the four types of application components:
Activities
An activity represents a single screen with a user interface. For example, an email
application might have one activity that shows a list of new emails, another
activity to compose an email, and another activity for reading emails. Although the
activities work together to form a cohesive user experience in the email
application, each one is independent of the others. As such, a different application
can start any one of these activities (if the email application allows it). For
example, a camera application can start the activity in the email application that
composes new mail, in order for the user to share a picture.
An activity is implemented as a subclass of Activity and you can learn more about
it in the Activities developer guide.
Services
A service is a component that runs in the background to perform long-running
operations or to perform work for remote processes. A service does not provide a
user interface. For example, a service might play music in the background while
the user is in a different application, or it might fetch data over the network
without blocking user interaction with an activity. Another component, such as an
activity, can start the service and let it run or bind to it in order to interact with it.
A service is implemented as a subclass of Serviceand you can learn more about it
in the Services developer guide.
Content providers
A content provider manages a shared set of application data. You can store the
data in the file system, an SQLite database, on the web, or any other persistent
storage location your application can access. Through the content provider, other
applications can query or even modify the data (if the content provider allows it).
For example, the Android system provides a content provider that manages the
user's contact information. As such, any application with the proper permissions
can query part of the content provider (such as ContactsContract.Data) to read
and write information about a particular person.
Content providers are also useful for reading and writing data that is private to
your application and not shared. For example, the Note Pad sample application
uses a content provider to save notes.
Broadcast receivers
8

A broadcast receiver is a component that responds to system-wide broadcast


announcements. Many broadcasts originate from the systemfor example, a
broadcast announcing that the screen has turned off, the battery is low, or a
picture was captured. Applications can also initiate broadcastsfor example, to let
other applications know that some data has been downloaded to the device and is
available for them to use. Although broadcast receivers don't display a user
interface, they may create a status bar notification
to alert the user when a broadcast event occurs. More commonly, though, a
broadcast receiver is just a "gateway" to other components and is intended to do a
very minimal amount of work. For instance, it might initiate a service to perform
some work based on the event.
A broadcast receiver is implemented as a subclass of BroadcastReceiver and
each broadcast is delivered as an Intent object. For more information, see
the BroadcastReceiver class.
A unique aspect of the Android system design is that any application can start another
applications component. For example, if you want the user to capture a photo with the
device camera, there's probably another application that does that and your application
can use it, instead of developing an activity to capture a photo yourself. You don't need
to incorporate or even link to the code from the camera application. Instead, you can
simply start the activity in the camera application that captures a photo. When complete,
the photo is even returned to your application so you can use it. To the user, it seems as
if the camera is actually a part of your application.
When the system starts a component, it starts the process for that application (if it's not
already running) and instantiates the classes needed for the component. For example, if
your application starts the activity in the camera application that captures a photo, that
activity runs in the process that belongs to the camera application, not in your
application's process. Therefore, unlike applications on most other systems, Android
applications don't have a single entry point (there's no main() function, for
example).Because the system runs each application in a separate process with file
permissions that restrict access to other applications, your application cannot directly
activate a component from another application. The Android system, however, can. So,
to activate a component in another application, you must deliver a message to the
system that specifies your intent to start a particular component. The system then
activates the component for you.
Activating Components
Three of the four component typesactivities, services, and broadcast receiversare
activated by an asynchronous message called an intent. Intents bind individual
components to each other at runtime (you can think of them as the messengers that
request an action from other components), whether the component belongs to your
application or another.
An intent is created with an Intent object, which defines a message to activate either a
specific component or a specific type of componentan intent can be either explicit or
implicit, respectively.
For activities and services, an intent defines the action to perform (for example, to "view"
or "send" something) and may specify the URI of the data to act on (among other things
9

that the component being started might need to know). For example, an intent might
convey a request for an activity to show an image or to open a web page. In some cases,
you can start an activity to receive a result, in which case, the activity also returns the
result in anIntent (for example, you can issue an intent to let the user pick a personal
contact and have it returned to youthe return intent includes a URI pointing to the
chosen contact).
For broadcast receivers, the intent simply defines the announcement being broadcast
(for example, a broadcast to indicate the device battery is low includes only a known
action string that indicates "battery is low").

The other component type, content provider, is not activated by intents. Rather, it
is activated when targeted by a request from a ContentResolver. The content
resolver handles all direct transactions with the content provider so that the
component that's performing transactions with the provider doesn't need to and
instead calls methods on the ContentResolver object. This leaves a layer of
abstraction between the content provider and the component requesting
information (for security).

There are separate methods for activating each type of component:

You can start an activity (or give it something new to do) by passing
an Intent to startActivity() orstartActivityForResult() (when you want the
activity to return a result).
You can start a service (or give new instructions to an ongoing service) by passing
an Intent tostartService(). Or you can bind to the service by passing
an Intent to bindService().
You
can
initiate
a
broadcast
by
passing
an Intent to
methods
like sendBroadcast(),sendOrderedBroadcast(), or sendStickyBroadcast().
You can perform a query to a content provider by calling query() on
a ContentResolver.

The Manifest File


Before the Android system can start an application component, the system must know
that the component exists by reading the application's AndroidManifest.xml file (the
"manifest" file). Your application must declare all its components in this file, which must
be at the root of the application project directory.The manifest does a number of things
in addition to declaring the application's components, such as:

Identify any user permissions the application requires, such as Internet access or
read-access to the user's contacts.
Declare the minimum API Level required by the application, based on which APIs
the application uses
Declare hardware and software features used or required by the application, such
as a camera, bluetooth services, or a multitouch screen.
API libraries the application needs to be linked against (other than the Android
framework APIs), such as theGoogle Maps library.
10

Declaring components
The primary task of the manifest is to inform the system about the application's
components. For example, a manifest file can declare an activity as follows:
<?xml version="1.0" encoding="utf-8"?>
<manifest ... >
<application android:icon="@drawable/app_icon.png" ... >
<activity android:name="com.example.project.ExampleActivity"
android:label="@string/example_label" ... >
</activity>

...</application>

</manifest>

In the <application> element, the android:icon attribute points to resources for an


icon
that
identifies
the
application.In
the <activity> element,
the android:name attribute
specifies
the
fully
qualified
class
name
of
theActivity subclass and the android:label attributes specifies a string to use as the
user-visible label for the activity. You must declare all application components this way:

<activity> elements for activities


<service> elements for services
<receiver> elements for broadcast receivers
<provider> elements for content providers

11

Day No.: 11 to 16

Date :

Topic User Interface Layout


User Interface Layout
The user interface for each component of your app is defined using a hierarchy
of View and ViewGroup objects, as shown in figure 1. Each view group is an invisible
container that organizes child views, while the child views may be input controls or other
widgets that draw some part of the UI. This hierarchy tree can be as simple or complex
as you need it to be (but simplicity is best for performance).

Figure 1. Illustration of a view hierarchy, which defines a UI layout.


To declare your layout, you can instantiate View objects in code and start building a tree,
but the easiest and most effective way to define your layout is with an XML file. XML
offers a human-readable structure for the layout, similar to HTML.
The name of an XML element for a view is respective to the Android class it represents.
So a <TextView>element creates a TextView widget in your UI, and
a <LinearLayout> element creates a LinearLayout view group.
For example, a simple vertical layout with a text view and a button looks like this:
<?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" >
12

<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a TextView" />
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a Button" />
</LinearLayout>
When you load a layout resource in your app, Android initializes each node of the layout
into a runtime object you can use to define additional behaviors, query the object state,
or modify the layout.\

Android widget

AnalogClock
<AnalogClock
id="@+id/clock1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
Button
<Button id ="@+id/button1"
android:text="Label"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
<Button id ="@+id/button2"
android:text="Label"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:typeface="serif"
/>
<Button id ="@+id/button3"
13

android:text="Label"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textStyle="bold_italic"
/>
CheckBox
<CheckBox id="@+id/plain_cb"
android:text="Plain"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<CheckBox id="@+id/serif_cb"
android:text="Serif"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:typeface="serif"
/>
<CheckBox id="@+id/bold_cb"
android:text="Bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
/>
<CheckBox id ="@+id/italic_cb"
android:text="Italic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="italic"
/>
DatePicker
<DatePicker
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
...
// Required Java init code:
DatePicker dp =
(DatePicker)this.findViewById(R.id.widget27);
// for example init to 1/27/2008, no callback
dp.init(2008, 0, 27, Calendar.SUNDAY, null);
...
DigitalClock
<DigitalClock id="@+id/digitalclock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
EditText

14

<EditText id ="@+id/edittext1"
android:text="EditText 1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<EditText id ="@+id/button2"
android:text="(206)555-1212"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:typeface="serif"
android:phoneNumber="true"
/>
<EditText id ="@+id/password"
android:text="SuperSecret"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold_italic"
android:password="true"
/>
Gallery
<Gallery
id="@+id/gallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
ImageButton
<ImageButton id="@+id/imagebutton"
android:src="@drawable/brush"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
ImageView
<ImageView id="@+id/imagebutton"
android:src="@drawable/brush"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
ProgressBar
<ProgressBar id="@+id/progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
RadioButton
<RadioGroup
id="@+id/widget1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/re
s/android"
android:orientation="vertical"
>
<RadioButton
15

id="@+id/widget2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Plain"
android:checked="false"
android:layout_gravity="left"
android:layout_weight="0"
>
</RadioButton>
<RadioButton
id="@+id/widget3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Serif"
android:checked="true"
android:layout_gravity="left"
android:layout_weight="0"
android:typeface="serif"
>
</RadioButton>
<RadioButton
id="@+id/widget25"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bold"
android:checked="false"
android:layout_weight="0"
android:layout_gravity="left"
android:textStyle="bold"
>
</RadioButton>
<RadioButton
id="@+id/widget24"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bold & Italic"
android:checked="false"
android:layout_weight="0"
android:layout_gravity="left"
android:textStyle="bold_italic"
>
</RadioButton>
</RadioGroup>
Spinner
<Spinner
id="@+id/widget1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="false"/>
16

TextView
<TextView id="@+id/plain"
android:text="Plain"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView id="@+id/serif"
android:text="Serif"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:typeface="serif"
/>
<TextView id="@+id/bold"
android:text="Bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
/>
<TextView id ="@+id/italic"
android:text="Italic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="italic"
/>
TimePicker
<TimePicker
id="@+id/widget3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

Day No.: 17to 22

Date :

Topic Android Gallery view


Android Gallery view
Continuing on the Views, I have taken up the Gallery View that helps in showing Images
as in a gallery. As per the android documentation, this is the definition: A Gallery is a
View commonly used to display items in a horizontally scrolling list that locks the current
selection at the center.
For this the layout xml in this case, the main.xml will have a Gallery element as shown
below:
<Gallery
17

android:id="@+id/Gallery01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"></Gallery>
<ImageView android:id="@+id/ImageView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></ImageView>
It also has an ImageView element which is used to show the selected Image in a larger
ImageView. Here is how it would look when executed

Create an array of these resources/images in the activity with the following code:
Integer[]
pics
=
{
R.drawable.antartica1,
R.drawable.antartica2;
R.drawable.antartica3
R.drawable.antartica4,
R.drawable.antartica5,
R.drawable.antartica6,
R.drawable.antartica7,
R.drawable.antartica8,
R.drawable.antartica9,
R.drawable.antartica10
};
As we have seen with all the other views so far, we need to have an adapter that
associates the view with the data. Here the view is Gallery and the data is the above
mentioned 10 images. An Adapter plays the role of linking the two as shown below:
Gallery
ga=(Gallery)findViewById(R.id.Gallery01);
ga.setAdapter(newImageAdapter(this));
However, we do not have a readymade implementation of the ImageAdapter. We have to
create our own implementation of the same by extending the BaseAdapter class. This is
the core of the code in this example. The moment we extend the BaseAdapter, we have
to override 4 methods. They
18

aregetCount(), getItem(),getItemId() and getView().


Before we go to each of them, let us see the constructor of the ImageAdpater:
public
class ImageAdapter
extends
BaseAdapter
{
private
Context
ctx;
int
imageBackground;
public
ImageAdapter(Context c)
{
ctx
=c;
TypedArray
ta
=
obtainStyledAttributes(R.styleable.Gallery1);
imageBackground
=
ta.getResourceId(R.styleable.Gallery1_android_galleryItemBackground,
1);
ta.recycle();
}
}
It takes the context that is passed to the constructor. We need to examine this code a
little. First, we can define our own resources or attributes in an XML file. Those attributes
can be retrieved through the methodobtainStyledAttributes. This is a method on
the Context object. The returned value needs to be stored in a TypedArray object.
A TypedArray is nothing but a container for an array of values that are returned
by obtainStyledAttributes.
So, in my example, I have created an xml file by name attributes.xml in
the res/values folder with the following content:
<resources>
<declare-styleable name="Gallery1">
<attr name="android:galleryItemBackground"/>
</declare-styleable>
</resources>
Here Gallery1 is a custom name for a style defined by us. In this style, we are trying to
say what should be the background of our images. For that we are using a pre-defined
backgournd in R.attr class asgalleryItemBackground.
So, this is accessed in the ImageAdapter contructor through the line
ta.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 1);
ta.recycle();
The number 1 is to say that it is the first element in the attributes.xml file under the
styelableGallery1.
The rest of the over ridden methods are simple:
@Override
public int getCount() {
return pics.length;
}
@Override
public Object getItem(int arg0) {
return arg0;
}
@Override
public long getItemId(int arg0) {
return arg0;
}@Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
ImageView iv = new ImageView(ctx);
19

iv.setImageResource(pics[arg0]);
iv.setScaleType(ImageView.ScaleType.FIT_XY);
iv.setLayoutParams(new Gallery.LayoutParams(150,120));
iv.setBackgroundResource(imageBackground)
return iv;}
The getView actually returns a View object when called. Here it is overridden it to return
a ImageViewobject with the selected image inside it alosn with some scale, layout
paramaters and the image background set.
Finally in the onCreate() method of the activity I have captured the onClick event on a
Gallery item and within that I have toasted a message as well as displayed the image in
a bigger manner below the gallery:
ga.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(getBaseContext(), "You have selected picture " + (arg2+1) + " of
Antartica",
Toast.LENGTH_SHORT).show();
imageView.setImageResource(pics[arg2]);
}
});

20

Day No.: 21 to 24

Date :

Android List View


The display of elements in a lists is a very common pattern in mobile applications. The
user sees a list of items and can scroll through them. If he selects one item, this can
update the ActionBar or triggers a detailed screen for the selection.Android provides
the ListView class which is capable of displaying a scrollable list of items. These items
can be of any type.
For example the following listing shows a layout file with includes a ListView.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="@+id/mylist"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>

Adapters and default implementations


A ListView receives its data via an adapter. The adapter also defines how each row is
the ListView is displayed.
The adapter is assigned to the list via the setAdapter method on the ListView object.
An adapter extend the BaseAdapter class. Android provides several standard adapters;
the most important areArrayAdapter and CursorAdapter.
ArrayAdapter

can handle data based on Arrays or java.util.List.

can handle database related data. This description focuses on the


non database case.The Android platform provides default layouts for rows in ListViews.
For
exampleandroid.R.layout.simple_list_item1.
By
default ArrayAdapter uses
the android.R.id.text1 ID, but you can define another one in the ArrayAdapter constructor.
21
SimpleCursorAdapter

The following coding shows an example of the usage of the ArrayAdapter class and a
predefined layout from the Android system. The example assumes that layout of
the Activity contains a ListView with the mylist ID.
ListView listView = (ListView) findViewById(R.id.mylist);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
// First paramenter - Context
// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is written
// Forth - the Array of data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);

Input for ArrayAdapter


The ArrayAdapter class can handle any Java object as input. It maps the data of this input to a TextView in the
layout. You can define one in the constructor otherwise the android.R.id.text1 ID will be used.
ArrayAdapter uses the toString() method of the data input object to determine the String
which should be displayed.

Add and remove data in the Adapter


The ArrayAdapter class allows to remove all elements in its underlying data structure with the clear() method
call. You can then add new elements via the add() method or a Collection via the addAll() method.

Listener

To react to selections in the list set an OnItemClickListener to your ListView.


listView.setOnItemClickListener(new OnItemClickListener() {
publicvoid onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"Click ListItem Number " + position, Toast.LENGTH_LONG)
.show(); } });

Filtering and Sorting


Filtering and sorting is handled by the Adapter. You need to implement the logic in your custom Adapter
implementation.

Own Adapters
To control the data assignment and to support this assignment to several Views, you create your
own Adapterimplementation. For this you would extend an existing adapter implementations or by sub-classing
the BaseAdapterclass directly.ListView calls the getView() method on the adapter for each data
22

element. In this method the adapter determines the layout of the row and how the data
is mapped to the Views in this layout.This root of the layout is typically
a ViewGroup (LayoutManager) and contains several other Views, e.g. anImageView and
a TextView.

Within the getView() method you would inflate an XML based layout and then set the
values of the individual Views in the layout. For inflating an XML layout you can use the
system service LayoutInflator. This service can get accessed via the Activity or via
thecontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE) method call.The individual
elements in the layout can be found via the findViewById() method call. The following
shows an implementation of an own adapter. This adapter assumes that you have two
png files (no.png and yes.png) in one of your res/drawable folders. The coding inflates an
XML layout file, finds the relevant Views in the layout and sets their content based on
the input data.

23

Package praveen;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MySimpleArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public MySimpleArrayAdapter(Context context, String[] values) {
super(context, R.layout.rowlayout, values);
this.context = context;
this.values = values;
}@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.rowlayout, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.label);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
textView.setText(values[position]);
// Change the icon for Windows and iPhone
String s = values[position];
if (s.startsWith("iPhone")) {
imageView.setImageResource(R.drawable.no);
} else {
imageView.setImageResource(R.drawable.ok); }
return rowView; } }
Your row layout can also contain Views which interact with the underlying data model via the adapter. For
example you can have a Checkbox in your row layout and if the Checkbox is selected, the underlying
data is changed.

24

ListActivity
Overview
The ListActivity class which extends the Activity class was designed to simplify the handling of ListViews.If it
is not assigned a layout to a ListActivity it contains a default ListView and defines
theonListItemClick() method for handling selection of list items. Internally the ListActivity registers
anOnItemClickListener on the ListView. ListActivity allows to set the adapter to the ListView via
the setListAdapter() method.
packageanmol.a;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public cclass MyListActivity extends ListActivity {
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);}}

ListActivity and Layout


ListActivity does
not
require
that
you
assign
a
layout
to
it
via
the setContentView() method, if you only want to show a ListView ListActivity contains
by default a ListView.In case you need to include more Views than a ListView in
your ListActivity you can still assign a layout to yourActivity. In this case your
layout must contain a ListView with the android:id attribute set to@android:id/list.
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"></ListView>

Day No.: 25 to 28

Date :

25

Topic Android Grid View

Android Grid View


Android Layout file res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridView1"
android:numColumns="auto_fit"
android:gravity="center"
android:columnWidth="50dp"
android:stretchMode="columnWidth"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</GridView>

Activity
package com.mkyong.android;
import android.app.Activity;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View;
26

import android.widget.AdapterView.OnItemClickListener;
publicclass GridViewActivity extends Activity {
GridView gridView;
staticfinal String[] numbers = new String[] {
"A", "B", "C", "D", "E",
"F", "G", "H", "I", "J",
"K", "L", "M", "N", "O",
"P", "Q", "R", "S", "T"};
publicvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gridView = (GridView) findViewById(R.id.gridView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, numbers);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new OnItemClickListener() {
publicvoid onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(getApplicationContext(),((TextView) v).getText(), Toast.LENGTH_SHORT).
} } );
}
}

27

Demo

Androd Intent
Intents are asynchronous messages which allow Android components to request
functionality from other components of the Android system. For example
an Activity can send an Intents to the Android system which starts anotherActivity.
Therefore Intents allow to combine loosely coupled components to perform certain
tasks. Intents can be used to signal to the Android system that a certain event has
occurred. Other components in Android can register to this event and will get notified.
Intents are instances of the android.content.Intent class. Intents are send to the
Android system. Depending on how the Intent was constructed the Android system will
run an receiver determination and determine what to do. An Intent can also contain
data. This data can be used by the receiving component. For example your application
can calls via an Intent a browser component. As data it may send the URL to the
browser component. Android supports explicit and implicit Intents.

Explicit Intents
Explicit Intents explicitly defines the component which should be called by the Android
system, by using the Java class as identifier.The following shows an explicit Intent. If
that Intent is correctly send to the Android system and the class is accessible, it will
start the associated class.
Intent i = newIntent(this, ActivityTwo.class);
i.putExtra("Value1", "This value one for ActivityTwo ");
i.putExtra("Value2", "This value two ActivityTwo");
Explicit Intents are typically used within on application as the classes in an application
are controlled by the application developer.

28

Implicit Intents
Implicit Intents do not directly specify the Android components which should be called.
They specify the action which should be performed and optionally an URI which should
be used for this action.For example the following tells the Android system to view a
webpage. Typically the web browser is registered to thisIntent but other component
could also register themself to this event.
Intent intent = newIntent(Intent.ACTION_VIEW, Uri.parse("http://www.vogella.com"));
If these Intents are send to the Android system it searches for all components which are
registered for the specific action and the data type.If only one component is found,
Android starts this component directly. If several components are identifier by the
Android system, the user will get an selection dialog and can decide which component
should be used for the Intent.

Data Transfer
An implicit Intent contains the Action and optional the URI. The receiving component
can get this information via thegetAction() and getData() methods.
Explicit and implicit Intents can also contain additional data. This data call be filled by
the component which creates theIntent. It can and can get extracted by the
component which receives the Intent.The component which creates the Intent can add
data to it via the overloaded putExtra() method. Extras are key/value pairs; the key is
always a String. As value you can use the primitive data types (int, float,..), String,
Bundle, Parceable and Serializable. For example you can trigger all components which
have
been
registered
to
send
some
data
via
the new
Intent(Intent.ACTION_SEND) This Intent determines possible receivers via the type.
What is send it defined via the putExtra method. You can use any String as key, the
following uses the keys which are predefined for the ACTION_SEND intent.
Intent intent = newIntent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "News for you!");
startActivity(intent);
The component which receives the Intent can use the getIntent().getExtras() method
call to get the extra data.
Bundle extras = getIntent().getExtras();
if (extras == null) {
return;

// Get data via the key


String value1 = extras.getString(Intent.EXTRA_TEXT);
if (value1 != null) {
29

// Do something with the data }


Using Intents to call Activities
Calling Activities
If you send an Intent to the Android system, Android requires that you tell it to which
type of component your Intentshould be send.To start an Activity use the
method startActivity(Intent). This method is defined on the Context object and
available
in
every Activity object.
If
you
call
an Activity with
the startActivity(Intent) method the caller requires no result from the calledActivity.
Calling Sub-Activities for result data
If
you
need
some
information
the startActivityForResult() method.

from

the

publicvoid onClick(View view) {


Intent i = newIntent(this, ActivityTwo.class);
i.putExtra("Value1", "This value one for ActivityTwo ");
i.putExtra("Value2", "This value two ActivityTwo");
// Set the request code to any code you like, you can identify the
// callback via this code
startActivityForResult(i, REQUEST_CODE);
}

Day No.: 29 to 36

Date :

30

called Activity use

Topic : SQLite and Android


What is SQLite?
SQLite is an Open Source Database which is embedded into Android. SQLite supports
standard relational database features like SQL syntax, transactions and prepared
statements. In addition it requires only little memory at runtime (approx. 250 KByte).
SQLite supports the data types TEXT (similar to String in Java), INTEGER (similar to long
in Java) and REAL (similar to double in Java). All other types must be converted into one
of these fields before saving them in the database. SQLite itself does not validate if
the types written to the columns are actually of the defined type, e.g. you can write an
integer into a string column and vice versa.

SQLite in Android
SQLite is available on every Android device. Using an SQLite database in Android does
not require any database setup or administration.
You only have to define the SQL statements for creating and updating the database.
Afterwards the database is automatically managed for you by the Android platform.
Access to an SQLite database involves accessing the filesystem. This can be slow.
Therefore it is recommended to perform database operations asynchronously, for
example inside the AsyncTask class.
If your application creates a database, this database is by default saved in the
directoryDATA/data/APP_NAME/databases/FILENAME.
The parts of the above directory are constructed based on the following rules. DATA is
the path which theEnvironment.getDataDirectory() method returns. APP_NAME is your
application name. FILENAME is the name you specify in your application code for the
database.

SQLite Architecture
Packages
The package android.database contains all general classes for working
databases.android.database.sqlite contains the SQLite specific classes.
31

with

SQLiteOpenHelper
To create and upgra de a database in your Android application you usually
subclass SQLiteOpenHelper. In the constructor of your subclass you call
the super() method of SQLiteOpenHelper, specifying the database name and the
current database version.
In this class you need to override the onCreate() and onUpgrade() methods.
onCreate() is called by the framework, if the database does not exists.onUpgrade() is
called, if the database version is increased in your application code. This method
allows you to update the database schema. Both methods receive
an SQLiteDatabase object as parameter which represents the database.
SQLiteOpenHelper provides the
methods getReadableDatabase() and getWriteableDatabase() to get access to
an SQLiteDatabase object; either in read or write mode.
The database tables should use the identifier _id for the primary key of the table.
Several Android functions rely on this standard. It is best practice to create a separate
class per table. This class defines static onCreate() and onUpdate()methods. These
methods are called in the corresponding methods of SQLiteOpenHelper. This way your
implementation of SQLiteOpenHelper will stay readable, even if you have several
tables.

SQLiteDatabase
SQLiteDatabase is the base class for working with a SQLite database in Android and
provides methods to open, query, update and close the database.
More specifically SQLiteDatabase provides the insert(), update() and delete() methods.
In addition it provides the execSQL() method, which allows to execute an SQL
statement directly. The object ContentValues allows to define key/values. The "key"
represents the table column identifier and the "value" represents the content for the
table record in this column. ContentValues can be used for inserts and updates of
database entries. Queries can be created via the rawQuery() and query() methods or
via the SQLiteQueryBuilder class . rawQuery() directly accepts an SQL select statement
as input.
query() provides a structured interface for specifying the SQL query.
SQLiteQueryBuilder is a convenience class that helps to build SQL queries.

rawQuery() Example

The following gives an example of a rawQuery() call.


Cursor cursor = getReadableDatabase().
rawQuery("select * from todo where _id = ?", new String[] { id });

query() Example
The following gives an example of a query() call.
return database.query(DATABASE_TABLE,

32

new String[] { KEY_ROWID, KEY_CATEGORY, KEY_SUMMARY, KEY_DESCRIPTION },


null, null, null, null, null);

The method query() has the following parameters.


Table 1. Parameters of the query() method
Parameter

Comment

String dbName

The table name to compile the query against.

int[] columnNames

A list of which table columns to return. Passing "null" will return all columns.

String whereClause

Where-clause, i.e. filter for the selection of data, null will select all data.

String[] selectionArgs

You may include ?s in the "whereClause"". These placeholders will get replaced by the values
from the selectionArgs array.

String[] groupBy

A filter declaring how to group rows, null will cause the rows to not be grouped.

String[] having

Filter for the groups, null means no filter.

String[] orderBy

Table columns which will be used to order the data, null means no ordering.

If a condition is not required you can pass null, e.g. for the group by clause.
The "whereClause" is specified without the word "where", for example a "where"
statement might look like: "_id=19 and summary=?".
If you specify placeholder values in the where clause via ?, you pass them as the
selectionArgs parameter to the query.

Cursor
A query returns a Cursor object. A Cursor represents the result of a query and basically
points to one row of the query result. This way Android can buffer the query results
efficiently; as it does not have to load all data into memory.To get the number of
elements of the resulting query use the getCount() method. To move between individual
data
rows,
you
can
use
the moveToFirst() and moveToNext() methods.
TheisAfterLast() method allows to check if the end of the query result has been reached.
Cursor provides typed get*() methods, e.g. getLong(columnIndex), getString(columnIndex) to
access the column data for the current position of the result. The "columnIndex" is the
33

number
of
the
column
you
are
accessing.
Cursor also
provides
the getColumnIndexOrThrow(String) method which allows to get the column index for a
column name of the table. A Cursor needs to be closed with the close() method call.

ListViews, ListActivities and SimpleCursorAdapter


ListViews are Views which allow to display a list of elements.
ListActivities are
specialized Activities which make the usage of ListViews easier. To work with
databases
and ListViews you
can
use
the SimpleCursorAdapter.
The SimpleCursorAdapterallows to set a layout for each row of the ListViews. You also
define an array which contains the column names and another array which contains
the IDs of Views which should be filled with the data. The SimpleCursorAdapter class
will map the columns to the Views based on the Cursor passed to it. To obtain
the Cursor you should use the Loader class.

Simple SQLite Example

package com.exercise.AndroidSQLite;
mport android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
public class SQLiteAdapter {
public static final String MYDATABASE_NAME = "MY_DATABASE";
public static final String MYDATABASE_TABLE = "MY_TABLE";
public static final int MYDATABASE_VERSION = 1;
public static final String KEY_ID = "_id";
public static final String KEY_CONTENT = "Content";
//create table MY_DATABASE (ID integer primary key, Content text not null);
private static final String SCRIPT_CREATE_DATABASE =
"create table " + MYDATABASE_TABLE + " ("
+ KEY_ID + " integer primary key autoincrement, "
34

+ KEY_CONTENT + " text not null);";


private SQLiteHelper sqLiteHelper;
private SQLiteDatabase sqLiteDatabase;
private Context context;
public SQLiteAdapter(Context c){
context = c;}
public SQLiteAdapter openToRead() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null,
MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getReadableDatabase();
return this;}
public SQLiteAdapter openToWrite() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null,
MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
return this;}
public void close(){
sqLiteHelper.close();
}
public long insert(String content){
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_CONTENT, content);
return sqLiteDatabase.insert(MYDATABASE_TABLE, null, contentValues);}
public int deleteAll(){
return sqLiteDatabase.delete(MYDATABASE_TABLE, null, null);
}
public Cursor queueAll(){
String[] columns = new String[]{KEY_ID, KEY_CONTENT};
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,
null, null, null, null, null);
return cursor;
}
public class SQLiteHelper extends SQLiteOpenHelper {
public SQLiteHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(SCRIPT_CREATE_DATABASE);}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub } } }

Create /res/layout/row.xml for our ListView


<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"/>
35

Modify main.xml to change the result(contentlist) from TextView to ListView.


<?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"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<ListView
android:id="@+id/contentlist"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
Finally, modify AndroidSQLite.java
package com.exercise.AndroidSQLite;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class AndroidSQLite extends Activity {
private SQLiteAdapter mySQLiteAdapter;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView listContent = (ListView)findViewById(R.id.contentlist);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
mySQLiteAdapter.deleteAll();
mySQLiteAdapter.insert("A for Apply");
mySQLiteAdapter.insert("B for Boy");
mySQLiteAdapter.insert("C for Cat");
mySQLiteAdapter.insert("D for Dog");
mySQLiteAdapter.insert("E for Egg");
mySQLiteAdapter.insert("F for Fish");
mySQLiteAdapter.insert("G for Girl");
mySQLiteAdapter.insert("H for Hand");
mySQLiteAdapter.insert("I for Ice-scream");
mySQLiteAdapter.close();
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToRead();
Cursor cursor = mySQLiteAdapter.queueAll();
startManagingCursor(cursor);
String[] from = new String[]{SQLiteAdapter.KEY_CONTENT};
36

int[] to = new int[]{R.id.text};


SimpleCursorAdapter cursorAdapter =
new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
listContent.setAdapter(cursorAdapter);
mySQLiteAdapter.close();
}
}

Day No.: 37 to 42

Date :

Topic : Android webservices


Android Webservice
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class AndroidWebService extends Activity {
private final String NAMESPACE = "http://www.webserviceX.NET/";
private final String URL = "http://www.webservicex.net/ConvertWeight.asmx";
private final String SOAP_ACTION = "http://www.webserviceX.NET/ConvertWeight";
private final String METHOD_NAME = "ConvertWeight";
37

/** Called when the activity is first created. */


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
String weight = "3700";
String fromUnit = "Grams";
String toUnit = "Kilograms";
PropertyInfo weightProp =new PropertyInfo();
weightProp.setName("Weight");
weightProp.setValue(weight);
weightProp.setType(double.class);
request.addProperty(weightProp);
PropertyInfo fromProp =new PropertyInfo();
fromProp.setName("FromUnit");
fromProp.setValue(fromUnit);
fromProp.setType(String.class);
request.addProperty(fromProp);
PropertyInfo toProp =new PropertyInfo();
toProp.setName("ToUnit");
toProp.setValue(toUnit);
toProp.setType(String.class);
request.addProperty(toProp);
SoapSerializationEnvelope envelope = new
SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
Log.i("myApp", response.toString());
TextView tv = new TextView(this);
tv.setText(weight+" "+fromUnit+" equal "+response.toString()+ " "+toUnit);
setContentView(tv);
} catch (Exception e) {
e.printStackTrace();
} }
}
You have to add INTERNET permission to AndroidManifest.xml as follows;
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sencide"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
38

<activity android:name=".AndroidWebService"
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>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>

39

Day No.: 42 to 45

Date :

Assignment : Android Project

40

Das könnte Ihnen auch gefallen