Você está na página 1de 72

Two Day Workshop on Android

ANDROID:

13/03/2014

Two Day Workshop on Android


What is Android?
Android Is a mobile Operating System developed by Google.
Android Os is based on open Linux kernal.
Unlike iPhone Os, Android Os is Open source, meaning the developers can modify and customize
the os for each phone.
Developers can create programs for Android by using the Android SDK(Software Development
Kit).
Android programs are written in java and run through Googles Davlik virtual machine, which
optimized for mobile devices.
Android Architecture :

The Main Components in the Android Architecture are


1. Android Application
2. Application Framework

13/03/2014

Two Day Workshop on Android


3. Libraries(Core & Native)
4. Runtime Android (DVM- Dalvik Virtual Machine)
5. Kernel Linux
1. Android Applications:

These are applications written in Java. Some of basic applications

includes an calendar, email client, SMS program, maps, making phone calls, accessing the Web
browser, accessing your contacts list and others.
2. Application FrameWork:

This is the skeleton or framework which all android developers has

to follow. The developers can access all framework APIs an manage phones basic functions like
resource allocation, switching between processes or programs, telephone applications, and
keeping track of the phones physical location.
3.

Libraries:

a. Core Libraries: The Android runtime layer which includes set of core java

libraries and DVM (Dalvik Virtual Machine) is also located in same layer.
b. Native Libraries: This layer consists of Android libraries written in C, C++, and used by various
system. These libraries tells the device how to handle different kinds of data and are exposed to Android
developers via Android Application framework. Some of these libraries includes media , graphics,
3d,SQLite,web browser library etc.

4. Runtime Android (Dalvik virtual Machine):

This layer includes set of base libraries that are

required for java libraries. Every Android application gets its own instance of Dalvik virtual machine.
Dalvik has been written so that a device can run multiple VMs efficiently and it executes files in
executable (.Dex) optimized for minimum memory.

13/03/2014

Two Day Workshop on Android


5. Kernel Linux:

This layer includes Androids memory management programs, security settings,

power management software and several drivers for hardware , file system access, networking and interprocess-communication. The kernel also acts as an abstraction layer between hardware and the rest of
the software stack.
Android Versions:

Android 1.0 (API level 1)

Android
2.3.32.3.7 Gingerbread (API level 10)
First
Major version of Android is 1.5 (CupCake)
may 2009

Android 1.1 (API level 2)

Android 3.0 Honeycomb (API level 11)

Android 1.5 Cupcake (API level 3)

Android 3.1 Honeycomb (API level 12)

Android 1.6 Donut (API level 4)

Android 3.2 Honeycomb (API level 13)

Android 2.0 Eclair (API level 5)

Android 4.04.0.2 Ice Cream Sandwich (API level 14)

Android 4.0.34.0.4 Ice Cream Sandwich (API level 15)

Android 1.6 (Donut)


Android 2.1(clair)

Android 2.2(Froyo)

2.3,2.3.2,2.3.3,.(GingarBread)
Android
Android 2.0.1
Eclair (API level 6)

Android
Android 2.13.1,3.2,3.2.1,3.2.2,3.2.3.(HoneyComb)
Eclair (API level 7)

Android 4.1 Jelly Bean (API level 16)

Android 2.22.2.3
Froyo
(API level
8)
Android
4.0(ice
Cream
Sandwitch)

Android 4.2 Jelly Bean (API level 17)

Android 2.32.3.2 Gingerbread (API level 9)

Android 4.3 Jelly Bean (API level 18)

Android 2.3.32.3.7 Gingerbread (API level 10)

Android 4.4 KitKat (API level 19)

2.11 Android 3.0 Honeycomb (API level 11)

Android
Features:
2.12
Android 3.1 Honeycomb (API level 12)

2.13 Android 3.2 Honeycomb (API level 13)

2.14 Android 4.04.0.2 Ice Cream Sandwich (API

The following are the advantages of Android


14)
level
Application
framework enabling reuse and replacement of components

2.15 Android 4.0.34.0.4 Ice Cream Sandwich (API

level
Dalvik
15) virtual machine optimized for mobile devices

2.16 Android 4.1 Jelly Bean (API level 16)

2.17 Android 4.2 Jelly Bean (API level 17)

2.18 Android 4.3 Jelly Bean (API level 18)

2.19 Android 4.4 KitKat (API level 19)

Optimized graphics

SQLite for structured data storage

Media support for common audio, video, and still image formats (MPEG4, H.264, MP3, AAC,
AMR, JPG, PNG, GIF)

13/03/2014

Two Day Workshop on Android


GSM Telephony (hardware dependent),Bluetooth, EDGE, 3G, and WiFi (hardware
dependent),Camera, GPS, compass, and accelerometer (hardware dependent)
Rich development environment

To Create , Test and build Android applications we need the following Softwares:
1. Eclipse IDE (is optional can use any other tool. But Eclipse is recommended ) + added with
Android Development plugin
2. Android SDK(Software Development Kit
we can download these s/w from this site http://www.android.com
Required Softwares:
The android app can be developed on any OS such as Windows, Linux, and MAC Os
The following are the resources that are required to set up into the system for android application
development
1. An IDE (Integrated Development Environment) : The Eclipse is the most prefered IDE. We can
download the Eclipse IDE from
the following website.

http://www.eclipse.org

2. Add a plugin making the eclipse aware of Android.


The Android Development Tool(ADT) is the Eclipse plugin doing this. For this we want to use the
Install plugin option of the Eclipse IDE.

13/03/2014

Two Day Workshop on Android


Alternatively we can get the ADT zip file downloaded from http://www.android.com and
manually copy the features and plugins folders into the eclipse root folder , which we got
extracting the ADT zip file.
3. In addition to the IDE and its plugin simplifying creating the android applications we want
to have an android SDK for building, and testing the android applications, we can download the
SDK from http://www.android.com After extracting the downloaded zip file for the SDK we need
to run the SDK Manager whicj is found in the <android-sdk-home> this find & install various
available packages.

The Android Application:


The Android Application is basically composed of the following 3 type of components.
1. Activity
2. Service
3. BroadCast Receiver
4.Content Providers

Activity:
The Activity is the one of the core components of Android App
This is crated as a Java Object subtype ofandroid.app.Activity
This component is managed by the Android App Framework

13/03/2014

Two Day Workshop on Android


The Following are the possible methods that we can override the Activity Object.

The onCreate() :
The onCreate() methos is used to implement initialization code like presenting the View for the
Activity.
The onStart():
The onStart() method allows writing the code executing on getting the activity foreground
The onRestart() :
The onRestart() method can initialize the resources that are closed in the onStop().

The onStop() :
The onStop() method can use the resources that are not required on paused activity. This may
even required to solve the start of the activity.
The onResume() :

13/03/2014

Two Day Workshop on Android


The onResume() can create the resources and / or get the saved state of the activity to get into
foreground.
The onDestroy() : The onDestroy() can perform the finilizations for the activity.
The Life Cycle of Activity is:

Or
Creating an Activity: While creating/starting the activity the following methods are invoked.
onCreate()
onStart()

13/03/2014

Two Day Workshop on Android


onResume()
Some other Activity wants to come to ForeGround:
At this stage onPause() of this activity is invoked and then the other activity is started. In
case of the other activity is taking the complete screen the onScreen() is invoked getting the activity to
background(stopped). Otherwise it gets paused.
The Activity is getting into the foreground:
This activity which is paused or stopped because of some other activity is foreground, is now
coming foreground because of the existing foreground activity is destroyed.
At this stage the onResume() is the only method invoked in case of getting from paused.
If it was stopped the following methods are invoked.
onRestart()
onStart()
onResume()
The Activity Destroying:
The Activity while destroying from foreground invokes the following methods.
onPause()
onStop()
onDestroy()

13/03/2014

Two Day Workshop on Android


Point to Note : The android system can destroy the stopped activity without a user request, just
invoking onDestroy()
he Startup Application :

For the first time want to take the following points to check

Install with Android SDK with necessary APIs


Create a AVD(Android Virtual Device), we can do this using SDK Manager which you find in the
Android SDK installed.
Eclipse is installed with ADT Plugin, and for the first time we want to set the Android SDK location
in Eclipse-window- Preferences.
Select Android from the left side tree.
Browse the Android SDK Install Folder
Eg: d:\android\SDK-windows

Once Creating the Android project we find the project is created with one activity bydefault.

10

13/03/2014

Two Day Workshop on Android


The following are the few important documents or folders to observe.
When you create a new Android project, you get several items in the project's root
directory:

src
A folder that holds the Java source code
gen
This is where Android's build tools will place source code that they generate.
R.java" is a generated class which contains the text and the UI elements.
Android projects come with this free class 'R' which is short for Resource.
This is an automatically generated class that we can use to reference
resources in our project. We should not try to modify this class manually.
assets
A folder that holds other static files you wish packaged with the application
for deployment onto the device.
bin
In Eclipse, the ADT plugin incrementally builds our project as we make
changes to the source code. Eclipse outputs an .apk file automatically to the
bin folder of the project, so we do not have to do anything extra to generate
the .apk.
res
A folder that holds resources such as icons, graphic user interface (GUI)
layouts, etc. that are packaged with the compiled Java in the application.
AndroidMainFest.xml
An XML file describing the application being built and which components
(activities, services, and so on) are being supplied by the application. This file
is the foundation for any Android application. This is where you declare what
is inside your application. You also indicate how these pieces attach
themselves to the overall Android systems; for example, you can indicate
which activity or activities should appear on the device's main menu (a.k.a.
the
launcher).
When you create your application, a starter manifest will be generated for
you automatically. For a simple application, offering a single activity and
nothing else, the auto generated manifest will probably work out fine, or
perhaps require a few minor modifications. But on the other spectrum, the
manifest file for the Android API demo suite is more that 1,000 lines long.
Your production applications will probably falls somewhere in the middle.
Most of the manifest will be describes detail in later chapters.
project.properties
Property files used by the Ant build script.

Creating an Activity:
The activity class needs to be a subtype of android.app.Activity
The onCreate() method is one basic method which minimum we want to override . Like
we may want to create / locate the View and set it to the Activity.
The following methods of Activity are used to set the View

11

13/03/2014

Two Day Workshop on Android


o setContentView(View)
o setContentView(int)
The first allows to set the View Object may be created in the program here. And the later
allows setting the view defined in the XML document.
The FirstActivity.java :
package com.durgasoft.android;
import com.durgasoft.android.R;
import .;
public class FirstActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}}
Main.xml:
<?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" >
</TextView>
</LinearLayout>

12

13/03/2014

Two Day Workshop on Android


The android application includes a generated resource file named R which lists all the resources defined
with unique identity. And this xml View is also given with a unique id to refer in the program. The id can
be accessed using R.layout.Main.
Thus the activity can have this View set as shown below
public class FirstActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}}
It is found in most cases creating a complex view it is convenient to go for XML style
How ever we can get View created in xml into the activity and do necessary changes .
Example:
Public void onCreate(){
setContentView(R.layout.main);
TextView tv=(TextView)findViewById(R.id.tv1);
Tv.setText(New Text); }
To run the above code could give an error as in the main.xml file the TextView is not
specified with any id. To run this above code successfully add the following attribute into the
<TextView> Tag.
andrioid:id=@+id/tv1
The + in the value of the attribute describes add the is resource into the R file if not
available
The android application support multiple type of resource such as layouts, ids and Strings
The String resource is can be added into strings.xml file res/values folder
Eg: <resource><String name=text> Text String Message </String> </resource>
These resources are added into the R file for convenient access.
To access the resources in xml documents we use the following syntax.
Syntax:
@<type>/<name>

13

13/03/2014

Two Day Workshop on Android


Eg:

@String/test

In case the same is required to access in the program we use.

R.<type>.<name>

We can use the following method for getting the string resource declared in the xml.
String s1=getResources().getString(R.String.test);
Similar to String we can have a Boolean resource .this is declared using <bool> tag.
Starting an Activity:
The activity with ACTION_MAIN, and CATEGORY_LAUNCHER is main activity to run on
accessing the application.
In addition we may want to start another activity from such main activity.
We use startActivity(Intent) method of the Activity to do this.

The Intent Object:


The Intent is a value object describing a message to the android system to perform an
action.
Like we may want to describe the android system to start an activity or background
service
The Intent Object describes following six methods
1. Component Name
4.
Data
2. Action
5.
Extras
3. Categories
6.
Flags
The Intents are of two types.
1. Explicit Intents
2. Implicit Intents
Explicit Intents:
These type of intents are started with component name, which directly locates a
Activity by its name.
Example: Lets add a new activity in the previous class
Public class Activity2 extends Activity
{

14

Public void onCreate(Bundle b)


13/03/2014

Two Day Workshop on Android


{

super.onCreate(b);
setContentView(R.layout.main1.xml);

}
}
This new Activity is requited to register into the AndroidManifest.xml
<activity android:name=.Activity2 android:label=Activity2></activity>
In the existing Activity:
following tag.

Lets consider the main.xml is the layout document and has the

<Button
.
Android:onClick=myMethod/>
The following method needs to added into the existence Activity
public void myMethod(View view)
{
Intent i=new Intent();
i.setComponentName(new ComponentName(getApplicationContext(),Activity2.class));
startActivity(i); }

Implicit Intents:
Although the explicit intents are simple but are useful only to locate the activities whose names
are known to us, which is generally with the activities of our application.
In case if we want to access the activities of some other applications in the system explicit would
not meet our requirement
In this case the android system is responsible to find the suitable activities to handle this intent.
In case if none found the ActivityNotFoundException would be thrown.

15

13/03/2014

Two Day Workshop on Android


To do this the intent object is matched with the configured intent filter for the activities .The
following tag is used in the <activity> tag to configure the intent filter.
<intent- filter>........................</>
Implicit Intent:
In Case if the Intent without a component is given , the f/w needs to use the
package manager conduct the following 3 tests to find the suitable activities that
can handle this intent.
Action:
Here the intent action is match with the actions of the intent filters of
the activities.
If the intent doesnt has an action(ies it is null) in such case every
activity with an intent filter atleast with one action will passes this test.
Android includes multiple builtin actions such as ACTION_CALL
We can create our own action, It is recommended to use package name
as prefix for the action name. For example
com.durgasoft.android.GAME_START
o Data:
Once if the activity passes the action test then it is checked for data
test. Here the MIME type and / or path is matched to find is the activity
matching to handle the intent with the given data.
o Category:
The intent and intent filter can have multiple categories added.
All the categories describes in the intent should match the intent filter
categories passing this test.
Note:
The category android.intent.category.DEFAULT is mandatory to include into the
intent filter to have any implicit intents locating this activity. This is excempttion for LAUNCHER
activity.
Intent and Intent Filters:
The intent filters for an activity are declared in the android manifest.xml file as
part of configuring the activity.
The <intent-filter> can have <action>,<data> and <category>

16

13/03/2014

Two Day Workshop on Android


Note:
Having at least one <action> is mandatory to choose this activity using implicit
intent
Having the <category> with the namae android.intent.category.DEFAULT is also
mandatory for locating using implicit intents. Example for the LAUNCHER and
ALTERNATIVE category intent.
The implicit intents requires to identify the appropriate activity to handle the
intent.
To do this it matches the intent info(such as action, type, data, and category) with
the intent filters info of the activity.
If the intent info matches with the intent filter info then the enclosing activity is
chosen to handle this intent
Example
Intent i=new Intent();
i.setAction(Intent.ACTION_DIAL);
startActivity(i);
This starts a phone dialer activity allowing us to dial the number and make a call.
Intent i=new Intent();
i.setAction(Intent.ACTION_DIAL);
Uri.Builder u=new Uri.Builder();
u.scheme(tel);
u.path(1234567890);
i.setData(u.build());
startActivity(i);
This starts the phone dialer activity with the number 1234567890 entered
directly to make a call.
Alternative to ACTION_DIAL we can use ACTION_CALL for directly making a call.
Intent i=new Intent();
i.setAction(Intent.ACTION_GET_CONTENT);

17

13/03/2014

Two Day Workshop on Android


Uri.Builder u=Uri.Builder();
u.scheme(content);
u.path(/contact);
i.setData(u.build());
In addition to startActivity() we can use the startActivityForResult() method to start an
activity.
The start ActivityForResult () method is used to start an activity that can carry some data
returning to the parent activity.
This method takes 2 arguments.

First Arg: Intent


Second Arg: int(specifies the request code, this is used diffentiate between
the multiple child activities that are possible to start from the activity)
This code is used in onActivityResult() method to find the result from which child
activity.
The child Activity can use the following method for sending the result.
setResult(int resultcode,Intent data)
Once the childActivity is finished then the following method of the parent activity is
invoked.
onActivityResult(int requestcode,int resultcode,Intent data)
Note:
In Case if the child activity finished without setting the result , the data will be null.
Sample Program on Intents:
SecondActiivity.java:
package com.durgasoft.android;
import com.durgasoft.android.R;
import .................................................................;
public class SecondActivity extends Activity {
/** Called when the activity is first created. */

18

13/03/2014

Two Day Workshop on Android


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
// Code for explicit Intents

public void MyMethod(View view)


{
Intent i=new Intent();
// Register the Activity2 class in the android manifest.xml file inside <application> tag
//

<activity android:name=".Acitivity2"></activity>

i.setComponent(new ComponentName(getApplicationContext(),Activity2.class));
startActivity(i);

}
// Code for implicit Intents
public void MyMethod1(View view)
{
Intent i=new Intent();
i.setAction(Intent.ACTION_DIAL);
startActivity(i);

19

}
13/03/2014

Two Day Workshop on Android

Activity2.java
package com.durgasoft.android;
import --------------------------------------------;
public class Activity2 extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);

} }

Main.xml
<?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" ></TextView>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/b1"
android:onClick="MyMethod"
android:text="Explicit Intent"></Button>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/b1"
android:onClick="MyMethod1"
android:text="Implicit Intent" ></Button>

20

13/03/2014

Two Day Workshop on Android


</LinearLayout>
Main1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="This is a Second Activity"></TextView>
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.durgasoft.android"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="10" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".SecondActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter></activity>
<activity android:name=".Activity2"></activity>
</application>
</manifest>
Understanding the Views:
The Userinterface of an activity is defined using a View Object.

21

13/03/2014

Two Day Workshop on Android


The View group is one special View type that allows us compose multiple Views into a
single view, thus we can have multiple views to present in a single screen (ies a single
View).
The following method of an Activity is used to set the View for this Activity.
setContentView(android.View.View)
setContentView(int ViewID)
The View can be described in two styles.
o Into XML declarative
o In Activity( Java Code) programmatic. We can use both in combination.
It is recommended use XML style , which can simplify creating the View and allows take
the advantage of first design using click and drag supported by the IDE.
Usign XML Style: In this case we create an XML documents into res/layouts folder
An XML document can describe only one View. Note the View here can be a View group
thus a tree of Views
Here we have an XML tag one for each concrete View type to use defining the View.
Example:
<Button...../> <TextView......../>

<EditView....../>

Example:
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text=Click Me Boss
android:onClick=Submit />
To set this view as User Interface for the Activity we can have the following code in the
onCreate() method of the activity.

setContentView(R.layout.simpleButton);
Note:
The android XML file names cannot have uppercase and special and white space
characters.
If we want have multiple view components into a UI we shall work with ViewGroup such
as Layouts.

22

13/03/2014

Two Day Workshop on Android


The Linear Layout:
This supports arranging multiple View components one after the other
Vertical/Horizontal.
The Orientation property of this component specifies is the child View components to
arrange in Vertical/Horizontal.
If vertical only one View component is allowed with each row.
If Horizontal- All the Views are arranged into a single row.
Example:
<?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="---------------------Linear Layout-------------------"
android:textStyle="bold"></TextView>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="A"></TextView>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="B"></TextView>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="C"></TextView>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="D"></TextView>
<TextView
android:layout_width="fill_parent"

23

13/03/2014

Two Day Workshop on Android


android:layout_height="wrap_content"
android:text="E"></TextView>
</LinearLayout>

The Button:
We use the android.View.Button class to create this component. Or
<Button> tag in the XML document.
Example:
Button b=new Button(this);
b.setText(Submit);
In XML: <Button android:text=Submit/>
Configuring the Button to listen for Click event:
Programatic:
In Case we use the following method of Button to set the listener for
onClick event.
setOnClickListener(View.onClickListener)
The View.OnClickListener is an interface that declares only one method.
public void onClick(View v)
This method is invoked by the View component when a user clicks the
component.
We can create a class implementing this interface . most of the time we
prepare creating an anonymous class
Example:
Button b1=new Button(this);
OnClickListener l=new OnClickListener(){
public void onClick(View v)
{ .......................... };
b1.setOnClickListener(l);
Declarative :
This is simple ,here we want to use android:onClick attribute specifying
the name of the method to listen for this event.
The method needs to be implemented in the content of this Buutton , with
the following signature
public void <method-name> (View v)

24

13/03/2014

Two Day Workshop on Android


The Relative Layout:
In this case the components in the view can be placed with respect to the other
components in the view or with respect to this layout (ies parent) view.
We can use the following attributes to configure the component align with respect to the
layout.
android:layout_alignParentBottom: specifies whether the component is to be placed
at the bottom of the layout. true describes to place to the Bottom.
android:layout_alignParentTop
android:layout_alignParentLeft
android:layout_alignParentRight
The following attributes can be used to place the component with respect to the another
components.
android:layout_below : specifies the id of the component below which this
component has to be arranged.
android:layout_toLeftOf
android:layout_toRightOf
Example:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="Hello This is from Relative Layout"
android:id="@+id/tv1" ></TextView>
<Button android:layout_below="@+id/tv1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="OnClick"
android:id="@+id/b1" > </Button>
<TextView android:layout_below="@+id/b1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="This is the Activity from Relative Layout"
android:id="@+id/tv2" > </TextView>

25

13/03/2014

Two Day Workshop on Android


<!-- Similarly we have
android:layout_toLeftOf="@+id/b1"
android:layout_toRightOf="@+id/b1"
android:layout_above="@+id/b1"-->
</RelativeLayout>
Sample Program on Relative Layout & Button:
package com.durgasoft.android;
import com.durgasoft.android.R;
import ----------------------------------------------;
public class FourthActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b1=(Button)findViewById(R.id.b1);
b1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"Hi This is From
Button",Toast.LENGTH_LONG).show();
}}); } }
Main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="Hello This is from Relative Layout"
android:id="@+id/tv1"></TextView>
<Button android:layout_below="@+id/tv1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="OnClick"
android:id="@+id/b1" > </Button>
<TextView android:layout_below="@+id/b1"

26

13/03/2014

Two Day Workshop on Android


android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="This is the Activity from Relative Layout"
android:id="@+id/tv2" >
</TextView>
<!-- Similarly we can have
android:layout_toLeftOf="@+id/b1"
android:layout_toRightOf="@+id/b1"
android:layout_above="@+id/b1"-->
</RelativeLayout>
The EditText:
This is a text field that allows taking the text content input from the user.
<EditText............/>
Example:
<LinearLayout..................>
<Button android:onClick=onClickB1......./>
<EditText
android:layout_width="150px"
android:layout_height="wrap_content"
android:id="@+id/et1"></EditText>
</LinearLayout>
In The Activity Class:
public void onClickB1(View v)
{
EditText v1=(EditText)findViewById(R.id.v1);
String value=v1.getText().toString();
Toast.makeText(getApplicationContext(), value,
Toast.LENGH_LONG).show();
}
View
TextView
EditText
Button
ToggleButton
CheckBox
RadioButton
Spinner
DatePicker

27

ViewGroup
LinearLayout
RelativeLayout
TableLayout
FrameLayout
ListView
ScrollView
TableView
RadioGroup
13/03/2014

Two Day Workshop on Android


TimePicker
DigitalTime
AnalogTime

ProgressBar
ImageButton
Image

The TextView autolink option ,this is used to have links automatically created for the phone
numbers , email ids and website address supporting us to click performing necessary action. We use
android:autolink attribute to configure this. This defaults to none, and we can specify phone, email, web,
map, or all.
The AutoCompleteTextView:
This is a subtype of EditView , this allows us get the help content listing to choose
the values from . we can use the following tag to declare this component.
<AutoCompleteTextView../>
Example:
<AutoCompleteTextView
android:layout_width="150px"
android:layout_height="wrap_content"
android:id="@+id/act1" >
</AutoCompleteTextView>
In the Activity onCreate() method we can have the following code for describing
the autocomplete words.
AutoCompleteTextView act=(AutoCompleteTextView)findViewById(R.id.act1);
String[] str=new
String[]{"SVU","OU","JNTUK","JNTUH","ANDHRA","SKU","YVU","VSU","PALAMURU","MAHATMA","OTHE
R"};
ArrayAdapter< String> aa=new
ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_dropdown_item_1line,str);
act.setThreshold(1);
act.setAdapter(aa);
The Toggle Button:
This is a subtype of button , this is a special type similar to the CheckBox allowing
us present the a view taking data like yes or no from the user.
We use the following tag to have this view.
<Toggle Button
android:layout_width="150px"

28

13/03/2014

Two Day Workshop on Android


android:layout_height="wrap_content"
android:taxtOn=yes
android:textOff=No/>
The android:textOn specifies the text to display when this button Check (ies on) and
textOff for content to displaying on unchecked(ies off).

The CheckBox:
This is also a subtype of button allows us to take checked/unchecked decisions
from the user.
We use the following tag to declare this view.
<CheckBox android:layout_width="50px"
android:layout_height="wrap_content"
android:id="@+id/cb1"
android:text="MCA"
android:onClick="CheckBox"></CheckBox>
In the activity class we can have the following method.
public void CheckBox(View view)
{
CheckBox cb1,cb2;
cb1=(CheckBox)findViewById(R.id.cb1);
cb2=(CheckBox)findViewById(R.id.cb2);
if(cb1.isChecked())
{ Toast.makeText(getApplicationContext(), "MCA is Selectd",Toast.LENGTH_LONG).show();
}
else if(cb2.isChecked())
{ Toast.makeText(getApplicationContext(), "BTech is Selectd",Toast.LENGTH_LONG).show();
} }

The RadioButton & Radio Group:


The RadioGroup allows having multiple RadioButtons to choose between
This allows setting
onCheckedChangeListener()
Where this listener support only one method
onCheckedChange(RadioGroup, int)
The second arfument described that id of the checked radio button , and -1 in
case of the clearing the check of the group.

29

13/03/2014

Two Day Workshop on Android


To make none of the radio button to check we can use clearCheck() method of
RadioGroup.
In XML Document:
<RadioGroup >
<RadioButton android:layout_width="70px"
android:layout_height="wrap_content"
android:id="@+id/rb1"
android:text="Male"
android:onClick="RadioBox" ></RadioButton>
<RadioButton android:layout_width="70px"
android:layout_height="wrap_content"
android:id="@+id/rb2"
android:text="Female"
android:onClick="RadioBox" ></RadioButton>
</RadioGroup>

In The Activity Class:


public void RadioBox(View view)
RadioButton rb1,rb2;
rb1=(RadioButton)findViewById(R.id.rb1);
rb2=(RadioButton)findViewById(R.id.rb2);
if(rb1.isChecked())
{ Toast.makeText(getApplicationContext(), "male is Selectd",Toast.LENGTH_LONG).show();
}else if(rb2.isChecked())
{Toast.makeText(getApplicationContext(), "Female is Selectd",Toast.LENGTH_LONG).show();
}
}

The Spinner:
This is a list box type allowing us to choose between the given values.
We use the following tag for defining this type of View.
<Spinner android:layout_width="150px"
android:layout_height="50px"
android:id="@+id/sp1" > </Spinner>
We can add the String array resources using the following tag.
<String-array name=myarray>

30

13/03/2014

Two Day Workshop on Android


<item>Value1</item>
<item>Value2</item>
</String-array>
Now we want to set the values for the spinner we write the following code in the activity class
onCreate() method.
String values[]=getResources.getStringArray(R.array.myarray);
ArrayAdapter<String> aa=new
ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item,values);
Spinner sp1=(Spinner)findViewById(R.id.sp1);
sp1.setAdapter(aa);
we can add these entries declaratively also using the following attribute
android:entries=@array/myarray
We can have a OnItemSelectedListener configured to this component, This supports the
following method.
onItemSelectedListener(AdapterView v,View selectedView, int position,long len)
we use setOnItemSelectedListener(OnItemSelectedListener) method of Spinner to set
this listener.
The Scroll View :
This allows us define the view with large height like may be with many components into it.
We use <ScrollView> tag to describe having the Scroll support.

The ListView:
This View allows us to have set of values to list.We use <ListView> tag to define this view.
Example:
Add the following tag in main layout.
<ListView android:layout_width="150px"
android:layout_height="50px"
android:id=@+id/mylist/>
In the onCreate() method of the activity we can have the following code for setting a list of values.
ListView lv=(lv)findViewById(R.id.mylist);
String values[]={value1,value2};
ArrayAdapter<String> aa=new
ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item,values);
lv.setAdapter(aa);

31

13/03/2014

Two Day Workshop on Android


The onItemClickListener:
We can configure this listener to the ListView this declares only one method.
public void onItemClickListener(AdapterView Parent,View v,int position,long id )
we can have a text filtering for the ListView we can be enable using the following method of the
ListView.
setTextFilterEnabled(Boolean)
we can use ListActivity as a utility for creating the Activity that just needs a ListView as a View.
public class MyActivity extends ListActivity
{
public void onCreate(Bundle b)
{
super.onCreate(b);
ListView lv=getListView();
..
}}

The GridView:
This is similar to the ListView , but supports arranging the elements into rows and
columns.
The following tag is used to define this View.
<GridView ....></>
We use android:numColumns attribute specifying the number of columns, and the
number of rows is decided decided based on the items.
Like done with the ListView we set the adapter for the items,and can set thee
OnItemClickListenr
The DatePicker:
This allows us to have a view that can take the date from the user. The following tag is
used to configure this view
<DatePicker .........../>
And the init() method of the DatePickerDialog is used to set
the initiated date and the onDateChangedListener.
If the method is not invoked it by default sets the date to the system date.

The TimePicker:

32

13/03/2014

Two Day Workshop on Android


Similar to the DatePicker this view allows us to select the time that includes hours and
minutes.
This is alsosupported with a listener to get the notification on the change in the time, just
like with DatePicker, this supports onTimeChangedListener
with one method described below.
void onTimeChanged(TimePicker,int hours,int minutes)
Progress Bar:
This is the View that supports to describe the end user that some long process is being
taking up and you may want to wait for completing process.
We generally can categorize the Progress Bar into two types.
1.Indetermine ProgressBar
2. Determine ProgressBar
Indetermine ProgressBar:
In this case the progress bar doesnt describes the status of the work completed
and/or the balance work, this is used in case if we are not known like that amount of
work is completed and how much still balance.
Determined ProgressBar:
The following tag is used to describe the progress bar, and by default this is
Indeterminent.
<ProgressBar.............../>
We use the setVisibility(int) method to show or make this View invisible . like may
be once the long running work is got completed . we can make this invisible.
Example:
ProgressBar pb=(ProgressBar)findViewById(R.id.pb);
pb.setVisibility(ProgressBar.GONE);
we can have this progress bar on the title bar itself . To have this we want to
request for the respective window feature. We use the following code in the activity
before setting the ContentView to do this.
requestWindowFeature(Window.FEATURE_INDETERMINE_PROGRESS)
(before setContentView(.............))
And the following method of the Activity can support us to show the visibility of
this feature.
setProgressBarIndeterminate Visibility(boolean)
Note : This method e want to use after setting the ContentView
Similarly we have determinate ProgressBar also on to the title bar. For this we
want to request for the following window Feature.

33

13/03/2014

Two Day Workshop on Android


requestWindowFeature(Window.FEATURE_PROGRESS);
And same like earlier we use the following method for setting the visibility of this
view.
setProgressBarVisibility(boolean)
In addition here we can set the progress using the following method of activity.
setProgress(int)
The maximum progress is defined as 10000. Meaning 5000 progress values
describes 50% of progress.

Sample Program on all Views:


FifthActivity.java
package com.durgasoft.android;
import ;
public class FifthActivity extends Activity {
private static int DATE_PICKER_DIALOG=1;
private static int TIME_PICKER_DIALOG=2;
/* Example for All The View ---> EditText,Buttons,
Radio Buttons,CheckBox,Spinners,ToggleButtons,
AutoCompleteTextView,DatePickerDialog,TimePickerDialog
AnalogTime,ScrollView,ProgressBar,ImageButton,ListView,RadioGroup
*/
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AutoCompleteTextView act;
act=(AutoCompleteTextView)findViewById(R.id.act1);
String[] str=new String[]{"SVU","OU",,"SKU","YVU",};
ArrayAdapter< String> aa=new
ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_dropdown_item_1line,str);
act.setThreshold(1);
act.setAdapter(aa);
Spinner sp1=(Spinner)findViewById(R.id.sp1);
String[] str1=getResources().getStringArray(R.array.myarray);

34

13/03/2014

Two Day Workshop on Android


ArrayAdapter< String> aa1=new
ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_dropdown_item_1line,str1)
sp1.setAdapter(aa1);
}
public void CheckBox(View view)
{
CheckBox cb1,cb2;
cb1=(CheckBox)findViewById(R.id.cb1);
cb2=(CheckBox)findViewById(R.id.cb2);
if(cb1.isChecked())
{ Toast.makeText(getApplicationContext(), "MCA is Selectd",Toast.LENGTH_LONG).show();
} else if(cb2.isChecked())
{
Toast.makeText(getApplicationContext(), "BTech is Selectd",Toast.LENGTH_LONG).show();
}
}
public void RadioBox(View view)
{
RadioButton rb1,rb2;
rb1=(RadioButton)findViewById(R.id.rb1);
rb2=(RadioButton)findViewById(R.id.rb2);
if(rb1.isChecked())
{
Toast.makeText(getApplicationContext(), "male is Selectd",Toast.LENGTH_LONG).show();
}
else if(rb2.isChecked())
{
Toast.makeText(getApplicationContext(), "Female is
Selectd",Toast.LENGTH_LONG).show();
}
}
public Dialog onCreateDialog(int index)
{
if(index==DATE_PICKER_DIALOG)
{
OnDateSetListener dl=new OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {

35

13/03/2014

Two Day Workshop on Android


Button b1=(Button)findViewById(R.id.dp);
b1.setText(dayOfMonth+"-"+(monthOfYear+1)+"-"+year);
}
};
DatePickerDialog dpd=new DatePickerDialog(this,dl,2012,04,24);
return dpd;
}
else if(index==TIME_PICKER_DIALOG)
{
OnTimeSetListener tl=new OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Button b1=(Button)findViewById(R.id.tp);
b1.setText(hourOfDay+"-"+minute);
}
};
TimePickerDialog tpd=new TimePickerDialog(this,tl,10,12,false);
return tpd;
}
return null;
}
public void StartDialog(View view)
{
showDialog(DATE_PICKER_DIALOG);
}
public void TimeDialog(View view)
{
showDialog(TIME_PICKER_DIALOG);
}}
The Main.xml:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/ap
k/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableLayout

36

android:layout_height="wrap_content"
android:layout_width="fill_parent"
<TableRow >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Student Registration Form"
android:textStyle="bold|italic" >
</TextView>
13/03/2014

>

Two Day Workshop on Android


</TableRow>
<TableRow >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter the Name" >
</TextView>
<EditText android:layout_width="150px"
android:layout_height="wrap_content"
android:id="@+id/et1" >
</EditText>
</TableRow>
<TableRow >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter the University " >
</TextView>
<AutoCompleteTextView
android:layout_width="150px"
android:layout_height="wrap_content"
android:id="@+id/act1" >
</AutoCompleteTextView>
</TableRow>
<TableRow >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select The Course " >
</TextView>
<Spinner android:layout_width="150px"
android:layout_height="50px"
android:id="@+id/sp1"
> </Spinner>
</TableRow>
<TableRow >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"

37

android:text="Select The Qualification " >


</TextView>
<CheckBox
android:layout_width="50px"
android:layout_height="wrap_content"
android:id="@+id/cb1"
android:text="MCA"
android:onClick="CheckBox" ></CheckBox>
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" ></TextView>
<CheckBox
android:layout_width="50px"
android:layout_height="wrap_content"
android:id="@+id/cb2"
android:text="BTech"
android:onClick="CheckBox" ></CheckBox>
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select The Gender"
></TextView>
<RadioGroup >
<RadioButton android:layout_width="70px"
android:layout_height="wrap_content"
android:id="@+id/rb1"
android:text="Male"
android:onClick="RadioBox"
></RadioButton>
<RadioButton
android:layout_width="70px"
android:layout_height="wrap_content"
android:id="@+id/rb2"
13/03/2014

Two Day Workshop on Android


android:text="Female"
android:onClick="RadioBox"
></RadioButton>
</RadioGroup>
</TableRow>
<TableRow >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Course Joining Date"
></TextView>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/dp"
android:text="Select Date"
android:onClick="StartDialog" ></Button>

</TableRow>
<TableRow >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Prefered Timings"
></TextView>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tp"
android:text="Select Time"
android:onClick="TimeDialog" ></Button>
</TableRow>
</TableLayout>
</ScrollView>

Dialog Box:
The android.app.DialogInterface is the base interface representing any dialog.
The android.app.Dialog class supports declaring a dialog . This is the base class for
any dialog.
Example:
Dialog d=new Dialog(this);
d.setContentView(R.layout.dialog_layout);
The dialog_layout describes the view for the dialog just as done for the activity.
d.setOwnerActivity(MyActivity,this);
d.show(); // This will show the dialog
we can add onCancelListener and onDismissListeners set to the Dialog.
We use any of the following methods of Dialog to choose the dialog box.
Cancel();
Dismiss();
Android includes the following builtin dialogs implementation simplifying creating the
dialog box for most common requirements.

38

13/03/2014

Two Day Workshop on Android


Alert Dialog
ProgressBar Dialog
DatePicker Dialog
TimePicker Dialog

The AlertDialog: This supports us to create a dialog that meets the most common requirement
of having a dialog for showing some alert, this includes
- A Optional Title
- Message Text
- Zero, one, two, or three buttons
- List of items
We use a AlertDialog.Builder object to crate this Dialog .
The following methods of this object allows us setting the details for the dialog.
- setTitle(String)
- setMessage(String)
- setPositiveButton(String lable,DialogInterface.OnClickLIstener listener)
- setNegiveeButton(String lable,DialogInterface.OnClickLIstener listener)
- setNutralButton(String lable,DialogInterface.OnClickLIstener listener)
- setItems(String[])
Once setting all the details , we can invoke create() method for the AlertDialog
object and further show() method for showing.
The following methods of Activity can be used to show and remove the Dialog
boxes.
showDialog(int): This shows the Dialog.
removeDialog(int): Removes the dialog from the Activity
The OnCreateDialog(int): method is invoked for the first time when a dialog is
requested to show. This method is responsible to create a dialog for the given
index to show.
The onPrepareDialog(int): method is invoked each time(including firsttime)
when a dialog is required to show.
Note:
The Activity retains the state of the dialog even on cancelled / dismiss of
the dialog is requested to show again . However invoking remove Dialog(int) will
release the dialog state with the activity.
The Menu:

39

13/03/2014

Two Day Workshop on Android


The following methods Activity are invoked to create the menu for the activity.
OnCreateOptionsMenu(menu):
This method is invoked for the first time the user clicks on the menu for the activity.
Note: From Android 3.0 this is invoked at the time starting the Activity as the menu
here is always visible.
OnPrepareOptionsMenu(menu):
This is called each time when the menu is required to be show.
To Listen for the menu item click we can override the following method.
boolean onMenuItemSelected(int featureId,MenuItem m)

Sample Program on Dialog Boxes and Menus:


package com.durgasoft.android;
import ......................................................................;
public class DialogsExampleActivity extends Activity {
private EditText time_et;
private Button date_button;
// Example for Dialog Boxes and the Menu
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
time_et=(EditText)findViewById(R.id.time_et);
date_button=(Button)findViewById(R.id.b2);
}
private static int BASIC_DIALOG=1;
private static int DATE_PICKER_DIALOG=2;
private static int TIME_PICKER_DIALOG=3;
private static int ALERT_DIALOG1=4;
private static int ALERT_DIALOG2=5;

40

13/03/2014

Two Day Workshop on Android


public void button1Click(View v){
// Remove the comments One by One and check the result
//showDialog(BASIC_DIALOG);
//showDialog(ALERT_DIALOG2);
showDialog(ALERT_DIALOG1);
; }
public void button2Click(View v){
showDialog(DATE_PICKER_DIALOG);
}
public void button3Click(View v){
showDialog(TIME_PICKER_DIALOG);
}
public Dialog onCreateDialog(int index){
if(index==BASIC_DIALOG){
final Dialog d=new Dialog(this);
d.setContentView(R.layout.dialog1_layout);
Button b=(Button)d.findViewById(R.id.b2);
b.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
d.dismiss();} });
return d;
}else if (index==DATE_PICKER_DIALOG){
OnDateSetListener dl=
new OnDateSetListener() {
public void onDateSet(
DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
Toast.makeText(getApplicationContext(), "Date : "+dayOfMonth+"-"+(monthOfYear+1)+""+year,
Toast.LENGTH_SHORT).show();
date_button.setText("New : "+
dayOfMonth+"-"+(monthOfYear+1)+"-"+year);
}
};

41

13/03/2014

Two Day Workshop on Android


DatePickerDialog dpd=new DatePickerDialog(this, dl, 2011, 10, 12);
return dpd;
}else if (index==TIME_PICKER_DIALOG){
OnTimeSetListener dl=new OnTimeSetListener() {
public void onTimeSet(TimePicker tp, int arg1,int arg2) {
Toast.makeText(getApplicationContext(), "Time : "+arg1+":"+arg2,
Toast.LENGTH_SHORT).show();
String text="";
if (arg1 <= 12){
text=arg1+":"+arg2+" AM";
}else{
text=(arg1-12)+":"+arg2+" PM";
}
time_et.setText(text);
}
};
TimePickerDialog tpd=
new TimePickerDialog(
this,dl, 10, 12, false);
return tpd;
}else if (index == ALERT_DIALOG1){
AlertDialog.OnClickListener listener=
new AlertDialog.OnClickListener(){
public void onClick(
DialogInterface dialog,
int which) {
String text="";
if (which==AlertDialog.BUTTON_POSITIVE){
text="Positive : OK";
}else if(which==AlertDialog.BUTTON_NEGATIVE){
text="Natative : Not OK";
}else {
text="Nutral : OK";
}

42

13/03/2014

Two Day Workshop on Android


Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
};
AlertDialog.Builder ab=
new AlertDialog.Builder(this);
ab.setTitle("Alert Dialog Sample");
ab.setMessage("You opened AlertDialog");
ab.setPositiveButton("OK", listener);
//ab.setNegativeButton("Not OK", listener);
//ab.setNeutralButton("Neutral", listener);
return ab.create();
}else if (index == ALERT_DIALOG2){
AlertDialog.Builder ab=new AlertDialog.Builder(this);
ab.setTitle("Alert Dialog Sample");
final String[] items={"Abc1", "Abc2","Abc3", "Abc4"};
DialogInterface.OnClickListener listener=
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
Toast.makeText(
getApplicationContext(),
items[which],
Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
};
ab.setItems(items, listener);
return ab.create();
}else{
return null;
}
}
public void onPrepareDialog(int index, Dialog d){
if (index==BASIC_DIALOG){
EditText ev=(EditText)d.findViewById(R.id.et1);
TextView tv=(TextView)d.findViewById(R.id.tv1);
tv.setText(tv.getText()+":"+ ev.getText());

43

13/03/2014

Two Day Workshop on Android


}
}
@Override
public boolean onCreateOptionsMenu(
Menu menu) {
MenuInflater mi=new MenuInflater(this);
mi.inflate(R.menu.menu1, menu);
return true;
}
@Override
public boolean onMenuItemSelected(
int featureId, MenuItem item) {
Toast.makeText(getApplicationContext(), item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
}
}
Main.xml:
<?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"
></TextView>
<Button android:id="@+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="button1Click"
android:text="Show Dialog">
</Button>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"

44

13/03/2014

Two Day Workshop on Android


android:orientation="horizontal">
<TextView
android:layout_width="150px"
android:layout_height="wrap_content"
android:text="Alarm Date : ">
</TextView>
<Button android:id="@+id/b2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="button2Click"
android:text="Set Date">
</Button>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText android:id="@+id/time_et"
android:layout_width="100px"
android:layout_height="wrap_content">
</EditText>
<Button android:id="@+id/b3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="button3Click"
android:text="Show Time Dialog">
</Button>
</LinearLayout>
</LinearLayout>
dialog1_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="@+id/tv1"

45

13/03/2014

Two Day Workshop on Android


android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="This is a dialog box" ></TextView>
<EditText android:layout_width="match_parent"
android:layout_height="wrap_content"
android:lines="2"
android:id="@+id/et1" ></EditText>
<Button android:id="@+id/b2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Close"></Button>
<DatePicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
></DatePicker></LinearLayout>

my_tabs_view.xml:
<?xml version="1.0" encoding="utf-8"?>
<TabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@id/android:tabhost"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TabWidget
android:id="@id/android:tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<FrameLayout
android:id="@id/android:tabcontent"

46

13/03/2014

Two Day Workshop on Android


android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
</TabHost>
Menu1.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/m1"
android:title="Option1"></item>
<item android:id="@+id/m2"
android:title="Option2"></item>
<item android:id="@+id/m3"
android:title="Option3"></item>
<item android:id="@+id/m4"
android:title="Option4"></item>
<item android:id="@+id/m5"
android:title="File">
<menu >
<item android:id="@+id/m6"
android:title="Open"></item>
<item android:id="@+id/m7"
android:title="New"></item>
</menu>
</item>
</menu>

Storage Methods:
1. Shared Preferences
2. SQLite Databse
3. XML
1). Shared Preferences :
Interface for accessing and modifying preference
data returned by
getSharedPreferences(String, int).
SharedPreferences

47

spf=getSharedPreferences("mypreferences",Con
text.MODE_PRIVATE);
SharedPreferences.Editor
Interface used for modifying values in a
SharedPreferences object.
Create a new Editor for these preferences,
through which you can make modifications to
the data in the
13/03/2014

Two Day Workshop on Android


preferences and atomically commit those
changes back to the SharedPreferences object.
SharedPreferences.Editor editor=spf.edit();
Note : to get the data from shared prefernces
shared prefrences object is enough but to insert
data or to
modify data we need to create Shared
Preferences.Editor Object.
The data is stored using key,value pairs you
need pass a unique key for each value and you
can
insert Boolean, Float , Long , String , int data
type values.
Sample Program on Shared Preferences :
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/ap
k/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="38dp"
android:text = "Enter Name :"
android:textAppearance="?android:attr/textApp
earanceMedium" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"

48

android:layout_marginTop="83dp"
android:text = "Enter Password :"
android:textAppearance="?android:attr/textApp
earanceMedium" />
< EditText
android:id="@+id/editText1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/textView1"
android:layout_marginLeft="27dp"
android:layout_toRightOf="@+id/textView1" >
<requestFocus />
</EditText>
< EditText
android:id="@+id/editText2"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView2"
android:layout_alignBottom="@+id/textView2"
android:layout_alignLeft="@+id/editText1" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/editText2"
android:layout_below="@+id/editText2"
android:layout_marginTop="53dp"
android:onClick="Save"
android:text = "Save" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/button1"
android:layout_below="@+id/button1"
android:layout_marginTop="34dp"
android:onClick="getDetails"
android:text = "getDetails" />
13/03/2014

Two Day Workshop on Android


</RelativeLayout>
TestProjectActivity.java
package com.mahesh.test;
import ................;
public class TestProjectActivity extends Activity {
SharedPreferences spf;
SharedPreferences.Editor spe;
@Override
public void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spf=getSharedPreferences("myprefs",
Context.MODE_PRIVATE);
spe=spf.edit();
}
public void Save(View v){
EditText
et1=(EditText)findViewById(R.id.editText1);
EditText
et2=(EditText)findViewById(R.id.editText2);
spe.putString("name", et1.getText().toString());
spe.putString("pass", et2.getText().toString());
spe.commit();
}
public void getDetails(View v){
String name=spf.getString("name","There is no
value with this key");
String pass=spf.getString("pass", "There is no
value with this key");
Toast.makeText(getApplicationContext(),"User
Name is :"+name+" Pass is :"+pass
,Toast.LENGTH_LONG ).show();
}
}
to explore persisted shared preferences select
DDMS-data-data-select your package open
shared

49

preferences you will get an xml with the


preferences name.
2). SQLite DataBase :
SQLiteDatabase has methods to create, delete,
execute SQL commands, and perform other
common database management tasks.
Note : Database names must be unique within
an application, not across all applications.
openOrCreateDatabase(String path,
SQLiteDatabase.CursorFactory factory)
Equivalent to openDatabase(path, factory,
CREATE_IF_NECESSARY).
Is used to create the SQLite Object if the data
base is not available creates a new database if
database is already available then it opens the
database .
SQLiteDatabase
db=openOrCreateDatabase("mydb",Context.M
ODE_PRIVATE, null);
Cursor : This interface provides random readwrite access to the result set returned by a
database
query.
db.execSQL("create table employee(eid
varchar2(20),ename varchar2(20),desig
varchar2(20),dept varchar2(20));");
This statement creates a new table with
employee if table is not there it will create a new
table.
If table is already available it will through u an
exception u need to handle it.
try{
db.execSQL("create table employee(eid
varchar2(20),ename varchar2(20),desig
varchar2(20),dept varchar2(20));");
}catch(Exception e){e.printStackTrace();}
Sample Program on SQLite Database :
sqlite.xml
13/03/2014

Two Day Workshop on Android


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/ap
k/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="33dp"
android:text = "Employee id :"
android:textAppearance="?android:attr/textApp
earanceMedium" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:layout_marginTop="40dp"
android:text = "Employee Name:"
android:textAppearance="?android:attr/textApp
earanceMedium" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView2"
android:layout_marginTop="54dp"
android:text = "Desig :"
android:textAppearance="?android:attr/textApp
earanceMedium" />
<TextView
android:id="@+id/textView4"

50

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView3"
android:layout_marginTop="66dp"
android:text = "Dept :"
android:textAppearance="?android:attr/textApp
earanceMedium" />
< EditText
android:id="@+id/editText1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/textView1"
android:layout_marginLeft="35dp"
android:layout_toRightOf="@+id/textView2" >
<requestFocus />
</EditText>
< EditText
android:id="@+id/editText2"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/textView2" />
< EditText
android:id="@+id/editText3"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView3"
android:layout_alignBottom="@+id/textView3"
android:layout_alignLeft="@+id/editText2"
android:layout_alignParentRight="true" />
< EditText
android:id="@+id/editText4"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView4"
13/03/2014

Two Day Workshop on Android


android:layout_alignBottom="@+id/textView4"
android:layout_alignLeft="@+id/editText3"
android:layout_alignParentRight="true" />
<RelativeLayout
android:id="@+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText4"
android:layout_toRightOf="@+id/textView3"
android:orientation="vertical" >
</RelativeLayout>
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:onClick="Delete"
android:text = "Delete" />
<Button
android:id="@+id/button2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/button1"
android:layout_alignParentLeft="true"
android:onClick="Update"
android:text = "Update" />
<Button
android:id="@+id/button3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/editText4"
android:layout_marginTop="14dp"
android:onClick="Insert"
android:text = "Insert" />
<Button
android:layout_width="fill_parent"

51

android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/button3"
android:onClick="getDetails"
android:text = "getDetails" />
</RelativeLayout>
TestProjectActivity .java
sqlite.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/ap
k/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="33dp"
android:text = "Employee id :"
android:textAppearance="?android:attr/textApp
earanceMedium" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:layout_marginTop="40dp"
android:text = "Employee Name:"
android:textAppearance="?android:attr/textApp
earanceMedium" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
13/03/2014

Two Day Workshop on Android


android:layout_alignParentLeft="true"
android:layout_below="@+id/textView2"
android:layout_marginTop="54dp"
android:text = "Desig :"
android:textAppearance="?android:attr/textApp
earanceMedium" />
< EditText
android:id="@+id/editText1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/textView1"
android:layout_marginLeft="35dp"
android:layout_toRightOf="@+id/textView2" >
<requestFocus /> </EditText>
< EditText
android:id="@+id/editText2"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/textView2" />
< EditText
android:id="@+id/editText3"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView3"
android:layout_alignBottom="@+id/textView3"
android:layout_alignLeft="@+id/editText2"
android:layout_alignParentRight="true" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text = "Dept :"

52

android:textAppearance="?android:attr/textApp
earanceMedium" />
< EditText
android:id="@+id/editText4"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText3"
android:layout_alignParentRight="true"
android:layout_centerVertical="true" />
<Button
android:id="@+id/button3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/editText4"
android:onClick="Insert"
android:text = "Insert" />
<Button
android:id="@+id/button4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/button3"
android:onClick="getDetails"
android:text = "getDetails" />
<Button
android:id="@+id/button2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/button4"
android:onClick="Update"
android:text = "Update" />
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
13/03/2014

Two Day Workshop on Android


android:layout_below="@+id/button2"
android:onClick="Delete"
android:text = "Delete" />
</RelativeLayout>
TestProjectActivity. Java
package com.mahesh.test;
import ............;
public class TestProjectActivity extends Activity {
SQLiteDatabase db;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sqlite);
db=openOrCreateDatabase("mydb",Context.MO
DE_PRIVATE, null);
try{
db.execSQL("create table employee(eid
varchar2(20),ename varchar2(20),desig
varchar2(20),dept
varchar2(20));");
}catch(Exception e){
e.printStackTrace();
}
}
public void Insert(View v){
EditText et1,et2,et3,et4;
et1=(EditText)findViewById(R.id.editText1);
et2=(EditText)findViewById(R.id.editText2);
et3=(EditText)findViewById(R.id.editText3);
et4=(EditText)findViewById(R.id.editText4);
ContentValues cv=new ContentValues();
cv.put("eid",et1.getText().toString());
cv.put("ename", et2.getText().toString());
cv.put("desig", et3.getText().toString());
cv.put("dept", et4.getText().toString());
db.insert("employee",null,cv);

53

et1.setText("");
et2.setText("");
et3.setText("");
et4.setText("");
}
public void Update(View v){
EditText et1,et2,et3,et4;
et1=(EditText)findViewById(R.id.editText1);
et2=(EditText)findViewById(R.id.editText2);
et3=(EditText)findViewById(R.id.editText3);
et4=(EditText)findViewById(R.id.editText4);
ContentValues cv=new ContentValues();
cv.put("ename", et2.getText().toString());
cv.put("desig", et3.getText().toString());
cv.put("dept", et4.getText().toString());
db.update("employee", cv, "eid=?", new
String[]{et1.getText().toString()});
et1.setText("");
et2.setText("");
et3.setText("");
et4.setText("");
}
public void Delete(View v){
EditText et1;
et1=(EditText)findViewById(R.id.editText1);
db.delete("employee", "eid=?", new
String[]{et1.getText().toString()});
et1.setText("");
}
public void getDetails(View v){
EditText et1;
et1=(EditText)findViewById(R.id.editText1);
Cursor c=db.query("employee", new
String[]{"eid","ename","desig","dept"}, "eid=?",
new
String[]{et1.getText().toString()}, null, null, null);
while (c.moveToNext()) {
13/03/2014

Two Day Workshop on Android


Toast.makeText(getApplicationContext(), "Eid is
:"+c.getString(0)+"\n Ename
is :"+c.getString(1)+"\n Desig is
:"+c.getString(2)+"\n Dept
is
:"+c.getString(3),Toast.LENGTH_LONG).show();
}
}
}
If you want explore the db file select DDMSdata data select your package inside package
u will
find a database folder and select u r db file u can
pull that one to ur system by selecting pull a file
from
the device icon . SQLite browser is used to
explore your sqlite dbfile .
Using XML :
You can persist the data as a XML file . The
advantage if u persist the data in xml u can store
the data into ur external and internal storage
and xml interapable language . If you want share
your to
some other technologies use XML format.
To read and write the data into xml file we need
XML parsers.
There are two types of parser are available
1). JAXP ( DOM (read-write) , SAX (Read-only))
2). JAXB
Android does not support JAXB.
For the above Activity instead of persisting the
data into SQLite we will store the data in to XML
Working with DOM :
to run this application u need to add the below
permission in the AndroidManifest.xml file
<uses-permission
android:name="android.permission.WRITE_EXTE
RNAL_STORAGE"/>

54

Before run this application u need to create a


xml file in your sdcard as the following structure
mnt/sdcard/xml/ Employees.xml with root tag
as <employees></employees>
package com.mahesh.test;
import java.io.File;
import .........................;
public class TestProjectActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sqlite);
}
public void Insert(View v){
try{
EditText et1,et2,et3,et4;
et1=(EditText)findViewById(R.id.editText1);
et2=(EditText)findViewById(R.id.editText2);
et3=(EditText)findViewById(R.id.editText3);
et4=(EditText)findViewById(R.id.editText4);
DocumentBuilderFactory
dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder
db=dbf.newDocumentBuilder();
File f=new
File(Environment.getExternalStorageDirectory()+
"/xml/Employees.xml");
// to parse the file there xml file should be
available with root tag <employees> <
/employees> otherwise create a new document
element
Document d=db.parse(f);
Element e1=d.createElement("employee");
Element e2=d.createElement("eid");
Element e3=d.createElement("ename");
Element e4=d.createElement("desig");
13/03/2014

Two Day Workshop on Android


Element e5=d.createElement("dept");
String eid,ename,desig,dept;
eid=et1.getText().toString();
ename=et2.getText().toString();
desig=et3.getText().toString();
dept=et4.getText().toString();
Node n1=d.createTextNode(eid);
Node n2=d.createTextNode(ename);
Node n3=d.createTextNode(desig);
Node n4=d.createTextNode(dept);
e2.appendChild(n1);
e3.appendChild(n2);
e4.appendChild(n3);
e5.appendChild(n4);
e1.appendChild(e2);
e1.appendChild(e3);
e1.appendChild(e4);
e1.appendChild(e5);
d.getDocumentElement().appendChild(e1);
TransformerFactory
tfr=TransformerFactory.newInstance();
Transformer tf=tfr.newTransformer();
DOMSource ds=new DOMSource(d);
// AssetManager am=getAssets();
StreamResult sr=new StreamResult(f);
// StreamResult sr=new
StreamResult(openFileOutput("Employees.xml",
Context.MODE_WORLD_WRITEABLE));
tf.transform(ds, sr);
et1.setText("");
et2.setText("");
et3.setText("");
et4.setText("");
}catch(Exception e){
e.printStackTrace();
}
}
public void Update(View v){

55

// Note : i want to update the data whose name


is mahesh i want change the data to Rajesh
try{
DocumentBuilderFactory
dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder
db=dbf.newDocumentBuilder();
File f=new
File(Environment.getExternalStorageDirectory()+
"/xml/Employees.xml");
// to parse the file there xml file should be
available with root tag <employees> <
/employees> otherwise create a new document
element
Document d=db.parse(f);
NodeList
nl=d.getElementsByTagName("ename");
for(int i=0;i<nl.getLength();i++){
Node n=nl.item(i);
if(n.getFirstChild().getNodeValue().equals("Mah
esh")){
n.getFirstChild().setNodeValue("Rajesh");
}
}
TransformerFactory
tfr=TransformerFactory.newInstance();
Transformer tf=tfr.newTransformer();
DOMSource ds=new DOMSource(d);
// AssetManager am=getAssets();
StreamResult sr=new StreamResult(f);
// StreamResult sr=new
StreamResult(openFileOutput("Employees.xml",
Context.MODE_WORLD_WRITEABLE));
tf.transform(ds, sr);
}catch(Exception e){
e.printStackTrace();
}
}
13/03/2014

Two Day Workshop on Android


public void Delete(View v){
// i want remove the ename from the employee
record whose name is Rajesh
try{
DocumentBuilderFactory
dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder
db=dbf.newDocumentBuilder();
File f=new
File(Environment.getExternalStorageDirectory()+
"/xml/Employees.xml");
// to parse the file there xml file should be
available with root tag <employees> <
/employees> otherwise create a new document
element
Document d=db.parse(f);
NodeList
nl=d.getElementsByTagName("employee");
for(int i=0;i<nl.getLength();i++){
Node n=nl.item(i);
NodeList nl1=n.getChildNodes();
for(int j=0;j<nl1.getLength();j++){
if(nl1.item(j).getFirstChild().getNodeValue().equ
als("Rajesh")){
n.removeChild(nl1.item(j));
}
}
TransformerFactory
tfr=TransformerFactory.newInstance();
Transformer tf=tfr.newTransformer();
DOMSource ds=new DOMSource(d);
// AssetManager am=getAssets();
StreamResult sr=new StreamResult(f);
// StreamResult sr=new
StreamResult(openFileOutput("Employees.xml",
Context.MODE_WORLD_WRITEABLE));
tf.transform(ds, sr);
}

56

}catch(Exception e){
e.printStackTrace();
}
}
public void getDetails(View v){
// i want to display the employee records in a
Toast message
try{
DocumentBuilderFactory
dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder
db=dbf.newDocumentBuilder();
File f=new
File(Environment.getExternalStorageDirectory()+
"/xml/Employees.xml");
// to parse the file there xml file should be
available with root tag <employees> <
/employees> otherwise create a new document
element
Document d=db.parse(f);
String msg="";
NodeList
nl=d.getElementsByTagName("employee");
for(int i=0;i<nl.getLength();i++){
Node n=nl.item(i);
NodeList nl1=n.getChildNodes();
for(int j=0;j<nl1.getLength();j++){
msg=msg+nl1.item(j).getFirstChild().getNodeVal
ue()+"\n";
}
Toast.makeText(getApplicationContext(), msg,
Toast.LENGTH_LONG).show();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
13/03/2014

Two Day Workshop on Android


Before performing delete operation
after delete operation
SAX Parser :
SAX Parser is the read only parser compare to
DOM Parser reading the data using SAX
Parser is easy and having move advantages than
DOM Parser .
Code to get the data using SAX Parser :
add this method in the previous example
public void getDataUsingSAX(View v){
try{
File f=new
File(Environment.getExternalStorageDirectory()+
"/xml/Employees.xml");
SAXParserFactory
spf=SAXParserFactory.newInstance();
SAXParser sp=spf.newSAXParser();
sp.parse(f, new DefaultHandler(){
Boolean eid,ename,desig,dept;
@Override
public void characters(char[] ch, int start, int
length)
throws SAXException {
// TODO Auto-generated method stub
super.characters(ch, start, length);
if(eid){
Toast.makeText(getApplicationContext(),
"Employee id is :"+new
String(ch, start, length),
Toast.LENGTH_SHORT).show();
}
if(ename){
Toast.makeText(getApplicationContext(),
"Employee Name
is :"+new String(ch, start, length),
Toast.LENGTH_SHORT).show();
}
if(desig){

57

Toast.makeText(getApplicationContext(),
"Employee Desig
is :"+new String(ch, start, length),
Toast.LENGTH_SHORT).show();
}
if(dept){
Toast.makeText(getApplicationContext(),
"Employee Dept
is :"+new String(ch, start, length),
Toast.LENGTH_SHORT).show();
}
}
@Override
public void endElement(String uri, String
localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
super.endElement(uri, localName, qName);
if(qName.equals("eid")){
eid=false;
}
if(qName.equals("ename")){
ename=false;
}
if(qName.equals("desig")){
desig=false;
}
if(qName.equals("dept")){
dept=false;
}
}
@Override
public void startElement(String uri, String
localName,
String qName, Attributes attributes) throws
SAXException {
// TODO Auto-generated method stub
13/03/2014

Two Day Workshop on Android


super.startElement(uri, localName, qName,
attributes);
System.out.println(qName);
if(qName.equals("eid")){
eid=true;
}
if(qName.equals("ename")){
ename=true;
}
if(qName.equals("desig")){
desig=true;
}
if(qName.equals("dept")){
dept=true;
}
}
});
}catch(Exception e){
e.printStackTrace();
}
}
Android With Restful WebServices
Communication :
Android SDK inbuild is having supporting
libraries to communicate with Restful
WebServices
Sample code to interact With Restful
WebServices :
(My Intension is I will pass two parameters to
server, get the response from the server display
the
response message using Toast)
login.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/ap
k/res/android"
android:layout_width="match_parent"

58

android:layout_height="match_parent" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="32dp"
android:text = "Enter Name"
android:textAppearance="?android:attr/textApp
earanceMedium" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:layout_marginTop="44dp"
android:text = "Enter Password"
android:textAppearance="?android:attr/textApp
earanceMedium" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView2"
android:layout_marginTop="35dp"
android:layout_toRightOf="@+id/textView2"
android:onClick="Login"
android:text = "Login" />
< EditText
android:id="@+id/editText1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView1"
android:layout_alignBottom="@+id/textView1"
android:layout_toRightOf="@+id/button1" >
<requestFocus />
13/03/2014

Two Day Workshop on Android


</EditText>
< EditText
android:id="@+id/editText2"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView2"
android:layout_alignBottom="@+id/textView2"
android:layout_toRightOf="@+id/button1" />
</RelativeLayout>
WebServicesTest . Java
package com.mahesh.xml;
import ........................;
public class WebServicesTest extends Activity{
@Override
protected void onCreate(Bundle
savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void Login(View v){
try{
// Calling Restful WebServices as a path Params
DefaultHttpClient httpClient=new
DefaultHttpClient();
// we need to add the request type get | post if
it is a get request call HttpGet if it is
Post request HttpPost
// Here specify your webservice URL address my
web service is running on this
IPAddress and the port Number and i am passing
the parameters as a path parameters
HttpGet get=new
HttpGet("http://192.168.137.1:8888//rest/welc
ome/mahesh/bened");
/* In case of Query Paramaters

59

* HttpGet get=new
HttpGet("http://192.168.137.1:8888//rest/welc
ome?
name=mahesh&pass=bened);
*
* InCase of Matrix Parameters
*
* HttpGet get=new
HttpGet("http://192.168.137.1:8888//rest/welc
ome/name:mahesh;pass=bened);
*
*/
// Here I am getting the text/plain as a response
we need add as header
get.addHeader("accept", "text/plain");
/*
* Header are different based on your response if
your getting a image file
* get.addHeader("accept","image/jpg");
* if ur getting a XML as Output
* get.Header("accept","application/xml");
* if ur getting a JSON as Output
* get.Header("accept","application/json");
*/
HttpResponse response=httpClient.execute(get);
InputStream
isr=response.getEntity().getContent();
int i=isr.read();
String msg="";
while(i!=-1){
msg=msg+(char)i;
i=isr.read();
}
Toast.makeText(getApplicationContext(),
"Response from the server is :"+msg,
Toast.LENGTH_LONG).show();
}catch(Exception e){
e.printStackTrace();
13/03/2014

Two Day Workshop on Android


}}}
If you are calling a Java or Other
WebComponent :
public void Login(View v){
URL u=new
URL("http://192.168.137.1:8888//Android?una
me=mahesh&pass=bened");
InputStream
isr=response.getEntity().getContent();
int i=isr.read();
String msg="";
while(i!=-1){
msg=msg+(char)i;
i=isr.read();
}
Toast.makeText(getApplicationContext(),
"Response from the server is :"+msg,
Toast.LENGTH_LONG).show();
}
To Work with above application you need add
the following permissions in the
AndroidManifest.xml file
<uses-permission
android:name="android.permission.INTERNET"/
>
<uses-permission
android:name="android.permission.ACCESS_WIF
I_STATE"/>
<uses-permission
android:name="android.permission.CHANGE_WI
FI_STATE"/>
Working With WebView:
A View that displays web pages. This class is the
basis upon which you can roll your own web
browser or simply display some online content
within your Activity. It uses the WebKit
rendering

60

engine to display web pages and includes


methods to navigate forward and backward
through a history,
zoom in and out, perform text searches and
more.
To enable the built-in zoom, set
WebSettings.setBuiltInZoomControls(boolean)
(introduced in API
version 3).
Note that, in order for your Activity to access the
Internet and load web pages in a WebView, you
must
add the INTERNET permissions to your Android
Manifest file:
<uses-permission
android:name="android.permission.INTERNET"
/>
<uses-permission
android:name="android.permission.ACCESS_WIF
I_STATE"/>
<uses-permission
android:name="android.permission.CHANGE_WI
FI_STATE"/>
Sample Application on WebView :
Take the input from the user through edittext
and when you press go button load
the web page in the webview
WebServicesTest.java
WebServicesTest.java
package com.mahesh.xml;
import ..................;
public class WebServicesTest extends Activity{
@Override
protected void onCreate(Bundle
savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
13/03/2014

Two Day Workshop on Android


}
public void Go(View v){
EditText
et1=(EditText)findViewById(R.id.editText1);
WebView
wv=(WebView)findViewById(R.id.webView1);
wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().setBuiltInZoomControls(true);
wv.getSettings().setUseWideViewPort(true);
wv.getSettings().setAllowFileAccess(true);
wv.getSettings().getLoadsImagesAutomatically();
wv.setDownloadListener(new
DownloadListener() {
@Override
public void onDownloadStart(String arg0, String
arg1, String arg2,
String arg3, long arg4) {
Intent i=new Intent(Intent.ACTION_VIEW);
startActivity(i);
}
});
final ProgressDialog pdialog=new
ProgressDialog(this);
pdialog.setTitle("Message...");
pdialog.setIcon(R.drawable.ic_launcher);
pdialog.setMessage("Pls wait page is
loading.......");
pdialog.setProgressStyle(ProgressDialog.STYLE_S
PINNER);
wv.setWebViewClient(new WebViewClient(){
@Override
public void onPageFinished(WebView view,
String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
pdialog.dismiss();
}
@Override

61

public void onPageStarted(WebView view,


String url,
Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
pdialog.show();
}
@Override
public boolean
shouldOverrideUrlLoading(WebView view, String
url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return super.shouldOverrideUrlLoading(view,
url);
}
});
wv.loadUrl("http://"+et1.getText().toString());
}}
Working With Wifi :
WifiManager :
This class provides the primary API for managing
all aspects of Wi-Fi
connectivity. Get an instance of this class by
calling
Context.getSystemService(Context.WIFI_SERVIC
E). It deals with several categories of items:
The list of configured networks. The list can be
viewed and updated, and attributes of individual
entries can be modified.
The currently active Wi-Fi network, if any.
Connectivity can be established or torn down,
and
dynamic information about the state of the
network can be queried.
Results of access point scans, containing
enough information to make decisions about
what
13/03/2014

Two Day Workshop on Android


access point to connect to.
It defines the names of various Intent actions
that are broadcast upon any sort of change in
WiFi state. To work with this application you need
to add the following persmissions in the
manifest.xml
<uses-permission
android:name="android.permission.ACCESS_WIF
I_STATE"/>
<uses-permission
android:name="android.permission.CHANGE_WI
FI_STATE"/>
WifiConfiguration :
A class representing a configured Wi-Fi network,
including the security configuration.
Sample Code to Work With Wifi :
wifi.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/ap
k/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="114dp"
android:layout_marginTop="27dp"
android:onClick="Wifi"
android:text = "Wifi"
/>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"

62

android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/toggleButton1"
android:layout_marginLeft="95dp"
android:layout_marginTop="55dp"
android:onClick="getWifiList"
android:text = "getWifiList" />
</RelativeLayout>
WifiExample . java
package com.mahesh.xml;
import ..................;
public class WifiExample extends Activity {
WifiManager wManager;
Button button;
@Override
protected void onCreate(Bundle
savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
wManager=(WifiManager)getSystemService(Con
text.WIFI_SERVICE);
setContentView(R.layout.wifi);
button=(Button)findViewById(R.id.toggleButton
1);
if(wManager.getWifiState()==wManager.WIFI_S
TATE_DISABLED){
button.setText("Wifi On");
}else
if(wManager.getWifiState()==wManager.WIFI_S
TATE_ENABLED){
button.setText("Wifi Off");
}
}
public void Wifi(View v){
if(wManager.getWifiState()==wManager.WIFI_S
TATE_DISABLED){
wManager.setWifiEnabled(true);
button.setText("Wifi Off");
13/03/2014

Two Day Workshop on Android


}else
if(wManager.getWifiState()==wManager.WIFI_S
TATE_ENABLED){
wManager.setWifiEnabled(false);
button.setText("Wifi On");
}
}
public void getWifiList(View v){
List<WifiConfiguration>
wificonfig=wManager.getConfiguredNetworks();
for(WifiConfiguration wifi:wificonfig){
Toast.makeText(getApplicationContext(), " SSID :
"+wifi.SSID +" \n
BSSID :"+wifi.BSSID+"\n Status :"+wifi.status+"\n
Priority
:"+wifi.priority,Toast.LENGTH_LONG).show();
}
}
}
Notification Manager :
class to notify the user of events that happen.
This is how you tell the user that something has
happened in the background.
Notifications can take different forms:
A persistent icon that goes in the status bar
and is accessible through the launcher, (when
the
user selects it, a designated Intent can be
launched),
Turning on or flashing LEDs on the device, or
Alerting the user by flashing the backlight,
playing a sound, or vibrating.
Each of the notify methods takes an int id
parameter. This id identifies this notification
from your app
to the system, so that id should be unique within
your app. If you call one of the notify methods
with an

63

id that is currently active and a new set of


notification parameters, it will be updated. For
example, if
you pass a new status bar icon, the old icon in
the status bar will be replaced with the new one.
This is
also the same id you pass to the cancel(int)
method to clear this notification.
You do not instantiate this class directly; instead,
retrieve it through getSystemService(String).
Notification :
Notification
A Notification object defines the details of the
notification message that is displayed in the
status bar
and "Notifications" window, and any other alert
settings, such as sounds and blinking lights.
A status bar notification requires all of the
following:
An icon for the status bar
A title and expanded message for the
expanded view (unless you define a custom
expanded
view)
A PendingIntent, to be fired when the
notification is selected
Optional settings for the status bar notification
include:
A ticker-text message for the status bar
An alert sound
A vibrate setting
A flashing LED setting
Vibrator :
Class that operates the vibrator on the device.
If your process exits, any vibration you started
with will stop.
You do not instantiate this class directly; instead,
retrieve it through getSystemService(String).
13/03/2014

Two Day Workshop on Android


Vibrator
vibrator=(Vibrator)getSystemService(Context.VI
BRATOR_SERVICE);
Need to add the following permission in the
AndroidManifest.xml
<uses-permission
android:name="android.permission.VIBRATE"/>
Develop a sample code to display notification
and Vibrate the device when wifi is switch on
or
wifi switch off for the above application.
package com.mahesh.xml;
import java.util.List;
import ............................;
public class WifiExample extends Activity {
WifiManager wManager;
Button button;
NotificationManager nManager;
Notification notification;
Vibrator vibrator;
@Override
protected void onCreate(Bundle
savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.wifi);
wManager=(WifiManager)getSystemService(Con
text.WIFI_SERVICE);
button=(Button)findViewById(R.id.toggleButton
1);
nManager=(NotificationManager)getSystemServ
ice(Context.NOTIFICATION_SERVICE);
vibrator=(Vibrator)getSystemService(Context.VI
BRATOR_SERVICE);
if(wManager.getWifiState()==wManager.WIFI_S
TATE_DISABLED){
button.setText("Wifi On");

64

}else
if(wManager.getWifiState()==wManager.WIFI_S
TATE_ENABLED){
button.setText("Wifi Off");
}
}
public void Wifi(View v){
if(wManager.getWifiState()==wManager.WIFI_S
TATE_DISABLED){
wManager.setWifiEnabled(true);
button.setText("Wifi Off");
notification=new
Notification(R.drawable.ic_launcher, "Wifi State
Changed",
System.currentTimeMillis());
notification.setLatestEventInfo(getBaseContext()
, "Wifi State Changed","Wifi
Enabled", getPendingIntent());
nManager.notify(1, notification);
vibrator.vibrate(1000);
}else
if(wManager.getWifiState()==wManager.WIFI_S
TATE_ENABLED){
wManager.setWifiEnabled(false);
button.setText("Wifi On");
notification=new
Notification(R.drawable.ic_launcher, "Wifi State
Changed", System.currentTimeMillis());
notification.setLatestEventInfo(getBaseContext()
, "Wifi State
Changed","Wifi Disabled", getPendingIntent());
nManager.notify(1, notification);
vibrator.vibrate(1000);
}
}
private PendingIntent getPendingIntent() {
Intent i=new Intent(getBaseContext(),
WifiExample.class);
13/03/2014

Two Day Workshop on Android


PendingIntent
pi=PendingIntent.getActivity(getBaseContext(),
0,i, 0);
return pi;
}
public void getWifiList(View v){
List<WifiConfiguration>
wificonfig=wManager.getConfiguredNetworks();
for(WifiConfiguration wifi:wificonfig){
Toast.makeText(getApplicationContext(), " SSID :
"+wifi.SSID +" \n
BSSID :"+wifi.BSSID+"\n Status :"+wifi.status+"\n
Priority
:"+wifi.priority,Toast.LENGTH_LONG).show();
}
}
}
LocationManager :
This class provides access to the system location
services. These services allow applications to
obtain periodic updates of the device's
geographical location, or to fire an applicationspecified Intent
when the device enters the proximity of a given
geographical location. You do not instantiate
this class
directly; instead, retrieve it through
Context.getSystemService(Context.LOCATION_S
ERVICE).
you need to add the following permissions in
AndroidManifest.xml
<uses-permission
android:name="android.permission.ACCESS_FIN
E_LOCATION"/>
<uses-permission
android:name="android.permission.ACCESS_MO
CK_LOCATION"/>

65

public void requestLocationUpdates ( String


provider, long minTime, float minDistance,
LocationListener listener)
Registers the current activity to be notified
periodically by the named provider. Periodically,
the
supplied LocationListener will be called with the
current Location or with status updates.
It may take a while to receive the most recent
location. If an immediate location is required,
applications may use the
getLastKnownLocation(String) method.
In case the provider is disabled by the user,
updates will stop, and the
onProviderDisabled(String)
method will be called. As soon as the provider is
enabled again, the onProviderEnabled(String)
method
will be called and location updates will start
again.
The frequency of notification may be controlled
using the minTime and minDistance parameters.
If
minTime is greater than 0, the LocationManager
could potentially rest for minTime milliseconds
between location updates to conserve power. If
minDistance is greater than 0, a location will
only be
broadcasted if the device moves by minDistance
meters. To obtain notifications as frequently as
possible, set both parameters to 0.
Background services should be careful about
setting a sufficiently high minTime so that the
device
doesn't consume too much power by keeping
the GPS or wireless radios on all the time. In
particular,
values under 60000ms are not recommended.
13/03/2014

Two Day Workshop on Android


The calling thread must be a Looper thread such
as the main thread of the calling Activity.
Parameters
provider the name of the provider with which to
register
minTime
the minimum time interval for notifications, in
milliseconds. This field is only used as a
hint to conserve power, and actual time
between location updates may be greater or
lesser than this value.
minDistance the minimum distance interval for
notifications, in meters
listener a {#link LocationListener} whose
onLocationChanged(Location) method will be
called
for each location update
Sample Code to Work with
LocationBasedServices :
package com.mahesh.xml;
import ..............................;
public class LocationTest extends Activity{
LocationManager lManager;
@Override
protected void onCreate(Bundle
savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
lManager=(LocationManager)getSystemService(
Context.LOCATION_SERVICE);
lManager.requestLocationUpdates(LocationMan
ager.GPS_PROVIDER, 1000, 1,
new LocationListener() {
@Override
public void onStatusChanged(String arg0, int
arg1, Bundle arg2) {
// TODO Auto-generated method stub

66

}
@Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void onLocationChanged(Location l) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"Latitude value
is :"+l.getLatitude()+"Logitude value is
:"+l.getLongitude(),
Toast.LENGTH_SHORT).show();
} }); }
public void getLocation(View v){
Location
l=lManager.getLastKnownLocation(LocationMan
ager.GPS_PROVIDER);
Toast.makeText(getApplicationContext(),
"Latitude value is :"+l.getLatitude()
+"Logitude value is :"+l.getLongitude(),
Toast.LENGTH_SHORT).show();
}}
ListActivity :
An activity that displays a list of items by binding
to a data source such as an array or Cursor,
and exposes event handlers when the user
selects an item.
ListActivity hosts a ListView object that can be
bound to different data sources, typically either
an
array or a Cursor holding query results. Binding,
screen layout, and row layout are discussed in
the
13/03/2014

Two Day Workshop on Android


following sections.
Screen Layout
ListActivity has a default layout that consists of a
single, full-screen list in the center of the screen.
However, if you desire, you can customize the
screen layout by setting your own view layout
with
setContentView() in onCreate(). To do this, your
own view MUST contain a ListView object with
the
id "@android:id/list" (or list if it's in code)
Optionally, your custom view can contain
another view object of any type to display when
the list view
is empty. This "empty list" notifier must have an
id "android:empty". Note that when an empty
view is
present, the list view will be hidden when there
is no data to display.
The following code demonstrates an (ugly)
custom screen layout. It has a list with a green
background,
and an alternate red "no data" message.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/ap
k/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="8dp"
android:paddingRight="8dp">
<ListView android:id="@id/android:list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#00FF00"
android:layout_weight="1"
android:drawSelectorOnTop="false"/>

67

<TextView id="@id/android:empty"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FF0000"
android:text="No data"/>
</LinearLayout>
Base Adapter :
Common base class of common implementation
for an Adapter that can be used in both
ListView (by implementing the specialized
ListAdapter interface} and Spinner (by
implementing the
specialized SpinnerAdapter interface.
Sample Program to display image names in
SDCARD using ListActivity:
package com.mahesh.xml;
import java.io.File;
import ..................;
public class ListActivityTest extends ListActivity{
@Override
protected void onCreate(Bundle
savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
String
path=Environment.getExternalStorageDirectory(
)+"/images";
File f=new File(path);
if(f.exists()){
String[] images=f.list();
ArrayAdapter<String> adapter=new
ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_gallery_item,images);
setListAdapter(adapter);
}else{
Toast.makeText(getApplicationContext(), "There
is no file with the given
path",Toast.LENGTH_LONG).show();
13/03/2014

Two Day Workshop on Android


}
}
}
Sample program on creating own CustomView
Adapter and display image , image name and
image size from SDCARD/images directory:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/ap
k/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
< ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/imageView1"
android:textAppearance="?android:attr/textApp
earanceMedium" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_toRightOf="@+id/imageView1"
android:textAppearance="?android:attr/textApp
earanceMedium" />
</RelativeLayout>
ListActivityImagesActivity. Java
package com.mahesh.listimages;

68

import ................;
public class ListActivityImagesActivity extends
ListActivity implements
AdapterView.OnItemSelectedListener{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new MyAdapter(this));
getListView().setOnItemSelectedListener(this);
}
class MyAdapter extends BaseAdapter{
private LayoutInflater inflater;
private Bitmap icon1;
private String[] files;
String path;
public MyAdapter(ListActivityImagesActivity laia)
{
inflater=LayoutInflater.from(laia);
icon1=BitmapFactory.decodeResource(getResou
rces(),
R.drawable.ic_launcher);
path=Environment.getExternalStorageDirectory(
)+"/images";
File f=new File(path);
files=f.list();
}
public int getCount() {
// TODO Auto-generated method stub
return files.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
13/03/2014

Two Day Workshop on Android


return position;
}
public View getView(int position, View view,
ViewGroup view_group) {
// TODO Auto-generated method stub
view=inflater.inflate(R.layout.main,null);
TextView tv1=(TextView)
view.findViewById(R.id.textView1);
TextView tv2=(TextView)
view.findViewById(R.id.textView2);
ImageView
iv1=(ImageView)view.findViewById(R.id.imageVi
ew1);
tv1.setText(files[position].toString());
File f=new File(path+"/"+files[position]);
tv2.setText(f.length()/1024+"kb");
iv1.setImageURI(Uri.fromFile(f));
return view;
}
}
public void onItemSelected(AdapterView<?>
arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "from
on Item Selected... ",
Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?>
arg0) {
// TODO Auto-generated method stub
}
}
Gallery :
A view that shows items in a center-locked,
horizontally scrolling list.

69

The default values for the Gallery assume you


will be using Theme_galleryItemBackground as
the
background for each View given to the Gallery
from the Adapter. If you are not doing this, you
may
need to adjust some Gallery properties, such as
the spacing.
Views given to the Gallery should use
Gallery.LayoutParams as their layout parameters
type.
Sample Code to work with Gallery and
CustomView Adapter:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/ap
k/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
< ImageView
android:id="@+id/imageView1"
android:paddingLeft = "10px"
android:paddingRight = "10px"
android:layout_width = "100px"
android:layout_height = "100px"
android:src="@drawable/ic_launcher" />
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/imageView1"
android:layout_marginLeft="27dp" />
</RelativeLayout>
Gallery.xml :
<?xml version="1.0" encoding="utf-8"?>
13/03/2014

Two Day Workshop on Android


<RelativeLayout
xmlns:android="http://schemas.android.com/ap
k/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Gallery
android:id="@+id/gallery1"
android:layout_width = "300px"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="16dp" />
</RelativeLayout>
GalleryTestExActivity .java
package com.mahesh.gallery;
import ...................................;
public class GalleryTestExActivity extends
Activity implements OnItemSelectedListener {
ArrayList<String> images_names=new
ArrayList<String>();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery);
Gallery g=(Gallery)findViewById(R.id.gallery1);
g.setAdapter(new MyAdapter(this));
g.setOnItemSelectedListener(this);
}
public void onItemSelected(AdapterView<?>
adview, View view, int arg2,
long arg3) {
CheckBox
cb1=(CheckBox)findViewById(R.id.checkBox1);
if(cb1.isChecked()){
images_names.add(cb1.getText().toString());

70

Toast.makeText(getApplicationContext(),cb1.get
Text(),Toast.LENGTH_LONG).show();
}
}
public void onNothingSelected(AdapterView<?>
arg0) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
images_names.size(),Toast.LENGTH_LONG).sho
w();
}}
MyAdapter.java :
package com.mahesh.gallery;
import ..................;
public class MyAdapter extends BaseAdapter{
GalleryTestExActivity gta;
LayoutInflater inflater;
String
path=Environment.getExternalStorageDirectory(
)+"/images";
File f=new File(path);
String[] images=f.list();
public MyAdapter(GalleryTestExActivity gtea) {
gta=gtea;
inflater=LayoutInflater.from(gtea);
}
public int getCount() {
return images.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View view,
ViewGroup arg2) {
view=inflater.inflate(R.layout.main, null);
13/03/2014

Two Day Workshop on Android


ImageView
iv1=(ImageView)view.findViewById(R.id.imageVi
ew1);
CheckBox
cb1=(CheckBox)view.findViewById(R.id.checkBo
x1);
cb1.setText(images[position].toString());
File f=new File(path+"/"+images[position]);
Uri uri=Uri.fromFile(f);
iv1.setImageURI(uri);
return view;
}
}
MediaPlayer :
MediaPlayer class can be used to control
playback of audio/video files and streams. An
example
on how to use the methods in this class can be
found in VideoView. Please see Audio and Video
for
additional help using MediaPlayer.
Important methods :
Method Name Valid Sates Invalid States
Comments
isPlaying
{Idle, Initialized,
Prepared, Started,
Paused, Stopped,
PlaybackCompleted}
{Error}
Successful invoke of this method in a valid state
does not change the state. Calling this method in
an invalid state transfers the object to the Error
state.
pause {Started, Paused}
{Idle, Initialized,
Prepared,
Stopped,

71

PlaybackComplet
ed, Error}
Successful invoke of this method in a valid state
transfers the object to the Paused state. Calling
this method in an invalid state transfers the
object
to the Error state.
prepare {Initialized,
Stopped}
{Idle, Prepared,
Started, Paused,
PlaybackComplet
ed, Error}
Successful invoke of this method in a valid state
transfers the object to the Prepared state.
Calling
this method in an invalid state throws an
IllegalStateException.
setDataSource {Idle}
{Initialized,
Prepared, Started,
Paused, Stopped,
PlaybackComplet
ed, Error}
Successful invoke of this method in a valid state
transfers the object to the Initialized state.
Callingthis method in an invalid state throws an
IllegalStateExceptionsetVolume
{Idle, Initialized,Stopped, Prepared,
Started, Paused,PlaybackCompleted}
{Error} Successful invoke of this method does
not change the state start{Prepared,
Started,Paused,PlaybackComplete}
{Idle, Initialized,Stopped, Error}
Successful invoke of this method in a valid state
transfers the object to the Started state. Calling
this method in an invalid state transfers the
object to the Error state.stop {Prepared, Started,
13/03/2014

Two Day Workshop on Android


Stopped, Paused, PlaybackCompleted}
{Idle, Initialized,Error}
Successful invoke of this method in a valid state
transfers the object to the Stopped state. Calling
this method in an invalid state transfers the
object
to the Error state

Contact Us
GEOSYS ENTERPRISE SOLUTIONS
Corporate Head Office: 6-3-841/A/2/C-1, III
Floor, Arun Aditya Building, Ameerpet,
Hyderabad, AP-500016
Contact Number:
040-65522333
94938806670
Email Address:
info@geosys.co.in

72

13/03/2014

Você também pode gostar