Android PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 321

1|Page APS Microtech Pvt Ltd

What is Android

Before learning all topics of android, it is required to know what is android.

Android is a software package and linux based operating system for mobile devices such as
tablet computers and smartphones.

It is developed by Google and later the OHA (Open Handset Alliance). Java language is mainly
used to write the android code even though other languages can be used.

The goal of android project is to create a successful real-world product that improves the mobile
experience for end users.

There are many code names of android such as Lollipop, Kitkat, Jelly Bean, Ice cream
Sandwich, Froyo, Ecliar, Donut etc which is covered in next page.

What is Open Handset Alliance (OHA)


It's a consortium of 84 companies such as google, samsung, AKM, synaptics, KDDI, Garmin,
Teleca, Ebay, Intel etc.

It was established on 5th November, 2007, led by Google. It is committed to advance open
standards, provide services and deploy handsets using the Android Plateform.

Features of Android
After learning what is android, let's see the features of android. The important features of android
are given below:

1) It is open-source.

2) Anyone can customize the Android Platform.

3) There are a lot of mobile applications that can be chosen by the consumer.

Email:[email protected]
2|Page APS Microtech Pvt Ltd

4) It provides many interesting features like weather details, opening screen, live RSS (Really
Simple Syndication) feeds etc.

It provides support for messaging services(SMS and MMS), web browser, storage (SQLite),
connectivity (GSM, CDMA, Blue Tooth, Wi-Fi etc.), media, handset layout etc.

Categories of Android applications


There are many android applications in the market. The top categories are:

 Entertainment
 Tools
 Communication
 Productivity
 Personalization
 Music and Audio
 Social
 Media and Video
 Travel and Local etc.

Email:[email protected]
3|Page APS Microtech Pvt Ltd

History of Android
The history and versions of android are interesting to know. The code names of android ranges
from A to J currently, such as Aestro, Blender, Cupcake, Donut, Eclair, Froyo, Gingerbread,
Honeycomb, Ice Cream Sandwitch, Jelly Bean, KitKat and Lollipop. Let's understand the
android history in a sequence.

1) Initially, Andy Rubin founded Android Incorporation in Palo Alto, California, United States
in October, 2003.

2) In 17th August 2005, Google acquired android Incorporation. Since then, it is in the subsidiary
of Google Incorporation.

3) The key employees of Android Incorporation are Andy Rubin, Rich Miner, Chris White
and Nick Sears.

4) Originally intended for camera but shifted to smart phones later because of low market for
camera only.

5) Android is the nick name of Andy Rubin given by coworkers because of his love to robots.

6) In 2007, Google announces the development of android OS.

7) In 2008, HTC launched the first android mobile.

Android Versions, Codename and API


Let's see the android versions, codenames and API Level provided by Google.

Version Code name API Level


1.5 Cupcake 3
1.6 Donut 4
2.1 Éclair 7
2.2 Froyo 8
2.3 Gingerbread 9 and 10
3.1 and 3.3 Honeycomb 12 and 13
4.0 Ice Cream Sandwitch 15
16, 17 and
4.1, 4.2 and 4.3 Jelly Bean
18
4.4 KitKat 19

Email:[email protected]
4|Page APS Microtech Pvt Ltd

5.0 Lollipop 21

Android Architecure
android architecture or Android software stack is categorized into five parts:

1. linux kernel
2. native libraries (middleware),
3. Android Runtime
4. Application Framework
5. Applications

Let's see the android architecture first.

1) Linux kernel

Email:[email protected]
5|Page APS Microtech Pvt Ltd

It is the heart of android architecture that exists at the root of android architecture. Linux kernel
is responsible for device drivers, power management, memory management, device management
and resource access.

2) Native Libraries
On the top of linux kernel, their are Native libraries such as WebKit, OpenGL, FreeType,
SQLite, Media, C runtime library (libc) etc.

The WebKit library is responsible for browser support, SQLite is for database, FreeType for font
support, Media for playing and recording audio and video formats.

3) Android Runtime
In android runtime, there are core libraries and DVM (Dalvik Virtual Machine) which is
responsible to run android application. DVM is like JVM but it is optimized for mobile devices.
It consumes less memory and provides fast performance.

4) Android Framework
On the top of Native libraries and android runtime, there is android framework. Android
framework includes Android API's such as UI (User Interface), telephony, resources, locations,
Content Providers (data) and package managers. It provides a lot of classes and interfaces for
android application development.

5) Applications
On the top of android framework, there are applications. All applications such as home, contact,
settings, games, browsers are using android framework that uses android runtime and libraries.
Android runtime and native libraries are using linux kernal.

Email:[email protected]
6|Page APS Microtech Pvt Ltd

Android Core Building Blocks

An android component is simply a piece of code that has a well defined life cycle e.g. Activity,
Receiver, Service etc.

The core building blocks or fundamental components of android are activities, views, intents,
services, content providers, fragments and AndroidManifest.xml.

Activity

An activity is a class that represents a single screen. It is like a Frame in AWT.

View

A view is the UI element such as button, label, text field etc. Anything that you see is a view.

Intent

Intent is used to invoke components. It is mainly used to:

 Start the service


 Launch an activity
 Display a web page
 Display a list of contacts
 Broadcast a message
 Dial a phone call etc.

For example, you may write the following code to view the webpage.

Email:[email protected]
7|Page APS Microtech Pvt Ltd

Intent intent=new Intent(Intent.A


intent.setData(Uri.parse("http://w
startActivity(intent);

Service

Service is a background process that can run for a long time.

There are two types of services local and remote. Local service is accessed from within the
application whereas remote service is accessed remotely from other applications running on the
same device.

Content Provider

Content Providers are used to share data between the applications.

Fragment

Fragments are like parts of activity. An activity can display one or more fragments on the screen
at the same time.

AndroidManifest.xml

It contains informations about activities, content providers, permissions etc. It is like the
web.xml file in Java EE.

Android Virtual Device (AVD)

It is used to test the android application without the need for mobile or tablet etc. It can be
created in different configurations to emulate different types of real devices.

Email:[email protected]
8|Page APS Microtech Pvt Ltd

Android Emulator
Android Emulator is used to run, debug and test the android application. If you don't have the
real device, it can be the best way to run, debug and test the application.

It uses an open source processor emulator technology called QEMU.

The emulator tool enables you to start the emulator from the command line. You need to write:

emulator -avd <AVD NAME>

In case of Eclipse IDE, you can create AVD by Window menu > AVD Manager > New.

In the given image, you can see the android emulator, it displays the output of the hello android
example.

Email:[email protected]
9|Page APS Microtech Pvt Ltd

Install Android
Android supports java, c++, c# etc. language to develop android applications. Java is the
officially supported language for android. All the android examples of this site is developed
using Java language and Eclipse IDE.

Here, we are going to tell you, the required softwares to develop android applications using
Eclipse IDE.

There are two ways to install android.

1. By ADT Bundle
2. By Setup Eclipse Manually

1) By ADT Bundle
It is the simplest technique to install required softwares for android application. It includes:

 Eclipse IDE
 Android SDK
 Eclipse Plugin

Click me to download android adt bundle

If you download the ADT from android site, you don't need to have eclipse IDE, android SDK
and eclipse Plugin because it is already included in adt bundle.

If you have downloaded the ADT bundle, unjar it, go to eclipse IDE and start the eclipse by
clicking on the eclipse icon. You don't need to do any extra steps here.

If eclipse is not started, paste the JRE directory inside the eclipse directory.

2) By set up eclipse manually

Email:[email protected]
10 | P a g e APS Microtech Pvt Ltd

How to setup Android for Eclipse IDE


In this page, you will learn what softwares are required for running an android application on
eclipse IDE. Here, you will be able to learn how to install the android SDK and ADT plugin for
Eclipse IDE. Let's see the list of software required to setup android for eclipse IDE manually.

1. Install the JDK


2. Download and install the Eclipse for developing android application
3. Download and Install the android SDK
4. Intall the ADT plugin for eclipse
5. Configure the ADT plugin
6. Create the AVD
7. Create the hello android application

1) Install the Java Development Kit (JDK)


For creating android application, JDK must be installed if you are developing the android
application with Java language. download the JDK

2) Download and install the Eclipse IDE


For developing the android application using eclipse IDE, you need to install the Eclipse. you
can download it from this location download the Eclipse. Eclipse classic version is recommended
but we are using the Eclipse IDE for JavaEE Developers.

3) Download and install the android SDK


First of all, download the android SDK. In this example we have installed the android SDK for
windows (.exe version).

Now double click on the exe file, it will be installed. I am using the android 2.2 version here.

4) Download the ADT plugin for eclipse

Email:[email protected]
11 | P a g e APS Microtech Pvt Ltd

ADT (Android Development Tools) is required for developing the android application in the
eclipse IDE. It is the plugin for Eclipse IDE that is designed to provide the integrated
environment.

For downloading the ADT, you need to follow these steps:

1) Start the eclipse IDE, then select Help > Install new software...

2) In the work with combo box, write https://dl-ssl.google.com/android/eclipse/

3) select the checkbox next to Developer Tools and click next

4) You will see, a list of tools to be downloaded here, click next

5) click finish

6) After completing the installation, restart the eclipse IDE

5) Configuring the ADT plugin


Email:[email protected]
12 | P a g e APS Microtech Pvt Ltd

After the installing ADT plugin, now tell the eclipse IDE for your android SDK location. To do
so:

1. Select the Window menu > preferences


2. Now select the android from the left panel. Here you may see a dialog box asking if you
want to send the statistics to the google. Click proceed.
3. Click on the browse button and locate your SDK directory e.g. my SDK location is
C:\Program Files\Android\android-sdk .
4. Click the apply button then OK.

6) Create an Android Virtual Device (AVD)


For running the android application in the Android Emulator, you need to create and AVD. For
creating the AVD:

1. Select the Window menu > AVD Manager


2. Click on the new button, to create the AVD
3. Now a dialog appears, write the AVD name e.g. myavd. Now choose the target android
version e.g. android2.2.
4. click the create AVD

7) create and run the simple android example


Visit the next page to create first android application.

Email:[email protected]
13 | P a g e APS Microtech Pvt Ltd

How to make android apps


In this page, you will know how to create the simple hello android application. We are creating
the simple example of android using the Eclipse IDE. For creating the simple example:

1. Create the new android project


2. Write the message (optional)
3. Run the android application

Hello Android Example

You need to follow the 3 steps mentioned above for creating the Hello android application.

1) Create the New Android project

For creating the new android project:

1) Select File > New > Project...

2) Select the android project and click next

Email:[email protected]
14 | P a g e APS Microtech Pvt Ltd

3) Fill the Details in this dialog box and click finish

Email:[email protected]
15 | P a g e APS Microtech Pvt Ltd

Now an android project have been created. You can explore the android project and see the
simple program, it looks like this:

Email:[email protected]
16 | P a g e APS Microtech Pvt Ltd

2) Write the message

For writing the message we are using the TextView class. Change the onCreate method as:

1. TextView textview=new TextView(this);


2. textview.setText("Hello Android!");
3. setContentView(textview);

Let's see the full code of MainActivity.java file.

1. package com.example.helloandroid;
2. import android.os.Bundle;
3. import android.app.Activity;
4. import android.view.Menu;
5. import android.widget.TextView;
6. public class MainActivity extends Activity {
7. @Override
8. protected void onCreate(Bundle savedInstanceState) {
9. super.onCreate(savedInstanceState);
10. TextView textview=new TextView(this);

Email:[email protected]
17 | P a g e APS Microtech Pvt Ltd

11. textview.setText("Hello Android!");


12. setContentView(textview);
13. }
14. @Override
15. public boolean onCreateOptionsMenu(Menu menu) {
16. // Inflate the menu; this adds items to the action bar if it is present.
17. getMenuInflater().inflate(R.menu.activity_main, menu);
18. return true;
19. }
20. }

To understand the first android application, visit the next page (internal details of hello
android example).

3) Run the android application


To run the android application: Right click on your project > Run As.. > Android Application

The android emulator might take 2 or 3 minutes to boot. So please have patience. After booting
the emulator, the eclipse plugin installs the application and launches the activity. You will see
something like this:

Email:[email protected]
18 | P a g e APS Microtech Pvt Ltd

Email:[email protected]
19 | P a g e APS Microtech Pvt Ltd

Internal Details of Hello Android Example


Here, we are going to learn the internal details or working of hello android example.

Android application contains different components such as java source code, string resources,
images, manifest file, apk file etc. Let's understand the project structure of android application.

Java Source Code

Let's see the java source file created by the Eclipse IDE:

File: MainActivity.java

Email:[email protected]
20 | P a g e APS Microtech Pvt Ltd

1. package com.example.helloandroid;
2. import android.os.Bundle;
3. import android.app.Activity;
4. import android.view.Menu;
5. import android.widget.TextView;
6. public class MainActivity extends Activity {//(1)
7. @Override
8. protected void onCreate(Bundle savedInstanceState) {//(2)
9. super.onCreate(savedInstanceState);
10.
11. setContentView(R.layout.activity_main);//(3)
12. }
13. @Override
14. public boolean onCreateOptionsMenu(Menu menu) {//(4)
15. // Inflate the menu; this adds items to the action bar if it is present.
16. getMenuInflater().inflate(R.menu.activity_main, menu);
17. return true;
18. }
19. }

(1) Activity is a java class that creates and default window on the screen where we can place
different components such as Button, EditText, TextView, Spinner etc. It is like the Frame of
Java AWT.

It provides life cycle methods for activity such as onCreate, onStop, OnResume etc.

(2) The onCreate method is called when Activity class is first created.

(3) The setContentView(R.layout.activity_main) gives information about our layout resource.


Here, our layout resources are defined in activity_main.xml file.

File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6. <TextView
7. android:layout_width="wrap_content"
8. android:layout_height="wrap_content"
9. android:layout_centerHorizontal="true"
10. android:layout_centerVertical="true"
11. android:text="@string/hello_world" />
12. </RelativeLayout>

Email:[email protected]
21 | P a g e APS Microtech Pvt Ltd

As you can see, a textview is created by the framework automatically. But the message for this
string is defined in the strings.xml file. The @string/hello_world provides information about the
textview message. The value of the attribute hello_world is defined in the strings.xml file.

File: strings.xml

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


2. <resources>
3. <string name="app_name">helloandroid</string>
4. <string name="hello_world">Hello world!</string>
5. <string name="menu_settings">Settings</string>
6. </resources>

You can change the value of the hello_world attribute from this file.

Generated R.java file

It is the auto-generated file that contains IDs for all the resources of res directory. It is generated
by aapt(Android Asset Packaging Tool). Whenever you create any component on activity_main,
a corresponding ID is created in the R.java file which can be used in the Java Source file later.

File: R.java

1. /* AUTO-GENERATED FILE. DO NOT MODIFY.


2. *
3. * This class was automatically generated by the
4. * aapt tool from the resource data it found. It
5. * should not be modified by hand.
6. */
7. package com.example.helloandroid;
8. public final class R {
9. public static final class attr {
10. }
11. public static final class drawable {
12. public static final int ic_launcher=0x7f020000;
13. }
14. public static final class id {
15. public static final int menu_settings=0x7f070000;
16. }
17. public static final class layout {
18. public static final int activity_main=0x7f030000;
19. }
20. public static final class menu {
21. public static final int activity_main=0x7f060000;
22. }

Email:[email protected]
22 | P a g e APS Microtech Pvt Ltd

23. public static final class string {


24. public static final int app_name=0x7f040000;
25. public static final int hello_world=0x7f040001;
26. public static final int menu_settings=0x7f040002;
27. }
28. public static final class style {
29. /**
30. Base application theme, dependent on API level. This theme is replaced
31. by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
32. Theme customizations available in newer API levels can go in
33. res/values-vXX/styles.xml, while customizations related to
34. backward-compatibility can go here.
35. Base application theme for API 11+. This theme completely replaces
36. AppBaseTheme from res/values/styles.xml on API 11+ devices.
37. API 11 theme customizations can go here.
38. Base application theme for API 14+. This theme completely replaces
39. AppBaseTheme from BOTH res/values/styles.xml and
40. res/values-v11/styles.xml on API 14+ devices.
41. API 14 theme customizations can go here.
42. */
43. public static final int AppBaseTheme=0x7f050000;
44. /** Application theme.
45. All customizations that are NOT specific to a particular API-level can go here.
46. */
47. public static final int AppTheme=0x7f050001;
48. }
49. }

APK File

An apk file is created by the framework automatically. If you want to run the android application
on the mobile, transfer and install it.

Resources

It contains resource files including activity_main, strings, styles etc.

Manifest file

It contains information about package including components such as activities, services, content
providers etc.

Email:[email protected]
23 | P a g e APS Microtech Pvt Ltd

Dalvik Virtual Machine | DVM


As we know the modern JVM is high performance and provides excellent memory management.
But it needs to be optimized for low-powered handheld devices as well.

The Dalvik Virtual Machine (DVM) is an android virtual machine optimized for mobile
devices. It optimizes the virtual machine for memory, battery life and performance.

Dalvik is a name of a town in Iceland. The Dalvik VM was written by Dan Bornstein.

The Dex compiler converts the class files into the .dex file that run on the Dalvik VM. Multiple
class files are converted into one dex file.

Let's see the compiling and packaging process from the source file:

The javac tool compiles the java source file into the class file.

The dx tool takes all the class files of your application and generates a single .dex file. It is a
platform-specific tool.

The Android Assets Packaging Tool (aapt) handles the packaging process.

Email:[email protected]
24 | P a g e APS Microtech Pvt Ltd

AndroidManifest.xml file in android


The AndroidManifest.xml file contains information of your package, including components of
the application such as activities, services, broadcast receivers, content providers etc.

It performs some other tasks also:

 It is responsible to protect the application to access any protected parts by providing the
permissions.
 It also declares the android api that the application is going to use.
 It lists the instrumentation classes. The instrumentation classes provides profiling and other
informations. These informations are removed just before the application is published etc.

This is the required xml file for all the android application and located inside the root directory.

A simple AndroidManifest.xml file looks like this:

1. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
2. package="com.javatpoint.hello"
3. android:versionCode="1"
4. android:versionName="1.0" >
5.
6. <uses-sdk
7. android:minSdkVersion="8"
8. android:targetSdkVersion="15" />
9.
10. <application
11. android:icon="@drawable/ic_launcher"
12. android:label="@string/app_name"
13. android:theme="@style/AppTheme" >
14. <activity
15. android:name=".MainActivity"
16. android:label="@string/title_activity_main" >
17. <intent-filter>
18. <action android:name="android.intent.action.MAIN" />
19.
20. <category android:name="android.intent.category.LAUNCHER" />
21. </intent-filter>
22. </activity>
23. </application>
24.
25. </manifest>

Elements of the AndroidManifest.xml file


The elements used in the above xml file are described below.
Email:[email protected]
25 | P a g e APS Microtech Pvt Ltd

<manifest>

manifest is the root element of the AndroidManifest.xml file. It has package attribute that
describes the package name of the activity class.

<application>

application is the subelement of the manifest. It includes the namespace declaration. This
element contains several subelements that declares the application component such as activity
etc.

The commonly used attributes are of this element are icon, label, theme etc.

android:icon represents the icon for all the android application components.

android:label works as the default label for all the application components.

android:theme represents a common theme for all the android activities.

<activity>

activity is the subelement of application and represents an activity that must be defined in the
AndroidManifest.xml file. It has many attributes such as label, name, theme, launchMode etc.

android:label represents a label i.e. displayed on the screen.

android:name represents a name for the activity class. It is required attribute.

<intent-filter>

intent-filter is the sub-element of activity that describes the type of intent to which activity,
service or broadcast receiver can respond to.

<action>

It adds an action for the intent-filter. The intent-filter must have at least one action element.

<category>

It adds a category name to an intent-filter.

Email:[email protected]
26 | P a g e APS Microtech Pvt Ltd

Android R.java file


Android R.java is an auto-generated file by aapt (Android Asset Packaging Tool) that contains
resource IDs for all the resources of res/ directory.

If you create any component in the activity_main.xml file, id for the corresponding component is
automatically created in this file. This id can be used in the activity source file to perform any
action on the component.

Note: If you delete R.jar file, android creates it automatically.

Let's see the android R.java file. It includes a lot of static nested classes such as menu, id, layout,
attr, drawable, string etc.

1. /* AUTO-GENERATED FILE. DO NOT MODIFY.


2. *
3. * This class was automatically generated by the
4. * aapt tool from the resource data it found. It
5. * should not be modified by hand.
6. */
7.
8. package com.example.helloandroid;
9.
10. public final class R {
11. public static final class attr {
12. }
13. public static final class drawable {
14. public static final int ic_launcher=0x7f020000;
15. }
16. public static final class id {
17. public static final int menu_settings=0x7f070000;
18. }
19. public static final class layout {
20. public static final int activity_main=0x7f030000;
21. }
22. public static final class menu {
23. public static final int activity_main=0x7f060000;
24. }
25. public static final class string {
26. public static final int app_name=0x7f040000;
27. public static final int hello_world=0x7f040001;
28. public static final int menu_settings=0x7f040002;
29. }
30. public static final class style {
31. /**
32. Base application theme, dependent on API level. This theme is replaced

Email:[email protected]
27 | P a g e APS Microtech Pvt Ltd

33. by AppBaseTheme from res/values-vXX/styles.xml on newer devices.


34.
35.
36. Theme customizations available in newer API levels can go in
37. res/values-vXX/styles.xml, while customizations related to
38. backward-compatibility can go here.
39.
40.
41. Base application theme for API 11+. This theme completely replaces
42. AppBaseTheme from res/values/styles.xml on API 11+ devices.
43.
44. API 11 theme customizations can go here.
45.
46. Base application theme for API 14+. This theme completely replaces
47. AppBaseTheme from BOTH res/values/styles.xml and
48. res/values-v11/styles.xml on API 14+ devices.
49.
50. API 14 theme customizations can go here.
51. */
52. public static final int AppBaseTheme=0x7f050000;
53. /** Application theme.
54. All customizations that are NOT specific to a particular API-level can go here.
55. */
56. public static final int AppTheme=0x7f050001;
57. }
58. }

Email:[email protected]
28 | P a g e APS Microtech Pvt Ltd

Android Hide Title Bar Example


In this example, we are going to explain how to hide the title bar and how to display content in
full screen mode.

The requestWindowFeature(Window.FEATURE_NO_TITLE) method of Activity must be


called to hide the title. But, it must be coded before the setContentView method.

1. @Override
2. protected void onCreate(Bundle savedInstanceState) {
3. super.onCreate(savedInstanceState);
4.
5. requestWindowFeature(Window.FEATURE_NO_TITLE);//will hide the title not the title bar
6.
7. setContentView(R.layout.activity_main);
8.
9. }
10. }

The setFlags() method of Window class is used to display content in full screen mode. You need
to pass the WindowManager.LayoutParams.FLAG_FULLSCREEN constant in the setFlags
method.

1. @Override
2. protected void onCreate(Bundle savedInstanceState) {
3. super.onCreate(savedInstanceState);
4.
5. requestWindowFeature(Window.FEATURE_NO_TITLE);
6. //code that displays the content in full screen mode
7. this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
8. WindowManager.LayoutParams.FLAG_FULLSCREEN);//int flag, int mask
9.
10. setContentView(R.layout.activity_main);
11.
12. }

Android Hide Title Bar Example

Let's see the full code to hide the title bar in android.

activity_main.xml
File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"

Email:[email protected]
29 | P a g e APS Microtech Pvt Ltd

4. android:layout_height="match_parent"
5. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".MainActivity" >
10.
11. <TextView
12. android:layout_width="wrap_content"
13. android:layout_height="wrap_content"
14. android:text="@string/hello_world" />
15.
16. </RelativeLayout>

Activity class
File: MainActivity.java

1. package com.javatpoint.hidetitle;
2.
3. import android.os.Bundle;
4. import android.app.Activity;
5. import android.view.Menu;
6. import android.view.Window;
7. import android.view.WindowManager;
8.
9. public class MainActivity extends Activity {
10.
11. @Override
12. protected void onCreate(Bundle savedInstanceState) {
13. super.onCreate(savedInstanceState);
14.
15. requestWindowFeature(Window.FEATURE_NO_TITLE);
16.
17. /*this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
18. WindowManager.LayoutParams.FLAG_FULLSCREEN);//int flag, int mask
19. */
20. setContentView(R.layout.activity_main);
21.
22. }
23.
24.
25. }

Email:[email protected]
30 | P a g e APS Microtech Pvt Ltd

Output: Hiding the Title Only

Output: Hiding the TitleBar and enabling FullScreen

`Android Screen Orientation Example


Email:[email protected]
31 | P a g e APS Microtech Pvt Ltd

The screenOrientation is the attribute of activity element. The orientation of android activity
can be portrait, landscape, sensor, unspecified etc. You need to define it in the
AndroidManifest.xml file. For example:

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:screenOrientation="landscape"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
</application>

The common values for screenOrientation attribute are as follows:

Value Description

unspecified It is the default value. In such case, system chooses the orientation.

Portrait taller not wider

Landscape wider not taller

Sensor orientation is determined by the device orientation sensor.

Android landscape mode screen orientation example

activity_main.xml
File: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:id="@+id/btnclick"
android:layout_marginTop="178dp"

Email:[email protected]
32 | P a g e APS Microtech Pvt Ltd

android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:onClick="show"
/>

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edtxt"
android:layout_alignParentTop="true"
android:layout_marginTop="53dp"
android:gravity="center"

android:text="@string/msg"
/>
</RelativeLayout>

Activity class
File: MainActivity.java

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

EditText edtxt;
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void show(View v)
{
edtxt=(EditText)findViewById(R.id.edtxt);
String s=edtxt.getText().toString();
// btn=(Button)findViewById(R.id.btnclick);
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();

}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

Email:[email protected]
33 | P a g e APS Microtech Pvt Ltd

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

AndroidManifest.xml
File: AndroidManifest.xml

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:screenOrientation="landscape"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
</application>

Output:

Email:[email protected]
34 | P a g e APS Microtech Pvt Ltd

Android Widgets
There are given a lot of android widgets with simplified examples such as Button, EditText,
AutoCompleteTextView, ToggleButton, DatePicker, TimePicker, ProgressBar etc.

Android widgets are easy to learn. The widely used android widgets with examples are given
below:

Android Button

Let's learn how to perform event handling on button click.

Android Toast

Displays information for the short duration of time.

Custom Toast

We are able to customize the toast, such as we can display image on the toast

ToggleButton

It has two states ON/OFF.

CheckBox

Let's see the application of simple food ordering.

AlertDialog

AlertDialog displays a alert dialog containing the message with OK and Cancel buttons.

Spinner

Spinner displays the multiple options, but only one can be selected at a time.

AutoCompleteTextView

Let's see the simple example of AutoCompleteTextView.

RatingBar

RatingBar displays the rating bar.

Email:[email protected]
35 | P a g e APS Microtech Pvt Ltd

DatePicker

Datepicker displays the datepicker dialog that can be used to pick the date.

TimePicker

TimePicker displays the timepicker dialog that can be used to pick the time.

ProgressBar

ProgressBar displays progress task.

Android Button Example

Android Button represents a push-button. The android.widget.Button is subclass of TextView


class and CompoundButton is the subclass of Button class.

There are different types of buttons in android such as RadioButton, ToggleButton,


CompoundButton etc.

Here, we are going to create two textfields and one button for sum of two numbers. If user clicks
button, sum of two input values is displayed on the Toast.

Drag the component or write the code for UI in activity_main.xml

First of all, drag 2 textfields from the Text Fields palette and one button from the Form Widgets
palette as shown in the following figure.

Email:[email protected]
36 | P a g e APS Microtech Pvt Ltd

The generated code for the ui components will be like this:

File: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/ed1"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:text="Enter First Number" />

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/ed2"
android:layout_below="@+id/ed1"
android:layout_centerHorizontal="true"
android:layout_marginTop="46dp"
android:text="Enter Second Number" />

<Button
android:layout_width="wrap_content"

Email:[email protected]
37 | P a g e APS Microtech Pvt Ltd

android:layout_height="wrap_content"
android:text="Add"
android:id="@+id/b1"
android:layout_below="@+id/ed2"
android:layout_centerHorizontal="true"
android:layout_marginTop="80dp"
android:onClick="addTwo" />
</RelativeLayout>

Activity class

Now write the code to display the sum of two numbers.

File: MainActivity.java

import andr
oid.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {


EditText e1,e2;
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1=(EditText)findViewById(R.id.ed1);
e2=(EditText)findViewById(R.id.ed2);
btn=(Button)findViewById(R.id.b1);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String s1=e1.getText().toString();
String s2=e2.getText().toString();
int n1,n2;
n1=Integer.parseInt(s1);
n2=Integer.parseInt(s2);
Toast.makeText(getApplicationContext(),"Addition Of Two
Number="+(n1+n2),Toast.LENGTH_LONG).show();
}
});

}
/*public void addTwo(View view){

String s1=e1.getText().toString();
String s2=e2.getText().toString();
int n1,n2;
n1=Integer.parseInt(s1);
n2=Integer.parseInt(s2);
Toast.makeText(this,"Addition Of Two
Number="+(n1+n2),Toast.LENGTH_LONG).show();
}*/

Email:[email protected]
38 | P a g e APS Microtech Pvt Ltd

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

Output:

Email:[email protected]
39 | P a g e APS Microtech Pvt Ltd

Android Toast Example

Andorid Toast can be used to display information for the short period of time. A toast contains
message to be displayed quickly and disappears after sometime.

The android.widget.Toast class is the subclass of java.lang.Object class.

You can also create custom toast as well for example toast displaying image. You can visit next
page to see the code for custom toast.

Toast class
Toast class is used to show notification for a particular interval of time. After sometime it
disappears. It doesn't block the user interaction.

Constants of Toast class

There are only 2 constants of Toast class which are given below.

Constant Description

Email:[email protected]
40 | P a g e APS Microtech Pvt Ltd

public static final int LENGTH_LONG displays view for the long duration of time.

public static final int LENGTH_SHORT displays view for the short duration of time.

Methods of Toast class

The widely used methods of Toast class are given below.

Method Description

public static Toast makeText(Context context, CharSequence makes the toast containing text and
text, int duration) duration.

public void show() displays toast.

public void setMargin (float horizontalMargin, float changes the horizontal and vertical
verticalMargin) margin difference.

Android Toast Example


1. Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LENGTH_SHORT).show();

Another code:

1. Toast toast=Toast.makeText(getApplicationContext(),"Hello Codemocrosystem",Toast.LENGTH_


SHORT);
2. toast.setMargin(50,50);
3. toast.show();

Here, getApplicationContext() method returns the instance of Context.

Full code of activity class displaying Toast


Let's see the code to display the toast.

File: MainActivity.java

1. package com.example.toast;
2. import android.os.Bundle;
3. import android.app.Activity;

Email:[email protected]
41 | P a g e APS Microtech Pvt Ltd

4. import android.view.Menu;
5. import android.view.View;
6. import android.widget.Toast;
7.
8. public class MainActivity extends Activity {
9. @Override
10. public void onCreate(Bundle savedInstanceState) {
11. super.onCreate(savedInstanceState);
12. setContentView(R.layout.activity_main);
13.
14. //Displaying Toast with Hello Javatpoint message
15. Toast.makeText(getApplicationContext(),"Hello Code
Microsystem",Toast.LENGTH_SHORT).show();
16. }
17.
18. @Override
19. public boolean onCreateOptionsMenu(Menu menu) {
20. getMenuInflater().inflate(R.menu.activity_main, menu);
21. return true;
22. }
23.
24. }

Output:

Email:[email protected]
42 | P a g e APS Microtech Pvt Ltd

Android Custom Toast Example


You are able to create custom toast in android. So, you can display some images like
congratulations or loss on the toast. It means you are able to customize the toast now.

activity_main.xml

Drag the component that you want to display on the main activity.

File: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="99dp"
android:layout_marginStart="99dp"
android:gravity="center_horizontal"
android:textAppearance="?android:textAppearanceLarge"
android:textColor="#801233"
/>

</RelativeLayout>

Email:[email protected]
43 | P a g e APS Microtech Pvt Ltd

customtoast.xml

Create another xml file inside the layout directory. Here we are having ImageView and
TextView in this xml file.

File: customtoast.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:id="@+id/custom_toast_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F14E23"
android:weightSum="1">

<ImageView
android:layout_width="175dp"
android:layout_height="wrap_content"
android:id="@+id/custom_toast_image"
android:src="@drawable/v2"
android:contentDescription="@string/hello_world"
/>

<TextView
android:id="@+id/custom_toast_message"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:contentDescription="@string/Toast"
android:text="@string/Toast"
android:layout_gravity="center_horizontal"
android:layout_weight="0.20" />

</LinearLayout>

Activity class

Now write the code to display the custom toast.

File: MainActivity.java

1. package microsystem.org.customtoastdemo;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

@Override

Email:[email protected]
44 | P a g e APS Microtech Pvt Ltd

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

LayoutInflater li=getLayoutInflater();
View layout=li.inflate(R.layout.customtoast, (ViewGroup)
findViewById(R.id.custom_toast_layout));
Toast toast=new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER_VERTICAL,0,0);
toast.setView(layout);
toast.show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

Output:

Android ToggleButton Example

Email:[email protected]
45 | P a g e APS Microtech Pvt Ltd

Android Toggle Button can be used to display checked/unchecked (On/Off) state on the button.

It is beneficial if user have to change the setting between two states. It can be used to On/Off
Sound, Wifi, Bluetooth etc.

Since Android 4.0, there is another type of toggle button called switch that provides slider
control.

Android ToggleButton and Switch both are the subclasses of CompoundButton class.

Android ToggleButton class


ToggleButton class provides the facility of creating the toggle button.

XML Attributes of ToggleButton class

The 3 XML attributes of ToggleButton class.

XML Attribute Description

android:disabledAlpha The alpha to apply to the indicator when disabled.

android:textOff The text for the button when it is not checked.

android:textOn The text for the button when it is checked.

Email:[email protected]
46 | P a g e APS Microtech Pvt Ltd

Methods of ToggleButton class

The widely used methods of ToggleButton class are given below.

Method Description

CharSequence getTextOff() Returns the text when button is not in the checked state.

CharSequence getTextOn() Returns the text for when button is in the checked state.

void setChecked(boolean checked) Changes the checked state of this button.

Android ToggleButton Example


activity_main.xml

Drag two toggle button and one button for the layout. Now the activity_main.xml file will look
like this:

File: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New ToggleButton"
android:id="@+id/toggleButton"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textOff="off"
android:textOn="on"
/>

<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New ToggleButton"
android:id="@+id/toggleButton2"
android:layout_alignTop="@+id/toggleButton"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:textOff="off"
android:textOn="on"

Email:[email protected]
47 | P a g e APS Microtech Pvt Ltd

/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="State"
android:id="@+id/button"
android:layout_marginTop="60dp"
android:layout_below="@+id/toggleButton2"
android:layout_centerHorizontal="true" />
</RelativeLayout>

Activity class

Let's write the code to check which toggle button is ON/OFF.

File: MainActivity.java

package microsystem.org.toggledemo;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends ActionBarActivity {

ToggleButton t1,t2;
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButtonClick();
}
public void addListenerOnButtonClick()
{
t1=(ToggleButton)findViewById(R.id.toggleButton);
t2=(ToggleButton)findViewById(R.id.toggleButton2);
b1=(Button)findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

StringBuilder result = new StringBuilder();


result.append("Togg1e1 is=").append(t1.getText());
result.append("\nToggle2=").append(t2.getText());
Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();

}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.

Email:[email protected]
48 | P a g e APS Microtech Pvt Ltd

getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

Output:

Email:[email protected]
49 | P a g e APS Microtech Pvt Ltd

Android CheckBox Example

Android CheckBox is a type of two state button either checked or unchecked.

There can be a lot of usage of checkboxes. For example, it can be used to know the hobby of the
user, activate/deactivate the specific action etc.

Android CheckBox class is the subclass of CompoundButton class.

Email:[email protected]
50 | P a g e APS Microtech Pvt Ltd

Android CheckBox class


The android.widget.CheckBox class provides the facility of creating the CheckBoxes.

Methods of CheckBox class

There are many inherited methods of View, TextView, and Button classes in the CheckBox
class. Some of them are as follows:

Method Description

public boolean isChecked() Returns true if it is checked otherwise false.

public void setChecked(boolean status) Changes the state of the CheckBox.

Android CheckBox Example


activity_main.xml

Drag the three checkboxes and one button for the layout. Now the activity_main.xml file will
look like this:

File: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Pizza" />

<CheckBox
android:id="@+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/checkBox1"
android:text="Coffe" />

<CheckBox

Email:[email protected]
51 | P a g e APS Microtech Pvt Ltd

android:id="@+id/checkBox3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/checkBox2"
android:text="Burger" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/checkBox2"
android:layout_marginTop="32dp"
android:layout_toLeftOf="@+id/checkBox3"
android:text="Order" />

</RelativeLayout>

Activity class

Let's write the code to check which toggle button is ON/OFF.

File: MainActivity.java

package microsystem.org.checkboxdemo;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {


CheckBox pizza,coffe,burger;
Button buttonOrder;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButtonClick();
}

public void addListenerOnButtonClick(){


//Getting instance of CheckBoxes and Button from the activty_main.xml file
pizza=(CheckBox)findViewById(R.id.checkBox1);
coffe=(CheckBox)findViewById(R.id.checkBox2);
burger=(CheckBox)findViewById(R.id.checkBox3);
buttonOrder=(Button)findViewById(R.id.button1);

//Applying the Listener on the Button click


buttonOrder.setOnClickListener(new View.OnClickListener(){

@Override
public void onClick(View view) {
int totalamount=0;

Email:[email protected]
52 | P a g e APS Microtech Pvt Ltd

StringBuilder result=new StringBuilder();


result.append("Selected Items:");
if(pizza.isChecked()){
result.append("\nPizza 100Rs");
totalamount+=100;
}
if(coffe.isChecked()){
result.append("\nCoffe 50Rs");
totalamount+=50;
}
if(burger.isChecked()){
result.append("\nBurger 120Rs");
totalamount+=120;
}
result.append("\nTotal: "+totalamount+"Rs");
//Displaying the message on the toast
Toast.makeText(getApplicationContext(),
result.toString(), Toast.LENGTH_LONG).show();
}

});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

Email:[email protected]
53 | P a g e APS Microtech Pvt Ltd

Output:

Email:[email protected]
54 | P a g e APS Microtech Pvt Ltd

Android AlertDialog Example

Android AlertDialog can be used to display the dialog message with OK and Cancel buttons. It
can be used to interrupt and ask the user about his/her choice to continue or discontinue.

Android AlertDialog is composed of three regions: title, content area and action buttons.

Android AlertDialog is the subclass of Dialog class.

Android AlertDialog Example


Let's see a simple example of android alert dialog.

activity_main.xml

You can have multiple components, here we are having only a textview.

File: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textAppearance="?android:textAppearanceLarge"
android:textColor="@color/cyan"

android:id="@+id/textView" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click"

Email:[email protected]
55 | P a g e APS Microtech Pvt Ltd

android:id="@+id/button"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="69dp"
android:onClick="show"
/>

</RelativeLayout>

strings.xml

Optionally, you can store the dialog message and title in the strings.xml file.

File: strings.xml

<resources>
<string name="app_name">AlertDialogDemo</string>

<string name="hello_world">Hello world!</string>


<string name="action_settings">Settings</string>
</resources>

Activity class

Let's write the code to create and show the AlertDialog.

File: MainActivity.java

package microsystem.org.alertdialogdemo;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

Email:[email protected]
56 | P a g e APS Microtech Pvt Ltd

public void show(View view)


{
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setMessage("Do u Want to Close the
App").setCancelable(false).setPositiveButton("Yes", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}

}).setNegativeButton("No", new DialogInterface.OnClickListener() {


@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});

AlertDialog alert=builder.create();
setTitle("Code Microsystem");
alert.show();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

Email:[email protected]
57 | P a g e APS Microtech Pvt Ltd

Output:

Android Spinner Example


Email:[email protected]
58 | P a g e APS Microtech Pvt Ltd

Android Spinner is like the combox box of AWT or Swing. It can be used to display the
multiple options to the user in which only one item can be selected by the user.

Android spinner is like the drop down menu with multiple values from which the end user can
select only one value.

Android spinner is associated with AdapterView. So you need to use one of the adapter classes
with spinner.

Android Spinner class is the subclass of AsbSpinner class.

Android Spinner Example


In this example, we are going to display the country list. You need to use ArrayAdapter class to
store the country list.

Let's see the simple example of spinner in android.

activity_main.xml

Drag the Spinner from the pallete, now the activity_main.xml file will like this:

File: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"

Email:[email protected]
59 | P a g e APS Microtech Pvt Ltd

tools:context=".MainActivity">

<TextView android:text="@string/city_name"

android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:textAppearanceLarge"
android:gravity="center_horizontal"
android:id="@+id/textView" />

<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/spinner"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="58dp" />

</RelativeLayout>

Activity class

Let's write the code to display item on the spinner and perform event handling.

File: MainActivity.java

package microsystem.org.spinnerdemoevening;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

public class MainActivity extends ActionBarActivity {


String mycity[]={"Nagpur","Pune","Katol","Amravati"};
Spinner sp1;
ArrayAdapter<String> ad;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp1=(Spinner)findViewById(R.id.spinner);
ad=new
ArrayAdapter<String>(this,android.R.layout.simple_list_item_single_choice,mycit
y);
sp1.setAdapter(ad);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override

Email:[email protected]
60 | P a g e APS Microtech Pvt Ltd

public boolean onOptionsItemSelected(MenuItem item) {


// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

Output:

Android AutoCompleteTextView Example

Email:[email protected]
61 | P a g e APS Microtech Pvt Ltd

Android AutoCompleteTextView completes the word based on the reserved words, so


no need to write all the characters of the word.

Android AutoCompleteTextView is a editable text field, it displays a list of suggestions in


a drop down menu from which user can select only one suggestion or value.

Android AutoCompleteTextView is the subclass of EditText class. The


MultiAutoCompleteTextView is the subclass of AutoCompleteTextView class.

Android AutoCompleteTextView Example


In this example, we are displaying the programming languages in the
autocompletetextview. All the programming languages are stored in string array. We are
using the ArrayAdapter class to display the array content.

Let's see the simple example of autocompletetextview in android.

activity_main.xml

Drag the AutoCompleteTextView and TextView from the pallete, now the
activity_main.xml file will like this:

File: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"

Email:[email protected]
62 | P a g e APS Microtech Pvt Ltd

android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:text="@string/hello_world"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"

android:textAppearance="?android:textAppearanceLarge"
android:textColor="#000000"
android:id="@+id/textView" />

<AutoCompleteTextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Enter Class"
android:id="@+id/av"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="80dp" />

</RelativeLayout>

Activity class

Let's write the code of AutoCompleteTextView.

File: MainActivity.java

package microsystem.org.autocompletedemo1;

import android.graphics.Color;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;

public class MainActivity extends ActionBarActivity {

String
myclass[]={"PHP","JAVA","ANDROID","ASP.NET","ORACLE","OOPs","PYTHAN"};
AutoCompleteTextView a1;
ArrayAdapter<String> ad;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
a1=(AutoCompleteTextView)findViewById(R.id.av);
ad=new
ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,myclass);
a1.setAdapter(ad);
a1.setThreshold(1);
a1.setTextColor(Color.RED);
}

Email:[email protected]
63 | P a g e APS Microtech Pvt Ltd

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

Output:

2)Second Example

1)activity.xml file

Email:[email protected]
64 | P a g e APS Microtech Pvt Ltd

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:id="@+id/rl1">

<AutoCompleteTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/a1"
android:hint="Select Name"
/>
</RelativeLayout>

2)string.xml file

<resources>
<string name="app_name">AutoCompleteTextViewDemo</string>

<string name="hello_world">Hello world!</string>


<string name="action_settings">Settings</string>
<string-array name="names">
<item>Arvind</item>
<item>Archana</item>
<item>Mohan</item>
<item>Manesh</item>
</string-array>
</resources>

3)MainActivity.java

package microsystem.org.autocompletetextviewdemo;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;

public class MainActivity extends ActionBarActivity {


AutoCompleteTextView acv;
String []s;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
acv=(AutoCompleteTextView)findViewById(R.id.a1);
s=getResources().getStringArray(R.array.names);

Email:[email protected]
65 | P a g e APS Microtech Pvt Ltd

ArrayAdapter<String> adapter=new
ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,s);
acv.setAdapter(adapter);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

4)Output:-

Email:[email protected]
66 | P a g e APS Microtech Pvt Ltd

Android RatingBar Example

Android RatingBar can be used to get the rating from the user. The Rating returns a
floating-point number. It may be 2.0, 3.5, 4.0 etc.

Android RatingBar displays the rating in stars. Android RatingBar is the subclass of
AbsSeekBar class.

The getRating() method of android RatingBar class returns the rating number.

Android RatingBar Example

Email:[email protected]
67 | P a g e APS Microtech Pvt Ltd

Let's see the simple example of rating bar in android.

activity_main.xml

Drag the RatingBar and Button from the pallete, now the activity_main.xml file will like
this:

File: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<RatingBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/ratingBar"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="42dp"

/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GetRating"
android:id="@+id/b1"
android:layout_below="@+id/ratingBar"
android:layout_centerHorizontal="true"
android:layout_marginTop="54dp"
android:onClick="show"
/>
</RelativeLayout>

Activity class

Let's write the code to display the rating of the user.

File: MainActivity.java

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

Email:[email protected]
68 | P a g e APS Microtech Pvt Ltd

import android.widget.RatingBar;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {


RatingBar r1;
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
r1=(RatingBar)findViewById(R.id.ratingBar);
btn=(Button)findViewById(R.id.b1);
show();
}
public void show(){
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

String s=String.valueOf(r1.getRating());
Toast.makeText(getApplicationContext(),"Your
Rating="+s,Toast.LENGTH_LONG).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

Output:

Email:[email protected]
69 | P a g e APS Microtech Pvt Ltd

Email:[email protected]
70 | P a g e APS Microtech Pvt Ltd

Android WebView Example

Android WebView is used to display web page in android. The web page can be loaded
from same application or URL. It is used to display online content in android activity.

Android WebView uses webkit engine to display web page.

The android.webkit.WebView is the subclass of AbsoluteLayout class.

The loadUrl() and loadData() methods of Android WebView class are used to load and
display web page.

Let's see the simple code to display google.com web page using web view.

1. WebView mywebview = (WebView) findViewById(R.id.webView1);


2. mywebview.loadUrl("http://www.google.com/");

Let's see the simple code to display HTML web page using web view. In this case, html
file must be located inside the asset directory.

1. WebView mywebview = (WebView) findViewById(R.id.webView1);


2. mywebview.loadUrl("file:///android_asset/myresource.html");

Let's see another code to display HTML code of a string.

1. String data = "<html><body><h1>Hello,Code Microsystem!</h1></body></html>";


2. mywebview.loadData(data, "text/html", "UTF-8");

Email:[email protected]
71 | P a g e APS Microtech Pvt Ltd

Android WebView Example


Let's see a simple example of android webview.

activity_main.xml
File: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/webView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>

Activity class
File: MainActivity.java

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView=(WebView)findViewById(R.id.webView);
// webView.loadUrl("www.google.com");
/* String data = "<html><body><h1>Hello, Xceller
IT!</h1></body></html>";
webView.loadData(data, "text/html", "UTF-8");
*/
webView.loadUrl("file:///asset/Hello.html");
}

Email:[email protected]
72 | P a g e APS Microtech Pvt Ltd

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

Output:

Email:[email protected]
73 | P a g e APS Microtech Pvt Ltd

Android SeekBar Example

Android SeekBar is a kind of ProgressBar with draggable thumb. The end user can drag
the thum left and right to move the progress of song, file download etc.

The SeekBar.OnSeekBarChangeListener interface provides methods to perform even


handling for seek bar.

Android SeekBar and RatingBar classes are the sub classes of AbsSeekBar.

Email:[email protected]
74 | P a g e APS Microtech Pvt Ltd

Android SeekBar Example


activity_main.xml

Drag the seek bar from the pallete, now activity_main.xml will look like this:

File: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/b1"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="58dp"
android:indeterminate="false" />
</RelativeLayout>

Activity class

Let's see the Activity class displaying seek bar and performing event handling.

File: MainActivity.java

import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.SeekBar;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class MainActivity extends ActionBarActivity implements


OnSeekBarChangeListener {
SeekBar s1;
private SeekBar seekBar;
private int progress;
private boolean fromUser;

Email:[email protected]
75 | P a g e APS Microtech Pvt Ltd

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
s1=(SeekBar)findViewById(R.id.b1);
s1.setOnSeekBarChangeListener(this);
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean
fromUser) {

Toast.makeText(getApplicationContext(), "seekbar progress: " + progress,


Toast.LENGTH_SHORT).show();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
Toast.makeText(getApplicationContext(),"seekbar touch
started!", Toast.LENGTH_SHORT).show();
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
Toast.makeText(getApplicationContext(),"seekbar touch stopped!",
Toast.LENGTH_SHORT).show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

Output:

Email:[email protected]
76 | P a g e APS Microtech Pvt Ltd

Android DatePicker Example

Android DatePicker is a widget to select date. It allows you to select date by day, month

Email:[email protected]
77 | P a g e APS Microtech Pvt Ltd

and year. Like DatePicker, android also provides TimePicker to select time.

The android.widget.DatePicker is the subclass of FrameLayout class.

Android DatePicker Example


Let's see the simple example of datepicker widget in android.

activity_main.xml

File: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView android:text="@string/hello_world"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:textAppearanceLarge"
android:gravity="center_horizontal"
android:id="@+id/textView" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Today Date"
android:id="@+id/b1"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="89dp" />

</RelativeLayout>

Activity class

File: MainActivity.java

package microsystem.org.mydatepickerdemo;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

Email:[email protected]
78 | P a g e APS Microtech Pvt Ltd

import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

import java.util.Calendar;

public class MainActivity extends ActionBarActivity {

Button b1;
TextView t1;
int y,m,d;
static final int DILOG_ID=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.b1);
t1=(TextView)findViewById(R.id.textView);
Calendar c= Calendar.getInstance();
y=c.get(Calendar.YEAR);
m=c.get(Calendar.MONTH);
d=c.get(Calendar.DAY_OF_MONTH);
show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public void show()
{
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialog(DILOG_ID);

}
});
}
@Override
protected Dialog onCreateDialog(int id)
{
if(id==DILOG_ID)
return new DatePickerDialog(this,dpicketlistener,y,m,d);

return null;

}
private DatePickerDialog.OnDateSetListener dpicketlistener= new
DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int
dayOfMonth) {
y=year;
m=monthOfYear+1;
d=dayOfMonth;
// ed=(EditText)findViewById(R.id.edDate);
t1.setText(d+"/"+m+"/"+y);
//
Toast.makeText(MainActivity.this,y+"/"+m+"/"+d,Toast.LENGTH_SHORT).show();

Email:[email protected]
79 | P a g e APS Microtech Pvt Ltd

}
};
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

Android TimePicker Example

Android TimePicker widget is used to select date. It allows you to select time by hour

Email:[email protected]
80 | P a g e APS Microtech Pvt Ltd

and minute. You cannot select time by seconds.

The android.widget.TimePicker is the subclass of FrameLayout class.

Android TimePicker Example

Let's see a simple example of android time picker.

activity_main.xml
File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <TimePicker
8. android:id="@+id/timePicker1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentTop="true"
12. android:layout_centerHorizontal="true"
13. android:layout_marginTop="86dp" />
14.
15. <TextView
16. android:id="@+id/textView1"
17. android:layout_width="wrap_content"
18. android:layout_height="wrap_content"
19. android:layout_alignLeft="@+id/timePicker1"
20. android:layout_alignParentTop="true"
21. android:layout_marginTop="17dp"
22. android:text="Current Time:" />
23.
24. <Button
25. android:id="@+id/button1"
26. android:layout_width="wrap_content"
27. android:layout_height="wrap_content"
28. android:layout_alignLeft="@+id/timePicker1"
29. android:layout_below="@+id/timePicker1"
30. android:layout_marginLeft="37dp"
31. android:layout_marginTop="55dp"
32. android:text="Change Time" />
33.
34. </RelativeLayout>

Email:[email protected]
81 | P a g e APS Microtech Pvt Ltd

Activity class
File: MainActivity.java

1. package com.example.timepicker1;
2.
3. import android.os.Bundle;
4. import android.app.Activity;
5. import android.view.Menu;
6. import android.view.View;
7. import android.view.View.OnClickListener;
8. import android.widget.Button;
9. import android.widget.TextView;
10. import android.widget.TimePicker;
11. import android.widget.Toast;
12.
13. public class MainActivity extends Activity {
14. TextView textview1;
15. TimePicker timepicker1;
16. Button changetime;
17.
18. @Override
19. protected void onCreate(Bundle savedInstanceState) {
20. super.onCreate(savedInstanceState);
21. setContentView(R.layout.activity_main);
22.
23. textview1=(TextView)findViewById(R.id.textView1);
24. timepicker1=(TimePicker)findViewById(R.id.timePicker1);
25. //Uncomment the below line of code for 24 hour view
26. timepicker1.setIs24HourView(true);
27. changetime=(Button)findViewById(R.id.button1);
28.
29. textview1.setText(getCurrentTime());
30.
31. changetime.setOnClickListener(new OnClickListener(){
32. @Override
33. public void onClick(View view) {
34. textview1.setText(getCurrentTime());
35. }
36. });
37.
38. }
39.
40. public String getCurrentTime(){
41. String currentTime="Current Time: "+timepicker1.getCurrentHour()+":"+timepicker1.
getCurrentMinute();
42. return currentTime;

Email:[email protected]
82 | P a g e APS Microtech Pvt Ltd

43. }
44. @Override
45. public boolean onCreateOptionsMenu(Menu menu) {
46. // Inflate the menu; this adds items to the action bar if it is present.
47. getMenuInflater().inflate(R.menu.activity_main, menu);
48. return true;
49. }
50.
51. }

Android Analog clock and Digital clock


example
The android.widget.AnalogClock and android.widget.DigitalClock classes provides the
functionality to display analog and digital clocks.

Android analog and digital clocks are used to show time in android application.

Android AnalogClock is the subclass of View class.

Android DigitalClock is the subclass of TextView class. Since Android API level 17, it is
deprecated. You are recommended to use TextClock Instead.

Note: Analog and Digital clocks cannot be used to change the time of the device. To do so,
you need to use DatePicker and TimePicker.

In android, you need to drag analog and digital clocks from the pallet to display analog
and digital clocks. It represents the timing of the current device.

activity_main.xml

Email:[email protected]
83 | P a g e APS Microtech Pvt Ltd

Now, drag the analog and digital clocks, now the xml file will look like this.

File: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView android:text="@string/hello_world"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:layout_centerHorizontal="true"
android:gravity="center_horizontal"
android:textAppearance="?android:textAppearanceLarge"
android:textColor="#1E90FF"
/>

<AnalogClock
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/analogClock"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="103dp" />

<DigitalClock
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/digitalClock"
android:layout_below="@+id/analogClock"
android:layout_centerHorizontal="true"
android:layout_marginTop="60dp"
android:textAppearance="?android:textAppearanceLarge"
android:gravity="center_horizontal"
/>

</RelativeLayout>

Activity class

We have not write any code here.

File: MainActivity.java

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

Email:[email protected]
84 | P a g e APS Microtech Pvt Ltd

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

Output:

Email:[email protected]
85 | P a g e APS Microtech Pvt Ltd

Android ProgressBar Example

We can display the android progress bar dialog box to display the status of work being
done e.g. downloading file, analyzing status of work etc.

In this example, we are displaying the progress dialog for dummy file download operation.

Here we are using android.app.ProgressDialog class to show the progress bar. Android

Email:[email protected]
86 | P a g e APS Microtech Pvt Ltd

ProgressDialog is the subclass of AlertDialog class.

The ProgressDialog class provides methods to work on progress bar like setProgress(),
setMessage(), setProgressStyle(), setMax(), show() etc. The progress range of Progress
Dialog is 0 to 10000.

Let's see a simple example to display progress bar in android.

1. ProgressDialog progressBar = new ProgressDialog(this);


2. progressBar.setCancelable(true);//you can cancel it by pressing back button
3. progressBar.setMessage("File downloading ...");
4. progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
5. progressBar.setProgress(0);//initially progress is 0
6. progressBar.setMax(100);//sets the maximum value 100
7. progressBar.show();//displays the progress bar

Android Progress Bar Example by ProgressDialog


What is Android ProgressBar ?
ProgressBar in Android is a graphical view indicator which shows some progress. It
shows a bar representing the completing of the task. Normally the ProgresBar do not
display the amount of completion in numbers. If we want, we can display it in the
TextView (Given in the example).

Difference between ProgressBar and ProgressDialog:


The programmers often get this doubt. ProgressBar is a view indicating the amount
of progress done. The application can change the value. This can be used in the layout to
show the progress.
On the other side ProgressDialog is a dialog box (like alert). The user must wait for the
progress to complete.

Important things about ProgressBar:


By default the progress bar maximum value is 100. It can also be changed by
setting the our own maximum value using android:max attribute. Example;

Email:[email protected]
87 | P a g e APS Microtech Pvt Ltd

If we know the amount of work, then we can use this progress bar showing the actual
progress. But if we do not know the amount of work to be done, then we can
use progressBar.setIndeterminate(true) in the activity class programatically or
using android:indeterminate="true" in the layout xml file which will enable the
intermediate mode. In the intermediate mode the actual progress will not be shown. A
cyclic animation will be shown to indicate that some progress is happening. This
intermediate mode is shown below;

By default the progress bar will be displayed as a spinning wheel. If we want it to be


displayed as a horizontal bar, we need to use
style="?android:attr/progressBarStyleHorizontal" attribute.
The default mode is shown below;

How to create:
ProgressBar can be created using <ProgressBar> tag in the layout xml file.
android:max attribute is used to set the maximum value of the progress bar.
android:minHeight attribute is used to set the height of the progress bar.
androif:minWidth attribute is used to set the width of the progress bar.
android:progress attribute is used to set the number in which the progress bar value will
be incremented.
activity_main.xml

Email:[email protected]
88 | P a g e APS Microtech Pvt Ltd

Drag one button from the pallete, now the activity_main.xml file will look like this:

File: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<ProgressBar
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="23dp"
android:layout_marginTop="20dp"
android:indeterminate="false"
android:max="100"
android:minHeight="50dp"
android:minWidth="200dp"
android:progress="1" />

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/progressBar1"
android:layout_below="@+id/progressBar1"/>
</RelativeLayout>

Activity class

Let's write the code to display the progress bar dialog box.

File: MainActivity.java

package microsystem.org.progressbardemo1;

import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

Email:[email protected]
89 | P a g e APS Microtech Pvt Ltd

private ProgressBar progressBar;


private int progressStatus = 0;
private TextView textView;
private Handler handler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
textView = (TextView) findViewById(R.id.textView1);
// Start long running operation in a background thread
new Thread(new Runnable() {
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
// Update the progress bar and display the

//current value in the text view


handler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressStatus);

textView.setText(progressStatus+"/"+progressBar.getMax());
}
});
try {
// Sleep for 200 milliseconds.

//Just to display the progress slowly


Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

Email:[email protected]
90 | P a g e APS Microtech Pvt Ltd

Output:

Email:[email protected]
91 | P a g e APS Microtech Pvt Ltd

Android Activity Lifecycle

Android Activity Lifecycle is controlled by 7 methods of android.app.Activity class. The


android Activity is the subclass of ContextThemeWrapper class.

An activity is the single screen in android. It is like window or frame of Java.

By the help of activity, you can place all your UI components or widgets in a single
screen.

The 7 lifecycle method of Activity describes how activity will behave at different states.

Android Activity Lifecycle methods


Let's see the 7 lifecycle methods of android activity.

Method Description

onCreate called when activity is first created.

onStart called when activity is becoming visible to the user.

onResume called when activity will start interacting with the user.

onPause called when activity is not visible to the user.

Email:[email protected]
92 | P a g e APS Microtech Pvt Ltd

onStop called when activity is no longer visible to the user.

onRestart called after your activity is stopped, prior to start.

onDestroy called before the activity is destroyed.

Android Activity Lifecycle Example

Email:[email protected]
93 | P a g e APS Microtech Pvt Ltd

It provides the details about the invocation of life cycle methods of activity. In this
example, we are displaying the content on the logcat.

File: MainActivity.java

package microsystem.org.activitylifecycle;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("lifecycle","onStart invoked");
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
protected void onResume() {
super.onResume();
Log.d("lifecycle","onResume invoked");
}

@Override
protected void onPause() {
super.onPause();
Log.d("lifecycle","onPause invoked");
}
@Override
protected void onStop() {
super.onStop();
Log.d("lifecycle","onStop invoked");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d("lifecycle","onRestart invoked");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("lifecycle","onDestroy invoked");
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will

Email:[email protected]
94 | P a g e APS Microtech Pvt Ltd

// automatically handle clicks on the Home/Up button, so long


// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

Output:

You will not see any output on the emulator or device. You need to open logcat.

Now see on the logcat: onCreate, onStart and onResume methods are invoked.

Email:[email protected]
95 | P a g e APS Microtech Pvt Ltd

Now click on the HOME Button. You will see onPause method is invoked.

Email:[email protected]
96 | P a g e APS Microtech Pvt Ltd

After a while, you will see onStop method is invoked.

Now see on the emulator. It is on the home. Now click on the center button to launch the
app again.

Now click on the lifecycleactivity icon.

Email:[email protected]
97 | P a g e APS Microtech Pvt Ltd

Now see on the logcat: onRestart, onStart and onResume methods are invoked.

If you see the emulator, application is started again.

Email:[email protected]
98 | P a g e APS Microtech Pvt Ltd

Now click on the back button. Now you will see onPause methods is invoked.

After a while, you will see onStop and onDestroy methods are invoked.

Email:[email protected]
99 | P a g e APS Microtech Pvt Ltd

The onCreate() and onDestroy() methods are called only once throughout the activity
lifecycle.

Email:[email protected]
100 | P a g e APS Microtech Pvt Ltd

Android Intent Tutorial

Android Intent is the message that is passed between components such as activities,
content providers, broadcast receivers, services etc.

It is generally used with startActivity() method to invoke activity, broadcast receivers etc.

The dictionary meaning of intent is intention or purpose. So, it can be described as the
intention to do action.

The LabeledIntent is the subclass of android.content.Intent class.

Android intents are mainly used to:

 Start the service


 Launch an activity
 Display a web page
 Display a list of contacts
 Broadcast a message
 Dial a phone call etc.

Types of Android Intents


There are two types of intents in android: implicit and explicit.

1) Implicit Intent

Implicit Intent doesn't specifiy the component. In such case, intent provides information
of available components provided by the system that is to be invoked.

For example, you may write the following code to view the webpage.

1. Intent intent=new Intent(Intent.ACTION_VIEW);


2. intent.setData(Uri.parse("http://www.google.com "));

Email:[email protected]
101 | P a g e APS Microtech Pvt Ltd

3. startActivity(intent);

2) Explicit Intent

Explicit Intent specifies the component. In such case, intent provides the external class to
be invoked.

1. Intent i = new Intent(getApplicationContext(), ActivityTwo.class);


2. startActivity(i);

To get the full code of explicit intent, visit the next page.

Android Implicit Intent Example

Let's see the simple example of implicit intent that displays a web page.

activity_main.xml
File: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="58dp"
android:textAppearance="?android:textAppearanceLarge"
/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Visit"
android:id="@+id/b1"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>

Email:[email protected]
102 | P a g e APS Microtech Pvt Ltd

Activity class
File: MainActivity.java

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends ActionBarActivity {

Button b1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.b1);
final EditText e1=(EditText)findViewById(R.id.editText);
b1.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
String url=e1.getText().toString();
Intent i=new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(i);
}
}
);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

Email:[email protected]
103 | P a g e APS Microtech Pvt Ltd

Output:

Email:[email protected]
104 | P a g e APS Microtech Pvt Ltd

Android Explicit Intent Example


Android Explicit intent specifies the component to be invoked from activity. In other
words, we can call another activity in android by explicit intent.

We can also pass the information from one activity to another using explicit intent.

Here, we are going to see an example to call one activity from another and vice-versa.

Android calling one activity from another activity example

Let's see the simple example of android explicit example that calls one activity from
another and vice versa.

activity_main.xml
File: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView android:text="@string/first_msg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/textView" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go To Second Activity"
android:id="@+id/b1"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="92dp" />

</RelativeLayout>

activitytwo_main.xml

Email:[email protected]
105 | P a g e APS Microtech Pvt Ltd

File: activitytwo_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="microsystem.org.explicitintentdemo.SecondActivity">

<TextView android:text="@string/second_msg"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

</RelativeLayout>

ActivityOne class
File: MainActivityOne.java

package microsystem.org.explicitintentdemo;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

public class MainActivity extends ActionBarActivity {

Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.b1);
b1.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new
Intent(MainActivity.this,SecondActivity.class);
i.putExtra("v1","Code Microsystem");
i.putExtra("v2","Nagpur");
startActivity(i);
}
}
);

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;

Email:[email protected]
106 | P a g e APS Microtech Pvt Ltd

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

ActivityTwo class
File: MainActivityTwo.java

package microsystem.org.explicitintentdemo;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class SecondActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Bundle extras = getIntent().getExtras();
String v1=extras.getString("v1");
String v2=extras.getString("v2");

Toast.makeText(getApplicationContext(),"Message=\n"+v1+"\n"+v2,Toast.LENGTH_LONG
).show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_second, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

Email:[email protected]
107 | P a g e APS Microtech Pvt Ltd

return super.onOptionsItemSelected(item);
}
}

Output:

Email:[email protected]
108 | P a g e APS Microtech Pvt Ltd

Android StartActivityForResult Example


By the help of android startActivityForResult() method, we can get result from another
activity.

By the help of android startActivityForResult() method, we can send information from one
activity to another and vice-versa. The android startActivityForResult method, requires a
result from the second activity (activity to be invoked).

In such case, we need to override the onActivityResult method that is invoked


automatically when second activity returns result.

Method Signature
There are two variants of startActivityForResult() method.

Email:[email protected]
109 | P a g e APS Microtech Pvt Ltd

1. public void startActivityForResult (Intent intent, int requestCode)


2. public void startActivityForResult (Intent intent, int requestCode, Bundle options)

Android StartActivityForResult Example


Let's see the simple example of android startActivityForResult method.

activity_main.xml

Drag one textview and one button from the pallete, now the xml file will look like this.

File: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView android:text="@string/hello_world"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textAppearance="?android:textAppearanceLarge"
android:id="@+id/textView" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Message"
android:id="@+id/b1"
android:layout_marginTop="139dp"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />

</RelativeLayout>

second_main.xml

This xml file is created automatically when you create another activity. To create new
activity Right click on the package inside the src -> New -> Other ->Android
Activity.

Now drag one editText, one textView and one button from the pallete, now the xml file
will look like this:

File: second_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"

Email:[email protected]
110 | P a g e APS Microtech Pvt Ltd

android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="microsystem.org.srartactivityforresultdemo.SecondActivity">

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="56dp"
android:gravity="center_horizontal"
android:textAppearance="?android:textAppearanceLarge"

/>

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello"
android:id="@+id/textView2"
android:gravity="center_horizontal"
android:textAppearance="?android:textAppearanceLarge"
android:layout_below="@+id/editText"
android:layout_centerHorizontal="true"
android:layout_marginTop="54dp" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:id="@+id/button"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true"
android:layout_marginTop="87dp" />
</RelativeLayout>

Activity class

Now let's write the code that invokes another activity and get result from that activity.

File: MainActivity.java

package microsystem.org.srartactivityforresultdemo;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

Email:[email protected]
111 | P a g e APS Microtech Pvt Ltd

public class MainActivity extends ActionBarActivity {


Button b1;
TextView t1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.b1);
t1=(TextView)findViewById(R.id.textView);
b1.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new
Intent(MainActivity.this,SecondActivity.class);
startActivityForResult(i,2);

}
}
);
}

@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what
is passed here it is 2
if(requestCode==2)
{
String
message=data.getStringExtra("MESSAGE");
t1.setText(message);
}

}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

Email:[email protected]
112 | P a g e APS Microtech Pvt Ltd

SecondActivity class

Let's write the code that displays the content of second activity layout file.

File: SecondActivity.java

package microsystem.org.srartactivityforresultdemo;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class SecondActivity extends ActionBarActivity {


EditText e1;
TextView t1;
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
e1=(EditText)findViewById(R.id.editText);
t1=(TextView)findViewById(R.id.textView);
b1=(Button)findViewById(R.id.button);
b1.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
String message=e1.getText().toString();
Intent intent=new Intent();
intent.putExtra("MESSAGE", message);
setResult(2,intent);
finish();//finishing activity

}
}
);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_second, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

Email:[email protected]
113 | P a g e APS Microtech Pvt Ltd

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

Output:

Email:[email protected]
114 | P a g e APS Microtech Pvt Ltd

Android Fragments
Android Fragment is the part of activity, it is also known as sub-activity. There can be
more than one fragment in an activity. Fragments represent multiple screen inside one
activity.

Android fragment lifecycle is affected by activity lifecycle because fragments are included
in activity.

Each fragment has its own life cycle methods that is affected by activity life cycle because
fragments are embedded in activity.

The FragmentManager class is responsible to make interaction between fragment


objects.

Android Fragment Lifecycle

Email:[email protected]
115 | P a g e APS Microtech Pvt Ltd

The lifecycle of android fragment is like the activity lifecycle. There are 12 lifecycle
methods for fragment.

No. Method Description

1) onAttach(Activity) it is called only once when it is attached with activity.

2) onCreate(Bundle) It is used to initialize the fragment.

onCreateView(LayoutInflater, ViewGroup,
3) creates and returns view hierarchy.
Bundle)

4) onActivityCreated(Bundle) It is invoked after the completion of onCreate() method.

It provides information to the fragment that all the saved state of


5) onViewStateRestored(Bundle)
fragment view hierarchy has been restored.

6) onStart() makes the fragment visible.

7) onResume() makes the fragment interactive.

8) onPause() is called when fragment is no longer interactive.

9) onStop() is called when fragment is no longer visible.

10) onDestroyView() allows the fragment to clean up resources.

11) onDestroy() allows the fragment to do final clean up of fragment state.

It is called immediately prior to the fragment no longer being


12) onDetach()
associated with its activity.

Android Fragment Example


Let's have a look at the simple example of android fragment.

activity_main.xml
File: activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"

Email:[email protected]
116 | P a g e APS Microtech Pvt Ltd

android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<fragment
android:id="@+id/fragment2"
android:name="microsystem.org.fragmentsdemo.Fragment2"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1"
/>

<fragment
android:id="@+id/fragment1"
android:name="microsystem.org.fragmentsdemo.Fragment1"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1"
/>

</LinearLayout>
File: fragment1.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"
android:background="#00ff00"
>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="fragment frist"
android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>
File: fragment2.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"
android:background="#0000ff"
>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Second Fragment"
android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

MainActivity class
File: MainActivity.java

package microsystem.org.fragmentsdemo;

Email:[email protected]
117 | P a g e APS Microtech Pvt Ltd

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

File: Fragment1.java

package microsystem.org.fragmentsdemo;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
* Created by Dell1 on 26/05/2016.
*/
public class Fragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment1,container, false);
}

Email:[email protected]
118 | P a g e APS Microtech Pvt Ltd

File: Fragment2.java

package microsystem.org.fragmentsdemo;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
* Created by Dell1 on 26/05/2016.
*/
public class Fragment2 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle
savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment2,container, false);
}

Output:

Second Example:-

Email:[email protected]
119 | P a g e APS Microtech Pvt Ltd

Project Name:-FragmentDemo2

Project Structure

Create these fe in res/layout folder

1)Main_activity.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context="com.amal.fragments.MainActivity">

<fragment
android:layout_height="match_parent"
android:layout_width="240px"
class="microsystem.org.fragmentdemo2.MenuFragment"
android:id="@+id/fragment"/>
<fragment
android:layout_width="240px"
android:layout_height="match_parent"
class="microsystem.org.fragmentdemo2.TextFragment"

Email:[email protected]
120 | P a g e APS Microtech Pvt Ltd

android:id="@+id/fragment2"/>

</LinearLayout>

2)list_fragment.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">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@android:id/list" />
</LinearLayout>
3)text_fragment.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:gravity="center"
android:background="#5ba4e5"
android:layout_height="match_parent">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="40px"
android:textColor="#ffffff"
android:layout_gravity="center"
android:id="@+id/AndroidOs"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#ffffff"
android:textSize="30px"
android:id="@+id/Version"/>

</LinearLayout>

4)MainActivity.java

package microsystem.org.fragmentdemo2;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

Email:[email protected]
121 | P a g e APS Microtech Pvt Ltd

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

5)TextFragment.java

package microsystem.org.fragmentdemo2;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
* Created by Dell1 on 02/06/2016.
*/
public class TextFragment extends Fragment {
TextView text,vers;

@Override

public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle


savedInstanceState) {

View view = inflater.inflate(R.layout.text_fragment, container, false);


text= (TextView) view.findViewById(R.id.AndroidOs);
vers= (TextView)view.findViewById(R.id.Version);

return view;

Email:[email protected]
122 | P a g e APS Microtech Pvt Ltd

}
public void change(String txt, String txt1){
text.setText(txt);
vers.setText(txt1);

}
}

6)MenuFragment.java

package microsystem.org.fragmentdemo2;

import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

/**
* Created by Dell1 on 02/06/2016.
*/
public class MenuFragment extends ListFragment {
String[] AndroidOS = new String[] {
"Cupcake","Donut","Eclair","Froyo","Gingerbread","Honeycomb","Ice Cream
SandWich","Jelly Bean","KitKat" };
String[] Version = new String[]{"1.5","1.6","2.0-2.1","2.2","2.3","3.0-
3.2","4.0","4.1-4.3","4.4"};
@Override

public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle


savedInstanceState) {
View view =inflater.inflate(R.layout.list_fragment, container, false);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, AndroidOS);
setListAdapter(adapter);

return view;

}
@Override
public void onListItemClick(Li`stView l, View v, int position, long id) {
TextFragment txt =
(TextFragment)getFragmentManager().findFragmentById(R.id.fragment2);
txt.change(AndroidOS[position],"Version : "+Version[position]);
getListView().setSelector(android.R.color.holo_blue_dark);
}
}

Android switch button example

Email:[email protected]
123 | P a g e APS Microtech Pvt Ltd

A switch is type of button that can only have two states ON and OFF. You can set the initial state
and then the user can change it. To get the current state you can check if the switch is checked or
not, in addition to that you can attach a OnCheckedChangeListener to the switch to get
notification when the state changes.

Android Screen Layout


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:padding="5dp">

<Switch
android:id="@+id/mySwitch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="20dp"
android:text="Play with the Switch" />

<TextView
android:id="@+id/switchStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/mySwitch"
android:layout_marginTop="22dp"
android:text="Medium Text"

Email:[email protected]
124 | P a g e APS Microtech Pvt Ltd

android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

Android Main Activity


package com.as400samplecode;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Switch;
import android.widget.TextView;

public class MainActivity extends Activity {

private TextView switchStatus;


private Switch mySwitch;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

switchStatus = (TextView) findViewById(R.id.switchStatus);


mySwitch = (Switch) findViewById(R.id.mySwitch);

//set the switch to ON


mySwitch.setChecked(true);
//attach a listener to check for changes in state
mySwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {

@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {

if(isChecked){
switchStatus.setText("Switch is currently ON");
}else{
switchStatus.setText("Switch is currently OFF");
}

}
});

//check the current state before we display the screen


if(mySwitch.isChecked()){
switchStatus.setText("Switch is currently ON");
}
else {
switchStatus.setText("Switch is currently OFF");
}
}

Email:[email protected]
125 | P a g e APS Microtech Pvt Ltd

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

Android Option Menu Example


Android Option Menus are the primary menus of android. They can be used for settings,
search, delete item etc.

Here, we are going to see two examples of option menus. First, the simple option menus
and second, options menus with images.

Here, we are inflating the menu by calling the inflate() method of MenuInflater class. To
perform event handling on menu items, you need to override onOptionsItemSelected()
method of Activity class.

Android Option Menu Example

Let's see how to create menu in android. Let's see the simple option menu example that
contains three menu items.

activity_main.xml

We have only one textview in this file.

File: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</RelativeLayout>

menu_main.xml

Email:[email protected]
126 | P a g e APS Microtech Pvt Ltd

It contains three items as show below. It is created automatically inside the res/menu
directory.

File: menu_main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<item android:id="@+id/action_settings"
android:title="@string/action_settings"
android:orderInCategory="100"
app:showAsAction="never" />
<item android:id="@+id/item1"
android:title="Delete"/>
<item android:id="@+id/item2"
android:title="Select"/>
<item android:id="@+id/item3"
android:title="Remove All"/>

</menu>

Activity class

This class displays the content of menu.xml file and performs event handling on clicking
the menu items.

File: MainActivity.java

package microsystem.org.optionmenufirstdemo;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

Email:[email protected]
127 | P a g e APS Microtech Pvt Ltd

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
// int id = item.getItemId();

switch (item.getItemId()) {
case R.id.item1:
Toast.makeText(getApplicationContext(), "Item 1
Selected", Toast.LENGTH_LONG).show();
return true;
case R.id.item2:
Toast.makeText(getApplicationContext(),"Item 2
Selected",Toast.LENGTH_LONG).show();
return true;
case R.id.item3:
Toast.makeText(getApplicationContext(),"Item 3
Selected",Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}

Output:

Output without clicking on the menu button.

Email:[email protected]
128 | P a g e APS Microtech Pvt Ltd

Output after clicking on the menu button.

Output after clicking on the second menu item .

Email:[email protected]
129 | P a g e APS Microtech Pvt Ltd

Option Menu with Icon

You need to have icon images inside the res/drawable directory. The android:icon element
is used to display the icon on the option menu. You can write the string information in the
strings.xml file. But we have written it inside the menu_main.xml file.

File: menu_main.xml

1. <menu xmlns:androclass="http://schemas.android.com/apk/res/android" >


2. <item android:id="@+id/item1"
3. android:icon="@drawable/add"
4. android:title="Item 1"/>
5. <item android:id="@+id/item2"
6. android:icon="@drawable/minus"
7. android:title="Item 2"/>
8. <item android:id="@+id/item3"
9. android:icon="@drawable/delete"
10. android:title="Item 3"/>
11. </menu>

Email:[email protected]
130 | P a g e APS Microtech Pvt Ltd

Android Context Menu Example


Android context menu appears when user press long click on the element. It is also known
as floating menu.

It doesn't support item shortcuts and icons.

Android Context Menu Example


Let's see the simple example of context menu in android.

activity_main.xml

Drag one listview from the pallete, now the xml file will look like this:

File: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

Email:[email protected]
131 | P a g e APS Microtech Pvt Ltd

android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/listView"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true" />
</RelativeLayout>

Activity class

Let's write the code to display the context menu on press of the listview.

File: MainActivity.java

package microsystem.org.myapplication;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

String sname[]={"Mohan","Rohan","Sohan","Tohan"};
ListView l1;
ArrayAdapter<String> ad;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l1=(ListView)findViewById(R.id.listView);
ad=new
ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,sname);
l1.setAdapter(ad);
registerForContextMenu(l1);
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Select The Action");
menu.add(0, v.getId(), 0, "Call");//groupId, itemId, order,
title
menu.add(0, v.getId(), 0, "SMS");
}

Email:[email protected]
132 | P a g e APS Microtech Pvt Ltd

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onContextItemSelected(MenuItem item){
if(item.getTitle()=="Call"){
Toast.makeText(getApplicationContext(), "calling
code", Toast.LENGTH_LONG).show();
}
else if(item.getTitle()=="SMS"){
Toast.makeText(getApplicationContext(),"sending sms
code",Toast.LENGTH_LONG).show();
}else{
return false;
}
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

Output:

Email:[email protected]
133 | P a g e APS Microtech Pvt Ltd

Output after long press on the listview.

Output after clicking on the context menu.

Email:[email protected]
134 | P a g e APS Microtech Pvt Ltd

Android Popup Menu Example


Android Popup Menu displays the menu below the anchor text if space is available
otherwise above the anchor text. It disappears if you click outside the popup menu.

The android.widget.PopupMenu is the direct subclass of java.lang.Object class.

Android Popup Menu Example

Let's see how to create popup menu in android.

activity_main.xml

It contains only one button.

File: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

Email:[email protected]
135 | P a g e APS Microtech Pvt Ltd

android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show POPUP"
android:id="@+id/btn"
android:layout_marginTop="125dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>

popup_menu.xml

It contains three items as show below. It is created inside the res/menu directory.

File: poupup_menu.xml

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


<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item
android:id="@+id/cut"
android:title="Cut"/>

<item
android:id="@+id/copy"
android:title="Copy"/>

<item
android:id="@+id/paste"
android:title="Paste"/>

</menu>

Activity class

Email:[email protected]
136 | P a g e APS Microtech Pvt Ltd

It displays the popup menu on button click.

File: MainActivity.java

package microsystem.org.popmenudemo;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {


Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

b1=(Button)findViewById(R.id.btn);
b1.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {

PopupMenu popup = new PopupMenu(MainActivity.this,b1);

popup.getMenuInflater().inflate(R.menu.poupup_menu, popup.getMenu());

popup.setOnMenuItemClickListener(
new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem
item) {
Toast.makeText(MainActivity.this,
"You Clicked : " + item.getTitle(), Toast.LENGTH_SHORT).show();
return true;

}
}
);
popup.show();
}
}
);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

Email:[email protected]
137 | P a g e APS Microtech Pvt Ltd

// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

Output:

Email:[email protected]
138 | P a g e APS Microtech Pvt Ltd

Email:[email protected]
139 | P a g e APS Microtech Pvt Ltd

Android Service Tutorial

Android service is a component that is used to perform operations on the background


such as playing music, handle network transactions, interacting content providers etc. It
doesn't has any UI (user interface).

The service runs in the background indefinitely even if application is destroyed.

Moreover, service can be bounded by a component to perform interactivity and inter


process communication (IPC).

The android.app.Service is subclass of ContextWrapper class.

Note: Android service is not a thread or separate process.

Life Cycle of Android Service


There can be two forms of a service.The lifecycle of service can follow two different
paths: started or bound.

1. Started
2. Bound

1) Started Service

A service is started when component (like activity) calls startService() method, now it
runs in the background indefinitely. It is stopped by stopService() method. The service
can stop itself by calling the stopSelf() method.

2) Bound Service

A service is bound when another component (e.g. client) calls bindService() method. The

Email:[email protected]
140 | P a g e APS Microtech Pvt Ltd

client can unbind the service by calling the unbindService() method.

The service cannot be stopped until all clients unbind the service.

Understanding Started and Bound Service by background music example

Suppose, I want to play music in the background, so call startService() method. But I want
to get information of the current song being played, I will bind the service that provides
information about the current song.

Android Service Example


Let's see the example of service in android that plays an audio in the background. Audio
will not be stopped even if you switch to another activity. To stop the audio, you need to
stop the service.

Email:[email protected]
141 | P a g e APS Microtech Pvt Ltd

activity_main.xml

Drag the 3 buttons from the pallete, now the activity_main.xml will look like this:

File: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Service"
android:id="@+id/b1"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="112dp" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop Service"
android:id="@+id/b2"
android:layout_below="@+id/b1"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="next"
android:id="@+id/b3"
android:layout_below="@+id/b2"
android:layout_centerHorizontal="true" />
</RelativeLayout>

activity_next.xml

It is the layout file of next activity.

File: activity_next.xml

It contains only one textview displaying the message Next Page

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"

Email:[email protected]
142 | P a g e APS Microtech Pvt Ltd

android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="microsystem.org.servicedemo.NextActivity">

<TextView android:text= "Next Activity"


android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</RelativeLayout>

Service class

Now create the service implemenation class by inheriting the Service class and
overridding its callback methods.

File: MyService.java

package microsystem.org.servicedemo;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;

/**
* Created by Dell1 on 30/05/2016.
*/
public class MyService extends Service {
MediaPlayer myPlayer;
@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public void onCreate() {
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
myPlayer = MediaPlayer.create(this, R.raw.hello);
myPlayer.setLooping(false); // Set looping
}
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
myPlayer.start();
}
@Override
public void onDestroy() {
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
myPlayer.stop();
}

Email:[email protected]
143 | P a g e APS Microtech Pvt Ltd

Activity class

Now create the MainActivity class to perform event handling. Here, we are writing the
code to start and stop service. Additionally, calling the second activity on buttonNext.

File: MainActivity.java

package microsystem.org.servicedemo;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

public class MainActivity extends ActionBarActivity implements


View.OnClickListener {
Button b1,b2,b3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.b1);
b2=(Button)findViewById(R.id.b2);
b3=(Button)findViewById(R.id.b3);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
b3.setOnClickListener(this);

public void onClick(View src) {


switch (src.getId()) {
case R.id.b1:
startService(new Intent(this, MyService.class));
break;
case R.id.b2:
stopService(new Intent(this, MyService.class));
break;
case R.id.b3:
Intent intent=new Intent(this,NextActivity.class);
startActivity(intent);
break;
}
}

@Override

Email:[email protected]
144 | P a g e APS Microtech Pvt Ltd

public boolean onCreateOptionsMenu(Menu menu) {


// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

NextPage class

Now, create another activity.

File: NextPage.java

package microsystem.org.servicedemo;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class NextActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_next, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement

Email:[email protected]
145 | P a g e APS Microtech Pvt Ltd

if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

Declare the Service in the AndroidManifest.xml file

Finally, declare the service in the manifest file.

File: AndroidManifest.xml

Let's see the complete AndroidManifest.xml file

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="microsystem.org.servicedemo" >

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
<service
android:name=".MyService"
android:enabled="true" />

<activity
android:name=".NextActivity"
android:label="@string/title_activity_next" >
</activity>
</application>

</manifest>

Output:

Email:[email protected]
146 | P a g e APS Microtech Pvt Ltd

Android AlarmManager
Android AlarmManager allows you to access system alarm.

By the help of Android AlarmManager in android, you can schedule your application to
run at a specific time in the future. It works whether your phone is running or not.

The Android AlarmManager holds a CPU wake lock that provides guarantee not to sleep
the phone until broadcast is handled.

Email:[email protected]
147 | P a g e APS Microtech Pvt Ltd

Android AlarmManager Example


Let's see a simple AlarmManager example that runs after a specific time provided by user.

activity_main.xml

You need to drag only a edittext and a button as given below.

File: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<EditText
android:id="@+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="28dp"
android:ems="10"
android:hint="Number of seconds"
android:inputType="numberDecimal"
/>

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/time"
android:layout_below="@+id/time"
android:layout_marginRight="60dp"
android:layout_marginTop="120dp"
android:text="Start" />

</RelativeLayout>

Activity class

The activity class starts the alarm service when user clicks on the button.

File: MainActivity.java

package microsystem.org.alramdemo;

import android.app.AlarmManager;
import android.app.PendingIntent;

Email:[email protected]
148 | P a g e APS Microtech Pvt Ltd

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {


Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
startAlert();
}
}
);
}
public void startAlert(){
EditText text = (EditText) findViewById(R.id.time);
int i = Integer.parseInt(text.getText().toString());
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent =
PendingIntent.getBroadcast(this.getApplicationContext(),234324243,intent,0);
AlarmManager alarmManager = (AlarmManager)
getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+ (i * 1000), pendingIntent);
Toast.makeText(this, "Alarm set in " + i + " seconds",
Toast.LENGTH_LONG).show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}

Email:[email protected]
149 | P a g e APS Microtech Pvt Ltd

Let's create BroadcastReceiver class that starts alarm.

File: MyBroadcastReceiver.java

package microsystem.org.alramdemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.widget.Toast;

/**
* Created by Dell1 on 30/05/2016.
*/
public class MyBroadcastReceiver extends BroadcastReceiver {
MediaPlayer mp;
@Override
public void onReceive(Context context, Intent intent) {
mp=MediaPlayer.create(context, R.raw.hello);
mp.start();
Toast.makeText(context, "Alarm....", Toast.LENGTH_LONG).show();

}
}

File: AndroidManifest.xml

You need to provide a receiver entry in AndroidManifest.xml file.

1. <receiver android:name="MyBroadcastReceiver" >


2. </receiver>

Let's see the full code of AndroidManifest.xml file.

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="microsystem.org.alramdemo" >

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
<receiver android:name="MyBroadcastReceiver" >

Email:[email protected]
150 | P a g e APS Microtech Pvt Ltd

</receiver>

</application>

</manifest>

Output:

Android Timer
Android Count Down Timer Example
1.Create a new project File ->New -> Project ->Android ->Android Application
Project. While creating the new project, name the activity as
TimerActivity(TimerActivity.java) and layout as activity_timer.xml.

2.Now let us design the UI for the TimerActivity i.e activity_timer.xml with a
textview and a button.

activity_timer.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView

android:id="@+id/timer"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerHorizontal="true"

android:layout_centerVertical="true"

android:paddingRight="10dip"

android:textSize="50dp" />

<Button

android:id="@+id/button"

android:layout_width="fill_parent"

Email:[email protected]
151 | P a g e APS Microtech Pvt Ltd

android:layout_height="wrap_content"

android:layout_alignParentBottom="true"

android:layout_alignParentLeft="true"
android:text="Start" />

</RelativeLayout>
3.Now in the TimerActivity we implement the count down timer by extending the
CountDownTimer class.Press Ctrl+Shift+O for missing imports after typing the
code.

TimerActivity.java
package microsystem.org.timerdemo;

import android.app.Activity;
import android.os.CountDownTimer;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements View.OnClickListener {

private CountDownTimer countDownTimer;

private boolean timerHasStarted = false;

private Button startB;

public TextView text;

private final long startTime = 30 * 1000;

private final long interval = 1 * 1000;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

startB = (Button) this.findViewById(R.id.button);

startB.setOnClickListener(this);

text = (TextView) this.findViewById(R.id.timer);

countDownTimer = new MyCountDownTimer(startTime, interval);

text.setText(text.getText() + String.valueOf(startTime / 1000));

Email:[email protected]
152 | P a g e APS Microtech Pvt Ltd

@Override

public void onClick(View v) {

if (!timerHasStarted) {

countDownTimer.start();

timerHasStarted = true;

startB.setText("STOP");

} else {

countDownTimer.cancel();

timerHasStarted = false;

startB.setText("RESTART");

public class MyCountDownTimer extends CountDownTimer {

public MyCountDownTimer(long startTime, long interval) {

super(startTime, interval);

@Override

public void onFinish() {

text.setText("Time's up!");

@Override

public void onTick(long millisUntilFinished) {

text.setText("" + millisUntilFinished / 1000);

Email:[email protected]
153 | P a g e APS Microtech Pvt Ltd

4.Run the project by rightclicking project Run as → android project.

Output:

The output of this example would be similar to the one as follows:

Email:[email protected]
154 | P a g e APS Microtech Pvt Ltd

Android Preferences Example


Android shared preference is used to store and retrieve primitive information. In android,
string, integer, long, number etc. are considered as primitive data type.

Android Shared preferences are used to store data in key and value pair so that we can
retrieve the value on the basis of key.

It is widely used to get information from user such as in settings.

Android Preferences Example


Let's see a simple example of android shared preference.

activity_main.xml

Email:[email protected]
155 | P a g e APS Microtech Pvt Ltd

Drag one textview and two buttons from the pallete.

File: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView2"
android:layout_centerVertical="true"
android:onClick="Save"
android:text="Save" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:onClick="Get"
android:text="Get" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/etEmail"
android:layout_alignBottom="@+id/etEmail"
android:layout_alignLeft="@+id/textView1"
android:text="Email"
android:textAppearance="?android:attr/textAppearanceMedium" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/etEmail"
android:layout_centerVertical="true"
android:layout_marginRight="21dp"
android:onClick="clear"
android:text="Clear" />

<EditText
android:id="@+id/etEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="@+id/textView1"
android:layout_marginTop="36dp"
android:ems="10"

Email:[email protected]
156 | P a g e APS Microtech Pvt Ltd

android:inputType="textEmailAddress" />

<EditText
android:id="@+id/etName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/etEmail"
android:layout_alignLeft="@+id/etEmail"
android:ems="10"
android:inputType="text" />

<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_marginLeft="17dp"
android:layout_marginTop="39dp"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

Preference Demo Activity Class


File: MainActivity.java

package microsystem.org.preferencedemo2;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {


SharedPreferences sharedpreferences;
TextView name;
TextView email;
SharedPreferences.Editor editor;
public static final String mypreference = "mypref";
public static final String Name = "nameKey";
public static final String Email = "emailKey";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (TextView) findViewById(R.id.etName);
email = (TextView) findViewById(R.id.etEmail);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(Email)) {
email.setText(sharedpreferences.getString(Email, ""));

Email:[email protected]
157 | P a g e APS Microtech Pvt Ltd

}
}

public void Save(View view) {


String n = name.getText().toString();
String e = email.getText().toString();
editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Email, e);
editor.commit();

public void clear(View view) {


name = (TextView) findViewById(R.id.etName);
email = (TextView) findViewById(R.id.etEmail);
name.setText("");
email.setText("");
// editor.clear();
//editor.remove(Email);
}

public void Get(View view) {


name = (TextView) findViewById(R.id.etName);
email = (TextView) findViewById(R.id.etEmail);
sharedpreferences =
getSharedPreferences(mypreference,Context.MODE_PRIVATE);

if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(Email)) {
email.setText(sharedpreferences.getString(Email, ""));

}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

Output:

Email:[email protected]
158 | P a g e APS Microtech Pvt Ltd

Android Internal Storage Example


We are able to save or read data from the device internal memory. FileInputStream and
FileOutputStream classes are used to read and write data into the file.

Here, we are going to read and write data to the internal storage of the device.

Email:[email protected]
159 | P a g e APS Microtech Pvt Ltd

Example of reading and writing data to the android internal storage

activity_main.xml

Drag the 2 edittexts, 2 textviews and 2 buttons from the pallete, now the
activity_main.xml file will like this:

File: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="20dp"
android:layout_marginTop="24dp"
android:ems="10" >

<requestFocus />
</EditText>

<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/editText1"
android:layout_below="@+id/editText1"
android:layout_marginTop="24dp"
android:ems="10" />

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText1"
android:layout_alignBottom="@+id/editText1"
android:layout_alignParentLeft="true"
android:text="File Name:" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText2"
android:layout_alignBottom="@+id/editText2"
android:layout_alignParentLeft="true"
android:text="Data:" />

<Button

Email:[email protected]
160 | P a g e APS Microtech Pvt Ltd

android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText2"
android:layout_below="@+id/editText2"
android:layout_marginLeft="70dp"
android:layout_marginTop="16dp"
android:text="save" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button1"
android:layout_alignBottom="@+id/button1"
android:layout_toRightOf="@+id/button1"
android:text="read" />

</RelativeLayout>

Activity class

Let's write the code to write and read data from the internal storage.

File: MainActivity.java

package microsystem.org.internalstroagedemo1;

import android.content.Context;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class MainActivity extends ActionBarActivity {


EditText editTextFileName,editTextData;
Button saveButton,readButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextFileName=(EditText)findViewById(R.id.editText1);
editTextData=(EditText)findViewById(R.id.editText2);
saveButton=(Button)findViewById(R.id.button1);
readButton=(Button)findViewById(R.id.button2);
saveButton.setOnClickListener(

Email:[email protected]
161 | P a g e APS Microtech Pvt Ltd

new View.OnClickListener() {
@Override
public void onClick(View v) {

String
filename=editTextFileName.getText().toString();
String
data=editTextData.getText().toString();

FileOutputStream fos;
try {
fos = openFileOutput(filename,
Context.MODE_PRIVATE);
//default mode is PRIVATE,
can be APPEND etc.
fos.write(data.getBytes());
fos.close();

Toast.makeText(getApplicationContext(), filename + " saved",

Toast.LENGTH_LONG).show();

} catch (FileNotFoundException
e) {e.printStackTrace();}
catch (IOException e)
{e.printStackTrace();}

}
}
);

readButton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
String
filename=editTextFileName.getText().toString();
StringBuffer stringBuffer = new
StringBuffer();
try {
//Attaching BufferedReader to
the FileInputStream by the help of InputStreamReader
BufferedReader inputReader =
new BufferedReader(new InputStreamReader(

openFileInput(filename)));
String inputString;
//Reading data line by line
and storing it into the stringbuffer
while ((inputString =
inputReader.readLine()) != null) {

stringBuffer.append(inputString + "\n");
}

} catch (IOException e) {
e.printStackTrace();
}
//Displaying data on the toast
editTextData.setText(stringBuffer);

Email:[email protected]
162 | P a g e APS Microtech Pvt Ltd

Toast.makeText(getApplicationContext(),stringBuffer.toString(),

Toast.LENGTH_LONG).show();

}
}
);

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

output:-

Email:[email protected]
163 | P a g e APS Microtech Pvt Ltd

Android External Storage Example


Like internal storage, we are able to save or read data from the device external memory
such as sdcard. FileInputStream and FileOutputStream classes are used to read and write
data into the file.

Example of reading and writing data in the android external storage

activity_main.xml

Drag the 2 edittexts, 2 textviews and 2 buttons from the pallete, now the
activity_main.xml file will like this:

File: activity_main.xml

1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.

Email:[email protected]
164 | P a g e APS Microtech Pvt Ltd

7. <EditText
8. android:id="@+id/editText1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentRight="true"
12. android:layout_alignParentTop="true"
13. android:layout_marginRight="20dp"
14. android:layout_marginTop="24dp"
15. android:ems="10" >
16.
17. <requestFocus />
18. </EditText>
19.
20. <EditText
21. android:id="@+id/editText2"
22. android:layout_width="wrap_content"
23. android:layout_height="wrap_content"
24. android:layout_alignRight="@+id/editText1"
25. android:layout_below="@+id/editText1"
26. android:layout_marginTop="24dp"
27. android:ems="10" />
28.
29. <TextView
30. android:id="@+id/textView1"
31. android:layout_width="wrap_content"
32. android:layout_height="wrap_content"
33. android:layout_alignBaseline="@+id/editText1"
34. android:layout_alignBottom="@+id/editText1"
35. android:layout_alignParentLeft="true"
36. android:text="File Name:" />
37.
38. <TextView
39. android:id="@+id/textView2"
40. android:layout_width="wrap_content"
41. android:layout_height="wrap_content"
42. android:layout_alignBaseline="@+id/editText2"
43. android:layout_alignBottom="@+id/editText2"
44. android:layout_alignParentLeft="true"
45. android:text="Data:" />
46.
47. <Button
48. android:id="@+id/button1"
49. android:layout_width="wrap_content"
50. android:layout_height="wrap_content"
51. android:layout_alignLeft="@+id/editText2"
52. android:layout_below="@+id/editText2"
53. android:layout_marginLeft="70dp"

Email:[email protected]
165 | P a g e APS Microtech Pvt Ltd

54. android:layout_marginTop="16dp"
55. android:text="save" />
56.
57. <Button
58. android:id="@+id/button2"
59. android:layout_width="wrap_content"
60. android:layout_height="wrap_content"
61. android:layout_alignBaseline="@+id/button1"
62. android:layout_alignBottom="@+id/button1"
63. android:layout_toRightOf="@+id/button1"
64. android:text="read" />
65.
66. </RelativeLayout>

Provide permission for the external storage

You need to provide the WRITE_EXTERNAL_STORAGE permission.

1. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

File: Activity_Manifest.xml

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


2. <manifest
3.
4. xmlns:android="http://schemas.android.com/apk/res/android"
5. package="com.example.externalstorage"
6. android:versionCode="1"
7. android:versionName="1.0" >
8.
9. <uses-sdk
10. android:minSdkVersion="8"
11. android:targetSdkVersion="16" />
12. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
13.
14. <application
15. android:allowBackup="true"
16. android:icon="@drawable/ic_launcher"
17. android:label="@string/app_name"
18. android:theme="@style/AppTheme" >
19. <activity
20. android:name="com.example.externalstorage.MainActivity"
21. android:label="@string/app_name" >
22. <intent-filter>
23. <action android:name="android.intent.action.MAIN" />

Email:[email protected]
166 | P a g e APS Microtech Pvt Ltd

24.
25. <category android:name="android.intent.category.LAUNCHER" />
26. </intent-filter>
27. </activity>
28. </application>
29.
30. </manifest>

Activity class

Let's write the code to write and read data from the android external storage.

File: MainActivity.java

1. package com.example.externalstorage;
2.
3. import java.io.BufferedReader;
4. import java.io.File;
5. import java.io.FileInputStream;
6. import java.io.FileNotFoundException;
7. import java.io.FileOutputStream;
8. import java.io.IOException;
9. import java.io.InputStreamReader;
10. import java.io.OutputStreamWriter;
11.
12. import android.os.Bundle;
13. import android.app.Activity;
14. import android.content.Context;
15. import android.view.Menu;
16. import android.view.View;
17. import android.view.View.OnClickListener;
18. import android.widget.Button;
19. import android.widget.EditText;
20. import android.widget.Toast;
21.
22. public class MainActivity extends Activity {
23. EditText editTextFileName,editTextData;
24. Button saveButton,readButton;
25. @Override
26. protected void onCreate(Bundle savedInstanceState) {
27. super.onCreate(savedInstanceState);
28. setContentView(R.layout.activity_main);
29.
30. editTextFileName=(EditText)findViewById(R.id.editText1);
31. editTextData=(EditText)findViewById(R.id.editText2);
32. saveButton=(Button)findViewById(R.id.button1);
33. readButton=(Button)findViewById(R.id.button2);

Email:[email protected]
167 | P a g e APS Microtech Pvt Ltd

34.
35. //Performing action on save button
36. saveButton.setOnClickListener(new OnClickListener(){
37.
38. @Override
39. public void onClick(View arg0) {
40. String filename=editTextFileName.getText().toString();
41. String data=editTextData.getText().toString();
42.
43. FileOutputStream fos;
44. try {
45. File myFile = new File("/sdcard/"+filename);
46. myFile.createNewFile();
47. FileOutputStream fOut = new
48.
49. FileOutputStream(myFile);
50. OutputStreamWriter myOutWriter = new
51.
52. OutputStreamWriter(fOut);
53. myOutWriter.append(data);
54. myOutWriter.close();
55. fOut.close();
56.
57. Toast.makeText(getApplicationContext(),filename + "
58.
59. saved",Toast.LENGTH_LONG).show();
60.
61.
62. } catch (FileNotFoundException e) {e.printStackTrace();}
63. catch (IOException e) {e.printStackTrace();}
64.
65. }
66.
67. });
68.
69. //Performing action on Read Button
70. readButton.setOnClickListener(new OnClickListener(){
71.
72. @Override
73. public void onClick(View arg0) {
74. String filename=editTextFileName.getText().toString();
75. StringBuffer stringBuffer = new StringBuffer();
76. String aDataRow = "";
77. String aBuffer = "";
78. try {
79. File myFile = new File("/sdcard/"+filename);
80. FileInputStream fIn = new FileInputStream(myFile);

Email:[email protected]
168 | P a g e APS Microtech Pvt Ltd

81. BufferedReader myReader = new BufferedReader(


82. new InputStreamReader(fIn));
83.
84. while ((aDataRow = myReader.readLine()) != null) {
85. aBuffer += aDataRow + "\n";
86. }
87. myReader.close();
88.
89. } catch (IOException e) {
90. e.printStackTrace();
91. }
92. Toast.makeText(getApplicationContext
93.
94. (),aBuffer,Toast.LENGTH_LONG).show();
95.
96. }
97.
98. });
99. }
100.
101. @Override
102. public boolean onCreateOptionsMenu(Menu menu) {
103. // Inflate the menu; this adds items to the action bar if it is present.
104. getMenuInflater().inflate(R.menu.activity_main, menu);
105. return true;
106. }
107.
108. }

Email:[email protected]
169 | P a g e APS Microtech Pvt Ltd

Android SQLite Tutorial


SQLite is an open-source relational database i.e. used to perform database operations
on android devices such as storing, manipulating or retrieving persistent data from the
database.

It is embedded in android bydefault. So, there is no need to perform any database setup or
administration task.

Here, we are going to see the example of sqlite to store and fetch the data. Data is
displayed in the logcat. For displaying data on the spinner or listview, move to the next
page.

SQLiteOpenHelper class provides the functionality to use the SQLite database.

SQLiteOpenHelper class
The android.database.sqlite.SQLiteOpenHelper class is used for database creation and
version management. For performing any database operation, you have to provide the
implementation of onCreate() and onUpgrade() methods of SQLiteOpenHelper class.

Constructors of SQLiteOpenHelper class

Email:[email protected]
170 | P a g e APS Microtech Pvt Ltd

There are two constructors of SQLiteOpenHelper class.

Constructor Description

SQLiteOpenHelper(Context context, String name, creates an object for creating, opening and
SQLiteDatabase.CursorFactory factory, int version) managing the database.

SQLiteOpenHelper(Context context, String name, creates an object for creating, opening and
SQLiteDatabase.CursorFactory factory, int version, managing the database. It specifies the
DatabaseErrorHandler errorHandler) error handler.

Methods of SQLiteOpenHelper class

There are many methods in SQLiteOpenHelper class. Some of them are as follows:

Method Description

called only once when database is created for


public abstract void onCreate(SQLiteDatabase db)
the first time.

public abstract void onUpgrade(SQLiteDatabase db, int oldVersion,


called when database needs to be upgraded.
int newVersion)

public synchronized void close () closes the database object.

public void onDowngrade(SQLiteDatabase db, int oldVersion, int called when database needs to be
newVersion) downgraded.

SQLiteDatabase class
It contains methods to be performed on sqlite database such as create, update, delete,
select etc.

Methods of SQLiteDatabase class

There are many methods in SQLiteDatabase class. Some of them are as follows:

Method Description

Email:[email protected]
171 | P a g e APS Microtech Pvt Ltd

void execSQL(String sql) executes the sql query not select query.

inserts a record on the database. The table specifies the table name,
long insert(String table, String nullColumnHack doesn't allow completely null values. If second
nullColumnHack, ContentValues values) argument is null, android will store null values if values are empty. The
third argument specifies the values to be stored.

int update(String table, ContentValues


values, String whereClause, String[] updates a row.
whereArgs)

Cursor query(String table, String[] columns,


String selection, String[] selectionArgs,
returns a cursor over the resultset.
String groupBy, String having, String
orderBy)

Example of android SQLite database

Let's see the simple example of android sqlite database.

File: Contact.java

1. package com.example.sqlite;
2. public class Contact {
3. int _id;
4. String _name;
5. String _phone_number;
6. public Contact(){ }
7. public Contact(int id, String name, String _phone_number){
8. this._id = id;
9. this._name = name;
10. this._phone_number = _phone_number;
11. }
12.
13. public Contact(String name, String _phone_number){
14. this._name = name;
15. this._phone_number = _phone_number;
16. }
17. public int getID(){
18. return this._id;
19. }
20.
21. public void setID(int id){

Email:[email protected]
172 | P a g e APS Microtech Pvt Ltd

22. this._id = id;


23. }
24.
25. public String getName(){
26. return this._name;
27. }
28.
29. public void setName(String name){
30. this._name = name;
31. }
32.
33. public String getPhoneNumber(){
34. return this._phone_number;
35. }
36.
37. public void setPhoneNumber(String phone_number){
38. this._phone_number = phone_number;
39. }
40. }

File: DatabaseHandler.java

Now, let's create the database handler class that extends SQLiteOpenHelper class and
provides the implementation of its methods.

1. package com.example.sqlite;
2. import java.util.ArrayList;
3. import java.util.List;
4.
5. import android.content.ContentValues;
6. import android.content.Context;
7. import android.database.Cursor;
8. import android.database.sqlite.SQLiteDatabase;
9. import android.database.sqlite.SQLiteOpenHelper;
10.
11. public class DatabaseHandler extends SQLiteOpenHelper {
12. private static final int DATABASE_VERSION = 1;
13. private static final String DATABASE_NAME = "contactsManager";
14. private static final String TABLE_CONTACTS = "contacts";
15. private static final String KEY_ID = "id";
16. private static final String KEY_NAME = "name";
17. private static final String KEY_PH_NO = "phone_number";
18.
19. public DatabaseHandler(Context context) {
20. super(context, DATABASE_NAME, null, DATABASE_VERSION);
21. //3rd argument to be passed is CursorFactory instance
22. }

Email:[email protected]
173 | P a g e APS Microtech Pvt Ltd

23.
24. // Creating Tables
25. @Override
26. public void onCreate(SQLiteDatabase db) {
27. String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
28. + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
29. + KEY_PH_NO + " TEXT" + ")";
30. db.execSQL(CREATE_CONTACTS_TABLE);
31. }
32.
33. // Upgrading database
34. @Override
35. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
36. // Drop older table if existed
37. db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
38.
39. // Create tables again
40. onCreate(db);
41. }
42.
43. // code to add the new contact
44. void addContact(Contact contact) {
45. SQLiteDatabase db = this.getWritableDatabase();
46.
47. ContentValues values = new ContentValues();
48. values.put(KEY_NAME, contact.getName()); // Contact Name
49. values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
50.
51. // Inserting Row
52. db.insert(TABLE_CONTACTS, null, values);
53. //2nd argument is String containing nullColumnHack
54. db.close(); // Closing database connection
55. }
56.
57. // code to get the single contact
58. Contact getContact(int id) {
59. SQLiteDatabase db = this.getReadableDatabase();
60.
61. Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
62. KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
63. new String[] { String.valueOf(id) }, null, null, null, null);
64. if (cursor != null)
65. cursor.moveToFirst();
66.
67. Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
68. cursor.getString(1), cursor.getString(2));
69. // return contact

Email:[email protected]
174 | P a g e APS Microtech Pvt Ltd

70. return contact;


71. }
72.
73. // code to get all contacts in a list view
74. public List<Contact> getAllContacts() {
75. List<Contact> contactList = new ArrayList<Contact>();
76. // Select All Query
77. String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
78.
79. SQLiteDatabase db = this.getWritableDatabase();
80. Cursor cursor = db.rawQuery(selectQuery, null);
81.
82. // looping through all rows and adding to list
83. if (cursor.moveToFirst()) {
84. do {
85. Contact contact = new Contact();
86. contact.setID(Integer.parseInt(cursor.getString(0)));
87. contact.setName(cursor.getString(1));
88. contact.setPhoneNumber(cursor.getString(2));
89. // Adding contact to list
90. contactList.add(contact);
91. } while (cursor.moveToNext());
92. }
93.
94. // return contact list
95. return contactList;
96. }
97.
98. // code to update the single contact
99. public int updateContact(Contact contact) {
100. SQLiteDatabase db = this.getWritableDatabase();
101.
102. ContentValues values = new ContentValues();
103. values.put(KEY_NAME, contact.getName());
104. values.put(KEY_PH_NO, contact.getPhoneNumber());
105.
106. // updating row
107. return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
108. new String[] { String.valueOf(contact.getID()) });
109. }
110.
111. // Deleting single contact
112. public void deleteContact(Contact contact) {
113. SQLiteDatabase db = this.getWritableDatabase();
114. db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
115. new String[] { String.valueOf(contact.getID()) });
116. db.close();

Email:[email protected]
175 | P a g e APS Microtech Pvt Ltd

117. }
118.
119. // Getting contacts Count
120. public int getContactsCount() {
121. String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
122. SQLiteDatabase db = this.getReadableDatabase();
123. Cursor cursor = db.rawQuery(countQuery, null);
124. cursor.close();
125.
126. // return count
127. return cursor.getCount();
128. }
129.
130. }

File: MainActivity.java

1. package com.example.sqlite;
2.
3. import java.util.List;
4.
5. import android.os.Bundle;
6. import android.app.Activity;
7. import android.util.Log;
8. import android.view.Menu;
9.
10. public class MainActivity extends Activity {
11.
12. @Override
13. protected void onCreate(Bundle savedInstanceState) {
14. super.onCreate(savedInstanceState);
15. setContentView(R.layout.activity_main);
16.
17. DatabaseHandler db = new DatabaseHandler(this);
18.
19. // Inserting Contacts
20. Log.d("Insert: ", "Inserting ..");
21. db.addContact(new Contact("Ravi", "9100000000"));
22. db.addContact(new Contact("Srinivas", "9199999999"));
23. db.addContact(new Contact("Tommy", "9522222222"));
24. db.addContact(new Contact("Karthik", "9533333333"));
25.
26. // Reading all contacts
27. Log.d("Reading: ", "Reading all contacts..");
28. List<Contact> contacts = db.getAllContacts();
29.
30. for (Contact cn : contacts) {

Email:[email protected]
176 | P a g e APS Microtech Pvt Ltd

31. String log = "Id: "+cn.getID()+" ,Name: " + cn.getName() + " ,Phone: " +
32. cn.getPhoneNumber();
33. // Writing Contacts to log
34. Log.d("Name: ", log);
35. }
36. }
37.
38. @Override
39. public boolean onCreateOptionsMenu(Menu menu) {
40. // Inflate the menu; this adds items to the action bar if it is present.
41. getMenuInflater().inflate(R.menu.activity_main, menu);
42. return true;
43. }
44.
45. }

download this sqlite example

Output:

Open Logcat and see the output. It is the basic example of android sqlite without any GUI.

For GUI application with android SQLite, visit next page.

Output:

Email:[email protected]
177 | P a g e APS Microtech Pvt Ltd

Android Sqlite Example


In this example, we are adding a label on button click and displaying all the added labels
on the spinner. As you have seen in the previous example, SQLiteOpenHelper class need
to be extended for performing operations on the sqlite.

We have overridden the onCreate() and onUpgrade() method of SQLiteOpenHelper class


in the DatabaseHandler class that provides additional methods to insert and display the
labels or data.

Email:[email protected]
178 | P a g e APS Microtech Pvt Ltd

Simple Insert Operation


1)avtivity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/et1"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:hint="Name"
/>

<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/et2"
android:layout_below="@+id/et1"
android:layout_centerHorizontal="true"
android:layout_marginTop="84dp"
android:hint="Mobile"
/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Insert"
android:id="@+id/button"
android:layout_below="@+id/et2"
android:layout_centerHorizontal="true"
android:layout_marginTop="106dp"
android:onClick="addContact"
/>

</RelativeLayout>

2)UserConrtact.java

package microsystem.org.databasedemo;

/**
* Created by Dell1 on 16/05/2016.
*/
public class UserContract {

public static abstract class NewUserInfo{


public static final String USER_NAME="user_name";
public static final String USER_MOB="user_mob";
public static final String TABLE_NAME="user_info";
}

Email:[email protected]
179 | P a g e APS Microtech Pvt Ltd

3)UserDbHelper.java

package microsystem.org.databasedemo;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
* Created by Dell1 on 16/05/2016.
*/
public class UserDBHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME="USERINFO.DB";


public static final int DATABASE_VERSION=1;
private static final String C_QUERY=
"CREATE TABLE
"+UserContract.NewUserInfo.TABLE_NAME+"("+UserContract.NewUserInfo.USER_NAME+"
TEXT,"+UserContract.NewUserInfo.USER_MOB+" TEXT);";
public UserDBHelper(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
Log.e("DATABASE OPERATION", "Database create ");

}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(C_QUERY);
Log.e("DATABASE OPERATION", "Table created ");
}

public void addInformation(String user,String umob,SQLiteDatabase db){


ContentValues cv=new ContentValues();
cv.put(UserContract.NewUserInfo.USER_NAME,user);
cv.put(UserContract.NewUserInfo.USER_MOB,umob);
db.insert(UserContract.NewUserInfo.TABLE_NAME, null, cv);
Log.e("DATABASE OPERATION", "1 Row Inserted");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}
}

4)MainActivity.java

package microsystem.org.databasedemo;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;

Email:[email protected]
180 | P a g e APS Microtech Pvt Ltd

import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

Context c=this;
UserDBHelper ub;
SQLiteDatabase db;
EditText ed1,ed2;
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1=(EditText)findViewById(R.id.et1);
ed2=(EditText)findViewById(R.id.et2);
b1=(Button)findViewById(R.id.button);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public void addContact(View v)
{
String user=ed1.getText().toString();
String mob=ed2.getText().toString();
ub=new UserDBHelper(c);
db=ub.getWritableDatabase();
ub.addInformation(user,mob,db);
Toast.makeText(getBaseContext(),"Data Save",Toast.LENGTH_LONG).show();
ub.close();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

Email:[email protected]
181 | P a g e APS Microtech Pvt Ltd

Android Sqlite Spinner Example

Let's see the simple code to add and display the string content on spinner using sqlite
database.

activity_main.xml
File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <!-- Label -->
8. <TextView
9. android:layout_width="fill_parent"
10. android:layout_height="wrap_content"
11. android:text="Add New Label"
12. android:padding="8dip" />
13.
14. <!-- Input Text -->
15. <EditText android:id="@+id/input_label"
16. android:layout_width="fill_parent"
17. android:layout_height="wrap_content"
18. android:layout_marginLeft="8dip"
19. android:layout_marginRight="8dip"/>
20.
21. <Spinner
22. android:id="@+id/spinner"
23. android:layout_width="fill_parent"
24. android:layout_height="wrap_content"
25. android:layout_alignParentLeft="true"
26. android:layout_below="@+id/btn_add"
27. android:layout_marginTop="23dp" />
28.
29. <Button
30. android:id="@+id/btn_add"
31. android:layout_width="wrap_content"
32. android:layout_height="wrap_content"
33. android:layout_below="@+id/input_label"
34. android:layout_centerHorizontal="true"
35. android:text="Add Item" />
36.
37. </RelativeLayout>

Email:[email protected]
182 | P a g e APS Microtech Pvt Ltd

Activity class
File: MainActivity.java

1. package com.example.sqlitespinner;
2.
3. import android.os.Bundle;
4. import android.app.Activity;
5. import android.view.Menu;
6. import java.util.List;
7. import android.content.Context;
8. import android.view.View;
9. import android.view.inputmethod.InputMethodManager;
10. import android.widget.AdapterView;
11. import android.widget.AdapterView.OnItemSelectedListener;
12. import android.widget.ArrayAdapter;
13. import android.widget.Button;
14. import android.widget.EditText;
15. import android.widget.Spinner;
16. import android.widget.Toast;
17.
18. public class MainActivity extends Activity implements OnItemSelectedListener{
19. Spinner spinner;
20. Button btnAdd;
21. EditText inputLabel;
22.
23. @Override
24. public void onCreate(Bundle savedInstanceState) {
25. super.onCreate(savedInstanceState);
26. setContentView(R.layout.activity_main);
27.
28. spinner = (Spinner) findViewById(R.id.spinner);
29. btnAdd = (Button) findViewById(R.id.btn_add);
30. inputLabel = (EditText) findViewById(R.id.input_label);
31.
32. spinner.setOnItemSelectedListener(this);
33.
34. // Loading spinner data from database
35. loadSpinnerData();
36.
37. btnAdd.setOnClickListener(new View.OnClickListener() {
38.
39. @Override
40. public void onClick(View arg0) {
41. String label = inputLabel.getText().toString();
42.

Email:[email protected]
183 | P a g e APS Microtech Pvt Ltd

43. if (label.trim().length() > 0) {


44. DatabaseHandler db = new DatabaseHandler(getApplicationContext());
45. db.insertLabel(label);
46.
47. // making input filed text to blank
48. inputLabel.setText("");
49.
50. // Hiding the keyboard
51. InputMethodManager imm = (InputMethodManager)
52. getSystemService(Context.INPUT_METHOD_SERVICE);
53. imm.hideSoftInputFromWindow(inputLabel.getWindowToken(), 0);
54.
55. // loading spinner with newly added data
56. loadSpinnerData();
57. } else {
58. Toast.makeText(getApplicationContext(), "Please enter label name",
59. Toast.LENGTH_SHORT).show();
60. }
61.
62. }
63. });
64. }
65.
66. /**
67. * Function to load the spinner data from SQLite database
68. * */
69. private void loadSpinnerData() {
70. DatabaseHandler db = new DatabaseHandler(getApplicationContext());
71. List<String> labels = db.getAllLabels();
72.
73. // Creating adapter for spinner
74. ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layou
t.simple_spinner_item, labels);
75.
76. // Drop down layout style - list view with radio button
77. dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdow
n_item);
78.
79. // attaching data adapter to spinner
80. spinner.setAdapter(dataAdapter);
81. }
82.
83. @Override
84. public void onItemSelected(AdapterView<?> parent, View view, int position,
85. long id) {
86. // On selecting a spinner item
87. String label = parent.getItemAtPosition(position).toString();

Email:[email protected]
184 | P a g e APS Microtech Pvt Ltd

88.
89. // Showing selected spinner item
90. Toast.makeText(parent.getContext(), "You selected: " + label,
91. Toast.LENGTH_LONG).show();
92.
93. }
94.
95. @Override
96. public void onNothingSelected(AdapterView<?> arg0) {
97. // TODO Auto-generated method stub
98.
99. }
100. @Override
101. public boolean onCreateOptionsMenu(Menu menu) {
102. // Inflate the menu; this adds items to the action bar if it is present.
103. getMenuInflater().inflate(R.menu.activity_main, menu);
104. return true;
105. }
106.
107. }

DatabaseHandler class
File: DatabaseHandler.java

1. package com.example.sqlitespinner2;
2. import java.util.ArrayList;
3. import java.util.List;
4. import android.content.ContentValues;
5. import android.content.Context;
6. import android.database.Cursor;
7. import android.database.sqlite.SQLiteDatabase;
8. import android.database.sqlite.SQLiteOpenHelper;
9.
10. public class DatabaseHandler extends SQLiteOpenHelper {
11. private static final int DATABASE_VERSION = 1;
12. private static final String DATABASE_NAME = "spinnerExample";
13. private static final String TABLE_NAME = "labels";
14. private static final String COLUMN_ID = "id";
15. private static final String COLUMN_NAME = "name";
16.
17. public DatabaseHandler(Context context) {
18. super(context, DATABASE_NAME, null, DATABASE_VERSION);
19. }
20.
21. // Creating Tables
22. @Override
23. public void onCreate(SQLiteDatabase db) {

Email:[email protected]
185 | P a g e APS Microtech Pvt Ltd

24. // Category table create query


25. String CREATE_ITEM_TABLE = "CREATE TABLE " + TABLE_NAME + "("
26. + COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_NAME + " TEXT)";
27. db.execSQL(CREATE_ITEM_TABLE);
28. }
29.
30. // Upgrading database
31. @Override
32. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
33. // Drop older table if existed
34. db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
35.
36. // Create tables again
37. onCreate(db);
38. }
39.
40. /**
41. * Inserting new lable into lables table
42. * */
43. public void insertLabel(String label){
44. SQLiteDatabase db = this.getWritableDatabase();
45.
46. ContentValues values = new ContentValues();
47. values.put(COLUMN_NAME, label);//column name, column value
48.
49. // Inserting Row
50. db.insert(TABLE_NAME, null, values);//tableName, nullColumnHack, CotentValues
51. db.close(); // Closing database connection
52. }
53.
54. /**
55. * Getting all labels
56. * returns list of labels
57. * */
58. public List<String> getAllLabels(){
59. List<String> list = new ArrayList<String>();
60.
61. // Select All Query
62. String selectQuery = "SELECT * FROM " + TABLE_NAME;
63.
64. SQLiteDatabase db = this.getReadableDatabase();
65. Cursor cursor = db.rawQuery(selectQuery, null);//selectQuery,selectedArguments
66.
67. // looping through all rows and adding to list
68. if (cursor.moveToFirst()) {
69. do {
70. list.add(cursor.getString(1));//adding 2nd column data

Email:[email protected]
186 | P a g e APS Microtech Pvt Ltd

71. } while (cursor.moveToNext());


72. }
73. // closing connection
74. cursor.close();
75. db.close();
76.
77. // returning lables
78. return list;
79. }
80. }

download this android example

Output:

Email:[email protected]
187 | P a g e APS Microtech Pvt Ltd

Email:[email protected]
188 | P a g e APS Microtech Pvt Ltd

Android XML Parsing using SAX Parser


Android provides the facility to parse the xml file using SAX, DOM etc. parsers. The
SAX parser cannot be used to create the XML file, It can be used to parse the xml file
only.

Advantage of SAX Parser over DOM

It consumes less memory than DOM.

Example of android SAX Xml parsing

activity_main.xml

Drag the one textview from the pallete. Now the activity_main.xml file will look like this:

File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <TextView
8. android:id="@+id/textView1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentLeft="true"
12. android:layout_alignParentTop="true"
13. android:layout_marginLeft="75dp"
14. android:layout_marginTop="46dp"
15. android:text="TextView" />
16.
17. </RelativeLayout>

xml document

Create an xml file named file.xml inside the assets directory of your project.

File: file.xml

Email:[email protected]
189 | P a g e APS Microtech Pvt Ltd

1. <?xml version="1.0"?>
2. <records>
3. <employee>
4. <name>Sachin Kumar</name>
5. <salary>50000</salary>
6. </employee>
7. <employee>
8. <name>Rahul Kumar</name>
9. <salary>60000</salary>
10. </employee>
11. <employee>
12. <name>John Mike</name>
13. <salary>70000</salary>
14. </employee>
15. </records>

Activity class

Now write the code to parse the xml using sax parser.

File: MainActivity.java

1. package com.javatpoint.saxxmlparsing;
2.
3.
4. import java.io.InputStream;
5. import javax.xml.parsers.SAXParser;
6. import javax.xml.parsers.SAXParserFactory;
7. import org.xml.sax.Attributes;
8. import org.xml.sax.SAXException;
9. import org.xml.sax.helpers.DefaultHandler;
10. import android.app.Activity;
11. import android.os.Bundle;
12. import android.widget.TextView;
13. public class MainActivity extends Activity {
14. TextView tv;
15. @Override
16.
17. public void onCreate(Bundle savedInstanceState) {
18. super.onCreate(savedInstanceState);
19. setContentView(R.layout.activity_main);
20. tv=(TextView)findViewById(R.id.textView1);
21. try {
22. SAXParserFactory factory = SAXParserFactory.newInstance();
23.

Email:[email protected]
190 | P a g e APS Microtech Pvt Ltd

24. SAXParser saxParser = factory.newSAXParser();


25.
26.
27. DefaultHandler handler = new DefaultHandler() {
28.
29. boolean name = false;
30.
31. boolean salary = false;
32.
33.
34. public void startElement(String uri, String localName,String qName,
35. Attributes attributes) throws SAXException {
36. if (qName.equalsIgnoreCase("name"))
37. {
38. name = true;
39. }
40. if (qName.equalsIgnoreCase("salary"))
41. {
42. salary = true;
43. }
44. }//end of startElement method
45. public void endElement(String uri, String localName,
46. String qName) throws SAXException {
47. }
48.
49. public void characters(char ch[], int start, int length) throws SAXException {
50. if (name) {
51.
52. tv.setText(tv.getText()+"\n\n Name : " + new String(ch, start, length));
53. name = false;
54. }
55. if (salary) {
56. tv.setText(tv.getText()+"\n Salary : " + new String(ch, start, length));
57. salary = false;
58. }
59. }//end of characters
60. method
61. };//end of DefaultHandler object
62.
63. InputStream is = getAssets().open("file.xml");
64. saxParser.parse(is, handler);
65.
66. } catch (Exception e) {e.printStackTrace();}
67. }
68. }

Email:[email protected]
191 | P a g e APS Microtech Pvt Ltd

download this example

Output:

Email:[email protected]
192 | P a g e APS Microtech Pvt Ltd

Android XML Parsing using DOM Parser


We can parse the xml document by dom parser also. It can be used to create and parse the
xml file.

Advantage of DOM Parser over SAX

It can be used to create and parse the xml file both but SAX parser can only be used to
parse the xml file.

Disadvantage of DOM Parser over SAX

It consumes more memory than SAX.

Example of android DOM Xml parsing

activity_main.xml

Drag the one textview from the pallete. Now the activity_main.xml file will look like this:

File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <TextView
8. android:id="@+id/textView1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentLeft="true"
12. android:layout_alignParentTop="true"
13. android:layout_marginLeft="75dp"
14. android:layout_marginTop="46dp"
15. android:text="TextView" />
16.
17. </RelativeLayout>

xml document

Email:[email protected]
193 | P a g e APS Microtech Pvt Ltd

Create an xml file named file.xml inside the assets directory of your project.

File: file.xml

1. <?xml version="1.0"?>
2. <records>
3. <employee>
4. <name>Sachin Kumar</name>
5. <salary>50000</salary>
6. </employee>
7. <employee>
8. <name>Rahul Kumar</name>
9. <salary>60000</salary>
10. </employee>
11. <employee>
12. <name>John Mike</name>
13. <salary>70000</salary>
14. </employee>
15. </records>

Activity class

Let's write the code to parse the xml using dom parser.

File: MainActivity.java

1. package com.javatpoint.domxmlparsing;
2. import java.io.InputStream;
3.
4. import javax.xml.parsers.DocumentBuilder;
5. import javax.xml.parsers.DocumentBuilderFactory;
6. import org.w3c.dom.Document;
7. import org.w3c.dom.Element;
8. import org.w3c.dom.Node;
9. import org.w3c.dom.NodeList;
10. import android.app.Activity;
11. import android.os.Bundle;
12. import android.widget.TextView;
13.
14. public class MainActivity extends Activity {
15. TextView tv1;
16.
17. @Override
18. public void onCreate(Bundle savedInstanceState) {

Email:[email protected]
194 | P a g e APS Microtech Pvt Ltd

19. super.onCreate(savedInstanceState);
20. setContentView(R.layout.activity_main);
21. tv1=(TextView)findViewById(R.id.textView1);
22. try {
23. InputStream is = getAssets().open("file.xml");
24.
25. DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
26. DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
27. Document doc = dBuilder.parse(is);
28.
29. Element element=doc.getDocumentElement();
30. element.normalize();
31.
32. NodeList nList = doc.getElementsByTagName("employee");
33. for (int i=0; i<nList.getLength(); i++) {
34.
35. Node node = nList.item(i);
36. if (node.getNodeType() == Node.ELEMENT_NODE) {
37. Element element2 = (Element) node;
38. tv1.setText(tv1.getText()+"\nName : " + getValue("name", element2)+"\n");
39. tv1.setText(tv1.getText()+"Salary : " + getValue("salary", element2)+"\n");
40. tv1.setText(tv1.getText()+"-----------------------");
41. }
42. }//end of for loop
43.
44. } catch (Exception e) {e.printStackTrace();}
45.
46. }
47. private static String getValue(String tag, Element element) {
48. NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();
49. Node node = (Node) nodeList.item(0);
50. return node.getNodeValue();
51. }
52.
53. }

download this example

Output:

Email:[email protected]
195 | P a g e APS Microtech Pvt Ltd

Email:[email protected]
196 | P a g e APS Microtech Pvt Ltd

Android XMLPullParser Tutorial


Android recommends to use XMLPullParser to parse the xml file than SAX and DOM
because it is fast.

The org.xmlpull.v1.XmlPullParser interface provides the functionality to parse the XML


document using XMLPullParser.

Events of XmlPullParser

The next() method of XMLPullParser moves the cursor pointer to the next event.
Generally, we use four constants (works as the event) defined in the XMLPullParser
interface.

START_TAG :An XML start tag was read.

TEXT :Text content was read; the text content can be retrieved using the getText()
method.

END_TAG : An end tag was read.

END_DOCUMENT :No more events are available

Example of android XMLPullParser

activity_main.xml

Drag the one listview from the pallete. Now the activity_main.xml file will look like this:

File: activity_main.xml

1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <ListView
8. android:id="@+id/listView1"
9. android:layout_width="match_parent"
10. android:layout_height="wrap_content" >
11.
12. </ListView>

Email:[email protected]
197 | P a g e APS Microtech Pvt Ltd

13.
14. </RelativeLayout>

xml document

Create an xml file named employees.xml inside the assets directory of your project.

File: employees.xml

1. <?xml version="1.0" encoding="UTF-8"?>


2. <employees>
3. <employee>
4. <id>1</id>
5. <name>Sachin</name>
6. <salary>50000</salary>
7. </employee>
8. <employee>
9. <id>2</id>
10. <name>Nikhil</name>
11. <salary>60000</salary>
12. </employee>
13.
14. </employees>

Employee class

Now create the Employee class that corresponds to the xml file.

File: Employee.java

1. package com.example.xmlpullparsing;
2. public class Employee {
3. private int id;
4. private String name;
5. private float salary;
6. public int getId() {
7. return id;
8. }
9. public void setId(int id) {
10. this.id = id;
11. }
12. public String getName() {
13. return name;

Email:[email protected]
198 | P a g e APS Microtech Pvt Ltd

14. }
15. public void setName(String name) {
16. this.name = name;
17. }
18. public float getSalary() {
19. return salary;
20. }
21. public void setSalary(float salary) {
22. this.salary = salary;
23. }
24.
25. @Override
26. public String toString() {
27. return " Id= "+id + "\n Name= " + name + "\n Salary= " + salary;
28. }
29. }

XMLPullParserHandler class

Now write the code to parse the xml file using XMLPullParser. Here, we are returning all
the employee in list.

File: XMLPullParserHandler.java

1. package com.example.xmlpullparsing;
2. import java.io.IOException;
3. import java.io.InputStream;
4. import java.util.ArrayList;
5. import java.util.List;
6. import org.xmlpull.v1.XmlPullParser;
7. import org.xmlpull.v1.XmlPullParserException;
8. import org.xmlpull.v1.XmlPullParserFactory;
9.
10.
11. public class XmlPullParserHandler {
12. private List<Employee> employees= new ArrayList<Employee>();
13. private Employee employee;
14. private String text;
15.
16. public List<Employee> getEmployees() {
17. return employees;
18. }
19.
20. public List<Employee> parse(InputStream is) {
21. try {

Email:[email protected]
199 | P a g e APS Microtech Pvt Ltd

22. XmlPullParserFactory factory = XmlPullParserFactory.newInstance();


23. factory.setNamespaceAware(true);
24. XmlPullParser parser = factory.newPullParser();
25.
26. parser.setInput(is, null);
27.
28. int eventType = parser.getEventType();
29. while (eventType != XmlPullParser.END_DOCUMENT) {
30. String tagname = parser.getName();
31. switch (eventType) {
32. case XmlPullParser.START_TAG:
33. if (tagname.equalsIgnoreCase("employee")) {
34. // create a new instance of employee
35. employee = new Employee();
36. }
37. break;
38.
39. case XmlPullParser.TEXT:
40. text = parser.getText();
41. break;
42.
43. case XmlPullParser.END_TAG:
44. if (tagname.equalsIgnoreCase("employee")) {
45. // add employee object to list
46. employees.add(employee);
47. }else if (tagname.equalsIgnoreCase("id")) {
48. employee.setId(Integer.parseInt(text));
49. } else if (tagname.equalsIgnoreCase("name")) {
50. employee.setName(text);
51. } else if (tagname.equalsIgnoreCase("salary")) {
52. employee.setSalary(Float.parseFloat(text));
53. }
54. break;
55.
56. default:
57. break;
58. }
59. eventType = parser.next();
60. }
61.
62. } catch (XmlPullParserException e) {e.printStackTrace();}
63. catch (IOException e) {e.printStackTrace();}
64.
65. return employees;
66. }
67. }

Email:[email protected]
200 | P a g e APS Microtech Pvt Ltd

MainActivity class

Now, write the code to display the list data in the ListView.

File: MainActivity.java

1. package com.example.xmlpullparsing;
2.
3. import java.io.IOException;
4. import java.io.InputStream;
5. import java.util.List;
6.
7. import android.os.Bundle;
8. import android.app.Activity;
9. import android.view.Menu;
10. import android.widget.ArrayAdapter;
11. import android.widget.ListView;
12.
13. public class MainActivity extends Activity {
14.
15. @Override
16. protected void onCreate(Bundle savedInstanceState) {
17. super.onCreate(savedInstanceState);
18. setContentView(R.layout.activity_main);
19.
20. ListView listView = (ListView) findViewById(R.id.listView1);
21.
22. List<Employee> employees = null;
23. try {
24. XmlPullParserHandler parser = new XmlPullParserHandler();
25. InputStream is=getAssets().open("employees.xml");
26. employees = parser.parse(is);
27.
28. ArrayAdapter<Employee> adapter =new ArrayAdapter<Employee>
29. (this,android.R.layout.simple_list_item_1, employees);
30. listView.setAdapter(adapter);
31.
32. } catch (IOException e) {e.printStackTrace();}
33.
34. }
35.
36. @Override
37. public boolean onCreateOptionsMenu(Menu menu) {
38. // Inflate the menu; this adds items to the action bar if it is present.
39. getMenuInflater().inflate(R.menu.activity_main, menu);

Email:[email protected]
201 | P a g e APS Microtech Pvt Ltd

40. return true;


41. }
42.
43. }

download this example

Output:

Email:[email protected]
202 | P a g e APS Microtech Pvt Ltd

Android JSON Parser Tutorial


JSON (Javascript Object Notation) is a programming language . It is minimal, textual, and
a subset of JavaScript. It is an alternative to XML.

Android provides support to parse the JSON object and array.

Advantage of JSON over XML

1) JSON is faster and easier than xml for AJAX applications.

2) Unlike XML, it is shorter and quicker to read and write.

3) It uses array.

json object

A JSON object contains key/value pairs like map. The keys are strings and the values are
the JSON types. Keys and values are separated by comma. The { (curly brace) represents
the json object.

1. {
2. "employee": {
3. "name": "sachin",
4. "salary": 56000,
5. "married": true
6. }
7. }

json array

The [ (square bracket) represents the json array.

1. ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]

Let's take another example of json array.

1. { "Employee" :
2. [
3. {"id":"101","name":"Sonoo Jaiswal","salary":"50000"},
4. {"id":"102","name":"Vimal Jaiswal","salary":"60000"}
5. ]
6. }

Email:[email protected]
203 | P a g e APS Microtech Pvt Ltd

Example of android JSON parsing

activity_main.xml

Drag the one textview from the pallete. Now the activity_main.xml file will look like this:

File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <TextView
8. android:id="@+id/textView1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentLeft="true"
12. android:layout_alignParentTop="true"
13. android:layout_marginLeft="75dp"
14. android:layout_marginTop="46dp"
15. android:text="TextView" />
16.
17. </RelativeLayout>

Activity class

Let's write the code to parse the xml using dom parser.

File: MainActivity.java

1. package com.javatpoint.jsonparsing;
2.
3. import org.json.JSONException;
4. import org.json.JSONObject;
5. import android.app.Activity;
6. import android.os.Bundle;
7. import android.widget.TextView;
8.
9. public class MainActivity extends Activity {
10. public static final String JSON_STRING="{\"employee\":{\"name\":\"Sachin\",\"salary\":5
6000}}";
11.
12. @Override

Email:[email protected]
204 | P a g e APS Microtech Pvt Ltd

13. public void onCreate(Bundle savedInstanceState) {


14. super.onCreate(savedInstanceState);
15. setContentView(R.layout.activity_main);
16.
17. TextView textView1=(TextView)findViewById(R.id.textView1);
18.
19. try{
20. JSONObject emp=(new JSONObject(JSON_STRING)).getJSONObject("employee");
21. String empname=emp.getString("name");
22. int empsalary=emp.getInt("salary");
23.
24. String str="Employee Name:"+empname+"\n"+"Employee Salary:"+empsalary;
25. textView1.setText(str);
26.
27. }catch (Exception e) {e.printStackTrace();}
28.
29. }
30.
31. }

download this example

Output:

Email:[email protected]
205 | P a g e APS Microtech Pvt Ltd

Parsing JSONArray in Android

By the help of JSONArray class, you can parse the JSONArray containing the JSON
Objects. Let's see the simple example to parse the json array.

File: MainActivity.java

1. package com.example.jsonparsing2;
2.
3. import org.json.JSONArray;
4. import org.json.JSONException;
5. import org.json.JSONObject;
6. import android.app.Activity;
7. import android.os.Bundle;
8. import android.widget.TextView;
9.
10. public class MainActivity extends Activity {
11. @Override
12. protected void onCreate(Bundle savedInstanceState) {
13. super.onCreate(savedInstanceState);
14. setContentView(R.layout.activity_main);
15.
16. TextView output = (TextView) findViewById(R.id.textView1);

Email:[email protected]
206 | P a g e APS Microtech Pvt Ltd

17.
18. String strJson="{ \"Employee\" :[{\"id\":\"101\",\"name\":\"Sonoo Jaiswal\",\"salary
\":\"50000\"},{\"id\":\"102\",\"name\":\"Vimal Jaiswal\",\"salary\":\"60000\"}] }";
19.
20. String data = "";
21. try {
22. // Create the root JSONObject from the JSON string.
23. JSONObject jsonRootObject = new JSONObject(strJson);
24.
25. //Get the instance of JSONArray that contains JSONObjects
26. JSONArray jsonArray = jsonRootObject.optJSONArray("Employee");
27.
28. //Iterate the jsonArray and print the info of JSONObjects
29. for(int i=0; i < jsonArray.length(); i++){
30. JSONObject jsonObject = jsonArray.getJSONObject(i);
31.
32. int id = Integer.parseInt(jsonObject.optString("id").toString());
33. String name = jsonObject.optString("name").toString();
34. float salary = Float.parseFloat(jsonObject.optString("salary").toString());
35.
36. data += "Node"+i+" : \n id= "+ id +" \n Name= "+ name +" \n Salary= "+ salar
y +" \n ";
37. }
38. output.setText(data);
39. } catch (JSONException e) {e.printStackTrace();}
40. }
41. }

download this example

Output:

Email:[email protected]
207 | P a g e APS Microtech Pvt Ltd

Email:[email protected]
208 | P a g e APS Microtech Pvt Ltd

Android Media Player Example


We can play and control the audio files in android by the help of MediaPlayer class.

Here, we are going to see a simple example to play the audio file. In the next page, we will
see the example to control the audio playback like start, stop, pause etc.

MediaPlayer class
The android.media.MediaPlayer class is used to control the audio or video files.

Methods of MediaPlayer class

There are many methods of MediaPlayer class. Some of them are as follows:

Method Description

sets the data source (file path or http url) to


public void setDataSource(String path)
use.

prepares the player for playback


public void prepare()
synchronously.

public void start() it starts or resumes the playback.

public void stop() it stops the playback.

public void pause() it pauses the playback.

public boolean isPlaying() checks if media player is playing.

public void seekTo(int millis) seeks to specified time in miliseconds.

public void setLooping(boolean looping) sets the player for looping or non-looping.

public boolean isLooping() checks if the player is looping or non-looping.

public void selectTrack(int index) it selects a track for the specified index.

public int getCurrentPosition() returns the current playback position.

public int getDuration() returns duration of the file.

Email:[email protected]
209 | P a g e APS Microtech Pvt Ltd

public void setVolume(float leftVolume,float


sets the volume on this player.
rightVolume)

Activity class

Let's write the code of to play the audio file. Here, we are going to play maine.mp3 file
located inside the sdcard/Music directory.

File: MainActivity.java

1. package com.example.audiomediaplayer1;
2.
3. import android.media.MediaPlayer;
4. import android.net.Uri;
5. import android.os.Bundle;
6. import android.app.Activity;
7. import android.view.Menu;
8. import android.widget.MediaController;
9. import android.widget.VideoView;
10.
11. public class MainActivity extends Activity {
12.
13. @Override
14. protected void onCreate(Bundle savedInstanceState) {
15. super.onCreate(savedInstanceState);
16. setContentView(R.layout.activity_main);
17.
18. MediaPlayer mp=new MediaPlayer();
19. try{
20. mp.setDataSource("/sdcard/Music/maine.mp3");//Write your location here
21. mp.prepare();
22. mp.start();
23.
24. }catch(Exception e){e.printStackTrace();}
25.
26. }
27.
28. @Override
29. public boolean onCreateOptionsMenu(Menu menu) {
30. // Inflate the menu; this adds items to the action bar if it is present.
31. getMenuInflater().inflate(R.menu.activity_main, menu);
32. return true;
33. }
34.
35. }

Email:[email protected]
210 | P a g e APS Microtech Pvt Ltd

download this android example

You need to run it on the real device to test the application.

Android MediaPlayer Example of controlling the audio

Let's see a simple example to start, stop and pause the audio play.

activity_main.xml

Drag three buttons from pallete to start, stop and pause the audio play. Now the xml file
will look like this:

File: MainActivity.java

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".MainActivity" >
10.
11. <TextView
12. android:id="@+id/textView1"
13. android:layout_width="wrap_content"
14. android:layout_height="wrap_content"
15. android:layout_alignParentTop="true"
16. android:layout_marginTop="30dp"
17. android:text="Audio Controller" />
18.
19. <Button
20. android:id="@+id/button1"
21. style="?android:attr/buttonStyleSmall"
22. android:layout_width="wrap_content"
23. android:layout_height="wrap_content"
24. android:layout_alignLeft="@+id/textView1"
25. android:layout_below="@+id/textView1"
26. android:layout_marginTop="48dp"
27. android:text="start" />
28.
29. <Button
30. android:id="@+id/button2"

Email:[email protected]
211 | P a g e APS Microtech Pvt Ltd

31. style="?android:attr/buttonStyleSmall"
32. android:layout_width="wrap_content"
33. android:layout_height="wrap_content"
34. android:layout_alignTop="@+id/button1"
35. android:layout_toRightOf="@+id/button1"
36. android:text="pause" />
37.
38. <Button
39. android:id="@+id/button3"
40. style="?android:attr/buttonStyleSmall"
41. android:layout_width="wrap_content"
42. android:layout_height="wrap_content"
43. android:layout_alignTop="@+id/button2"
44. android:layout_toRightOf="@+id/button2"
45. android:text="stop" />
46.
47. </RelativeLayout>

Activity class

Let's write the code to start, pause and stop the audio player.

File: MainActivity.java

1. package com.example.audioplay;
2.
3. import android.media.MediaPlayer;
4. import android.os.Bundle;
5. import android.os.Environment;
6. import android.app.Activity;
7. import android.view.Menu;
8. import android.view.View;
9. import android.view.View.OnClickListener;
10. import android.widget.Button;
11.
12. public class MainActivity extends Activity {
13. Button start,pause,stop;
14. @Override
15. protected void onCreate(Bundle savedInstanceState) {
16. super.onCreate(savedInstanceState);
17. setContentView(R.layout.activity_main);
18.
19. start=(Button)findViewById(R.id.button1);
20. pause=(Button)findViewById(R.id.button2);
21. stop=(Button)findViewById(R.id.button3);
22. //creating media player
23. final MediaPlayer mp=new MediaPlayer();

Email:[email protected]
212 | P a g e APS Microtech Pvt Ltd

24. try{
25. //you can change the path, here path is external directory(e.g. sdcard) /Music/m
aine.mp3
26. mp.setDataSource(Environment.getExternalStorageDirectory().getPath()+"/Music/m
aine.mp3");
27.
28. mp.prepare();
29. }catch(Exception e){e.printStackTrace();}
30.
31. start.setOnClickListener(new OnClickListener() {
32. @Override
33. public void onClick(View v) {
34. mp.start();
35. }
36. });
37. pause.setOnClickListener(new OnClickListener() {
38. @Override
39. public void onClick(View v) {
40. mp.pause();
41. }
42. });
43. stop.setOnClickListener(new OnClickListener() {
44. @Override
45. public void onClick(View v) {
46. mp.stop();
47. }
48. });
49. }
50. }

download this android example

Output:

Email:[email protected]
213 | P a g e APS Microtech Pvt Ltd

Email:[email protected]
214 | P a g e APS Microtech Pvt Ltd

Android Video Player Example


By the help of MediaController and VideoView classes, we can play the video files in
android.

MediaController class

The android.widget.MediaController is a view that contains media controls like


play/pause, previous, next, fast-forward, rewind etc.

VideoView class

The android.widget.VideoView class provides methods to play and control the video
player. The commonly used methods of VideoView class are as follows:

Method Description

public void setMediaController(MediaController sets the media controller to the video


controller) view.

public void setVideoURI (Uri uri) sets the URI of the video file.

public void start() starts the video view.

public void stopPlayback() stops the playback.

public void pause() pauses the playback.

public void suspend() suspends the playback.

public void resume() resumes the playback.

public void seekTo(int millis) seeks to specified time in miliseconds.

activity_main.xml

Drag the VideoView from the pallete, now the activity_main.xml file will like this:

File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"

Email:[email protected]
215 | P a g e APS Microtech Pvt Ltd

4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <VideoView
8. android:id="@+id/videoView1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentLeft="true"
12. android:layout_centerVertical="true" />
13.
14. </RelativeLayout>

Activity class

Let's write the code of to play the video file. Here, we are going to play 1.mp4 file located
inside the sdcard/media directory.

File: MainActivity.java

1. package com.example.video1;
2.
3. import android.net.Uri;
4. import android.os.Bundle;
5. import android.app.Activity;
6. import android.view.Menu;
7. import android.widget.MediaController;
8. import android.widget.VideoView;
9.
10. public class MainActivity extends Activity {
11.
12. @Override
13. protected void onCreate(Bundle savedInstanceState) {
14. super.onCreate(savedInstanceState);
15. setContentView(R.layout.activity_main);
16.
17. VideoView videoView =(VideoView)findViewById(R.id.videoView1);
18.
19. //Creating MediaController
20. MediaController mediaController= new MediaController(this);
21. mediaController.setAnchorView(videoView);
22.
23. //specify the location of media file
24. Uri uri=Uri.parse(Environment.getExternalStorageDirectory().getPath()+"/media/1.
mp4");
25.

Email:[email protected]
216 | P a g e APS Microtech Pvt Ltd

26. //Setting MediaController and URI, then starting the videoView


27. videoView.setMediaController(mediaController);
28. videoView.setVideoURI(uri);
29. videoView.requestFocus();
30. videoView.start();
31.
32. }
33.
34. @Override
35. public boolean onCreateOptionsMenu(Menu menu) {
36. // Inflate the menu; this adds items to the action bar if it is present.
37. getMenuInflater().inflate(R.menu.activity_main, menu);
38. return true;
39. }
40.
41. }

You need to run it on the real device (e.g. mobile) to test the application.

Email:[email protected]
217 | P a g e APS Microtech Pvt Ltd

Android MediaRecorder Example


MediaRecorder class can be used to record audio and video files.

After recording the media, we can create a sound file that can be played later.

In this example, we are going to record the audio file and storing it in the external
directory in 3gp format.

activity_main.xml

Drag 2 buttons from the pallete, one to start the recording and another stop the recording.
Here, we are registering the view with the listener in xml file using android:onClick.

File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".MainActivity" >
10.
11. <Button
12. android:id="@+id/button1"
13. android:layout_width="wrap_content"
14. android:layout_height="wrap_content"
15. android:layout_alignParentLeft="true"
16. android:layout_alignParentTop="true"
17. android:layout_marginLeft="68dp"
18. android:layout_marginTop="50dp"
19. android:text="Start Recording"
20. android:onClick="startRecording"
21. />
22.
23. <Button
24. android:id="@+id/button2"
25. android:layout_width="wrap_content"
26. android:layout_height="wrap_content"
27. android:layout_alignLeft="@+id/button1"
28. android:layout_below="@+id/button1"
29. android:layout_marginTop="64dp"
30. android:text="Stop Recording"

Email:[email protected]
218 | P a g e APS Microtech Pvt Ltd

31. android:onClick="stopRecording"
32. />
33.
34. </RelativeLayout>

Activity class
File: MainActivity.java

1. package com.javatpoint.mediarecorder;
2. import java.io.File;
3. import java.io.IOException;
4. import android.app.Activity;
5. import android.content.ContentResolver;
6. import android.content.ContentValues;
7. import android.content.Intent;
8. import android.media.MediaRecorder;
9. import android.net.Uri;
10. import android.os.Bundle;
11. import android.os.Environment;
12. import android.provider.MediaStore;
13. import android.util.Log;
14. import android.view.View;
15. import android.widget.Button;
16. import android.widget.Toast;
17.
18. public class MainActivity extends Activity {
19. MediaRecorder recorder;
20. File audiofile = null;
21. static final String TAG = "MediaRecording";
22. Button startButton,stopButton;
23.
24. @Override
25. public void onCreate(Bundle savedInstanceState) {
26. super.onCreate(savedInstanceState);
27. setContentView(R.layout.activity_main);
28. startButton = (Button) findViewById(R.id.button1);
29. stopButton = (Button) findViewById(R.id.button2);
30. }
31.
32. public void startRecording(View view) throws IOException {
33. startButton.setEnabled(false);
34. stopButton.setEnabled(true);
35. //Creating file
36. File dir = Environment.getExternalStorageDirectory();
37. try {

Email:[email protected]
219 | P a g e APS Microtech Pvt Ltd

38. audiofile = File.createTempFile("sound", ".3gp", dir);


39. } catch (IOException e) {
40. Log.e(TAG, "external storage access error");
41. return;
42. }
43. //Creating MediaRecorder and specifying audio source, output format, encoder &
output format
44. recorder = new MediaRecorder();
45. recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
46. recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
47. recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
48. recorder.setOutputFile(audiofile.getAbsolutePath());
49. recorder.prepare();
50. recorder.start();
51. }
52.
53. public void stopRecording(View view) {
54. startButton.setEnabled(true);
55. stopButton.setEnabled(false);
56. //stopping recorder
57. recorder.stop();
58. recorder.release();
59. //after stopping the recorder, create the sound file and add it to media library.
60. addRecordingToMediaLibrary();
61. }
62.
63. protected void addRecordingToMediaLibrary() {
64. //creating content values of size 4
65. ContentValues values = new ContentValues(4);
66. long current = System.currentTimeMillis();
67. values.put(MediaStore.Audio.Media.TITLE, "audio" + audiofile.getName());
68. values.put(MediaStore.Audio.Media.DATE_ADDED, (int) (current / 1000));
69. values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/3gpp");
70. values.put(MediaStore.Audio.Media.DATA, audiofile.getAbsolutePath());
71.
72. //creating content resolver and storing it in the external content uri
73. ContentResolver contentResolver = getContentResolver();
74. Uri base = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
75. Uri newUri = contentResolver.insert(base, values);
76.
77. //sending broadcast message to scan the media file so that it can be available
78. sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, newUri));
79. Toast.makeText(this, "Added File " + newUri, Toast.LENGTH_LONG).show();
80. }
81. }

Email:[email protected]
220 | P a g e APS Microtech Pvt Ltd

download this mediarecorder Example

Output:

Email:[email protected]
221 | P a g e APS Microtech Pvt Ltd

Android TextToSpeech Tutorial


In android, you can convert your text into speech by the help of TextToSpeech class.
After completion of the conversion, you can playback or create the sound file.

Constructor of TextToSpeech class

 TextToSpeech(Context context, TextToSpeech.OnInitListener)

Methods of TextToSpeech class

The commonly used methods of TextToSpeech class are as follows:

Method Description

converts the text into speech. Queue Mode may be QUEUE_ADD or


int speak (String text, int
QUEUE_FLUSH. Request parameters can be null,
queueMode, HashMap params)
KEY_PARAM_STREAM, KEY_PARAM_VALUME etc.

int setSpeechRate(float speed) it sets the speed for the speech.

int setPitch(float speed) it sets the pitch for the speech.

int setLanguage (Locale loc) it sets the locale specific language for the speech.

void shutdown() it releases the resource set by TextToSpeech Engine.

it interrupts the current utterance (whether played or rendered to


int stop()
file) and discards other utterances in the queue.

TextToSpeech.OnInitListener Interface
You need to implement TextToSpeech.OnInitListener interface, for performing event
handling on TextToSpeech engine.

Method of TextToSpeech.OnInitListener Interface

There is only one method in this interface.

Method Description

Email:[email protected]
222 | P a g e APS Microtech Pvt Ltd

void onInit (int Called to signal the completion of the TextToSpeech engine initialization. The status
status) can be SUCCESS or ERROR.

Android TextToSpeech Example

Let's write the code to convert text into voice.

activity_main.xml

Drag one textview, one edittext and one button for the layout. Now the activity_main.xml
file will look like this:

File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <EditText
8. android:id="@+id/editText1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentLeft="true"
12. android:layout_alignParentTop="true"
13. android:layout_marginLeft="77dp"
14. android:layout_marginTop="42dp"
15. android:ems="10" >
16.
17. <requestFocus />
18. </EditText>
19.
20. <Button
21. android:id="@+id/button1"
22. android:layout_width="wrap_content"
23. android:layout_height="wrap_content"
24. android:layout_alignLeft="@+id/editText1"
25. android:layout_below="@+id/editText1"
26. android:layout_marginLeft="59dp"
27. android:layout_marginTop="39dp"
28. android:text="Speak" />
29.
30. <TextView
31. android:id="@+id/textView1"

Email:[email protected]
223 | P a g e APS Microtech Pvt Ltd

32. android:layout_width="wrap_content"
33. android:layout_height="wrap_content"
34. android:layout_alignBaseline="@+id/editText1"
35. android:layout_alignBottom="@+id/editText1"
36. android:layout_alignParentLeft="true"
37. android:text="Enter Text:" />
38.
39. </RelativeLayout>

Activity class

Let's see the code to speak the given text.

File: MainActivity.java

1. package com.example.texttospeech;
2.
3. import android.os.Bundle;
4. import android.app.Activity;
5. import android.view.Menu;
6. import java.util.Locale;
7.
8. import android.app.Activity;
9. import android.os.Bundle;
10. import android.speech.tts.TextToSpeech;
11. import android.util.Log;
12. import android.view.View;
13. import android.widget.Button;
14. import android.widget.EditText;
15. public class MainActivity extends Activity implements
16. TextToSpeech.OnInitListener {
17. /** Called when the activity is first created. */
18.
19. private TextToSpeech tts;
20. private Button buttonSpeak;
21. private EditText editText;
22.
23. @Override
24. public void onCreate(Bundle savedInstanceState) {
25. super.onCreate(savedInstanceState);
26. setContentView(R.layout.activity_main);
27.
28. tts = new TextToSpeech(this, this);
29. buttonSpeak = (Button) findViewById(R.id.button1);
30. editText = (EditText) findViewById(R.id.editText1);

Email:[email protected]
224 | P a g e APS Microtech Pvt Ltd

31.
32. buttonSpeak.setOnClickListener(new View.OnClickListener() {
33. @Override
34. public void onClick(View arg0) {
35. speakOut();
36. }
37.
38. });
39. }
40.
41. @Override
42. public void onDestroy() {
43. // Don't forget to shutdown tts!
44. if (tts != null) {
45. tts.stop();
46. tts.shutdown();
47. }
48. super.onDestroy();
49. }
50.
51. @Override
52. public void onInit(int status) {
53.
54. if (status == TextToSpeech.SUCCESS) {
55.
56. int result = tts.setLanguage(Locale.US);
57.
58. if (result == TextToSpeech.LANG_MISSING_DATA
59. || result == TextToSpeech.LANG_NOT_SUPPORTED) {
60. Log.e("TTS", "This Language is not supported");
61. } else {
62. buttonSpeak.setEnabled(true);
63. speakOut();
64. }
65.
66. } else {
67. Log.e("TTS", "Initilization Failed!");
68. }
69.
70. }
71.
72. private void speakOut() {
73. String text = editText.getText().toString();
74. tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
75. }
76.
77. @Override

Email:[email protected]
225 | P a g e APS Microtech Pvt Ltd

78. public boolean onCreateOptionsMenu(Menu menu) {


79. // Inflate the menu; this adds items to the action bar if it is present.
80. getMenuInflater().inflate(R.menu.activity_main, menu);
81. return true;
82. }
83.
84. }

You need to run it on the Real Device (e.g. Mobile) to test the application.

Next: TextToSpeech example with speed and pitch option

Android TextToSpeech Example

Email:[email protected]
226 | P a g e APS Microtech Pvt Ltd

TextToSpeech class is responsible to convert text into speech. It provides a lot of methods
to control the speech such as setSpeedRate(), setPitch() etc.

In this example, we are going to see the android texttospeech example with speed and
pitch option.

activity_main.xml

Drag 2 textviews, 1 edittext, 1 spinner and 1 button for the layout. Now the
activity_main.xml file will look like this:

File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <EditText
8. android:id="@+id/editText1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignBaseline="@+id/textView1"
12. android:layout_alignBottom="@+id/textView1"
13. android:layout_alignParentRight="true"
14. android:layout_marginRight="58dp"
15. android:ems="10" >
16.
17. <requestFocus />
18. </EditText>
19.
20. <Button
21. android:id="@+id/button1"
22. android:layout_width="wrap_content"
23. android:layout_height="wrap_content"
24. android:layout_below="@+id/editText1"
25. android:layout_centerHorizontal="true"
26. android:layout_marginTop="28dp"
27. android:text="Speak" />
28.
29. <TextView
30. android:id="@+id/textView2"
31. android:layout_width="wrap_content"
32. android:layout_height="wrap_content"
33. android:layout_below="@+id/button1"
34. android:layout_marginTop="62dp"

Email:[email protected]
227 | P a g e APS Microtech Pvt Ltd

35. android:layout_toLeftOf="@+id/editText1"
36. android:text="Speed:" />
37.
38. <TextView
39. android:id="@+id/textView1"
40. android:layout_width="wrap_content"
41. android:layout_height="wrap_content"
42. android:layout_alignLeft="@+id/textView2"
43. android:layout_alignParentTop="true"
44. android:layout_marginTop="42dp"
45. android:text="Text:" />
46.
47. <Spinner
48. android:id="@+id/spinner1"
49. android:layout_width="200dp"
50. android:layout_height="wrap_content"
51. android:layout_below="@+id/button1"
52. android:layout_centerHorizontal="true"
53. android:layout_marginTop="43dp" />
54.
55. </RelativeLayout>

Activity class

Let's see the code to speak the given text.

File: MainActivity.java

1. package com.example.texttospeechspeed;
2.
3. import android.os.Bundle;
4. import android.app.Activity;
5. import android.view.Menu;
6.
7. import java.util.ArrayList;
8. import java.util.List;
9. import java.util.Locale;
10. import android.speech.tts.TextToSpeech;
11. import android.util.Log;
12. import android.view.View;
13. import android.widget.AdapterView;
14. import android.widget.AdapterView.OnItemSelectedListener;
15. import android.widget.ArrayAdapter;
16. import android.widget.Button;
17. import android.widget.EditText;

Email:[email protected]
228 | P a g e APS Microtech Pvt Ltd

18. import android.widget.Spinner;


19. import android.widget.Toast;
20. public class MainActivity extends Activity implements
21. TextToSpeech.OnInitListener,OnItemSelectedListener {
22. /** Called when the activity is first created. */
23.
24. private TextToSpeech tts;
25. private Button buttonSpeak;
26. private EditText editText;
27. private Spinner speedSpinner,pitchSpinner;
28.
29. private static String speed="Normal";
30. @Override
31. public void onCreate(Bundle savedInstanceState) {
32. super.onCreate(savedInstanceState);
33. setContentView(R.layout.activity_main);
34.
35. tts = new TextToSpeech(this, this);
36. buttonSpeak = (Button) findViewById(R.id.button1);
37. editText = (EditText) findViewById(R.id.editText1);
38. speedSpinner = (Spinner) findViewById(R.id.spinner1);
39.
40. //load data in spinner
41. loadSpinnerData();
42. speedSpinner.setOnItemSelectedListener(this);
43.
44. //button click event
45. buttonSpeak.setOnClickListener(new View.OnClickListener() {
46. @Override
47. public void onClick(View arg0) {
48. setSpeed();
49. speakOut();
50. }
51.
52. });
53. }
54.
55.
56. @Override
57. public void onInit(int status) {
58.
59. if (status == TextToSpeech.SUCCESS) {
60.
61. int result = tts.setLanguage(Locale.US);
62.
63. if (result == TextToSpeech.LANG_MISSING_DATA
64. || result == TextToSpeech.LANG_NOT_SUPPORTED) {

Email:[email protected]
229 | P a g e APS Microtech Pvt Ltd

65. Log.e("TTS", "This Language is not supported");


66. } else {
67. buttonSpeak.setEnabled(true);
68. speakOut();
69. }
70.
71. } else { Log.e("TTS", "Initilization Failed!");}
72.
73. }
74.
75. @Override
76. public void onDestroy() {
77. // Don't forget to shutdown tts!
78. if (tts != null) {
79. tts.stop();
80. tts.shutdown();
81. }
82. super.onDestroy();
83. }
84.
85. private void setSpeed(){
86. if(speed.equals("Very Slow")){
87. tts.setSpeechRate(0.1f);
88. }
89. if(speed.equals("Slow")){
90. tts.setSpeechRate(0.5f);
91. }
92. if(speed.equals("Normal")){
93. tts.setSpeechRate(1.0f);//default 1.0
94. }
95. if(speed.equals("Fast")){
96. tts.setSpeechRate(1.5f);
97. }
98. if(speed.equals("Very Fast")){
99. tts.setSpeechRate(2.0f);
100. }
101. //for setting pitch you may call
102. //tts.setPitch(1.0f);//default 1.0
103. }
104.
105. private void speakOut() {
106. String text = editText.getText().toString();
107. tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
108. }
109.
110. private void loadSpinnerData() {
111. //Data for speed Spinner

Email:[email protected]
230 | P a g e APS Microtech Pvt Ltd

112. List<String> lables = new ArrayList<String>();


113. lables.add("Very Slow");
114. lables.add("Slow");
115. lables.add("Normal");
116. lables.add("Fast");
117. lables.add("Very Fast");
118.
119. // Creating adapter for spinner
120. ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.
layout.simple_spinner_item, lables);
121.
122. // Drop down layout style - list view with radio button
123. dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dro
pdown_item);
124.
125. // attaching data adapter to spinner
126. speedSpinner.setAdapter(dataAdapter);
127.
128. }
129.
130. @Override
131. public void onItemSelected(AdapterView<?> parent, View view, int position,
132. long id) {
133. // On selecting a spinner item
134. speed = parent.getItemAtPosition(position).toString();
135.
136. Toast.makeText(parent.getContext(), "You selected: " + speed,
137. Toast.LENGTH_LONG).show();
138. }
139.
140. @Override
141. public void onNothingSelected(AdapterView<?> arg0) {
142.
143. }
144.
145.
146. @Override
147. public boolean onCreateOptionsMenu(Menu menu) {
148. // Inflate the menu; this adds items to the action bar if it is present.
149. getMenuInflater().inflate(R.menu.activity_main, menu);
150. return true;
151. }
152.
153. }

Email:[email protected]
231 | P a g e APS Microtech Pvt Ltd

You need to run it on the Real Device (e.g. Mobile) to test the application.

Android TelephonyManager Tutorial


The android.telephony.TelephonyManager class provides information about the
telephony services such as subscriber id, sim serial number, phone network type etc.

Email:[email protected]
232 | P a g e APS Microtech Pvt Ltd

Moreover, you can determine the phone state etc.

Android TelephonyManager Example

Let's see the simple example of TelephonyManager that prints information of the
telephony services.

activity_main.xml

Drag one textview from the pallete, now the xml file will look like this.

File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".MainActivity" >
10.
11. <TextView
12. android:id="@+id/textView1"
13. android:layout_width="wrap_content"
14. android:layout_height="wrap_content"
15. android:layout_alignParentLeft="true"
16. android:layout_alignParentTop="true"
17. android:layout_marginLeft="38dp"
18. android:layout_marginTop="30dp"
19. android:text="Phone Details:" />
20.
21. </RelativeLayout>

Activity class

Now, write the code to display the information about the telephony services.

File: MainActivity.java

1. package com.javatpoint.telephonymanager;
2.
3. import android.os.Bundle;

Email:[email protected]
233 | P a g e APS Microtech Pvt Ltd

4. import android.app.Activity;
5. import android.content.Context;
6. import android.telephony.TelephonyManager;
7. import android.view.Menu;
8. import android.widget.TextView;
9.
10. public class MainActivity extends Activity {
11. TextView textView1;
12. @Override
13. protected void onCreate(Bundle savedInstanceState) {
14. super.onCreate(savedInstanceState);
15. setContentView(R.layout.activity_main);
16.
17. textView1=(TextView)findViewById(R.id.textView1);
18.
19. //Get the instance of TelephonyManager
20. TelephonyManager tm=(TelephonyManager)getSystemService(Context.TELEPHONY
_SERVICE);
21.
22. //Calling the methods of TelephonyManager the returns the information
23. String IMEINumber=tm.getDeviceId();
24. String subscriberID=tm.getDeviceId();
25. String SIMSerialNumber=tm.getSimSerialNumber();
26. String networkCountryISO=tm.getNetworkCountryIso();
27. String SIMCountryISO=tm.getSimCountryIso();
28. String softwareVersion=tm.getDeviceSoftwareVersion();
29. String voiceMailNumber=tm.getVoiceMailNumber();
30.
31. //Get the phone type
32. String strphoneType="";
33.
34. int phoneType=tm.getPhoneType();
35.
36. switch (phoneType)
37. {
38. case (TelephonyManager.PHONE_TYPE_CDMA):
39. strphoneType="CDMA";
40. break;
41. case (TelephonyManager.PHONE_TYPE_GSM):
42. strphoneType="GSM";
43. break;
44. case (TelephonyManager.PHONE_TYPE_NONE):
45. strphoneType="NONE";
46. break;
47. }
48.
49. //getting information if phone is in roaming

Email:[email protected]
234 | P a g e APS Microtech Pvt Ltd

50. boolean isRoaming=tm.isNetworkRoaming();


51.
52. String info="Phone Details:\n";
53. info+="\n IMEI Number:"+IMEINumber;
54. info+="\n SubscriberID:"+subscriberID;
55. info+="\n Sim Serial Number:"+SIMSerialNumber;
56. info+="\n Network Country ISO:"+networkCountryISO;
57. info+="\n SIM Country ISO:"+SIMCountryISO;
58. info+="\n Software Version:"+softwareVersion;
59. info+="\n Voice Mail Number:"+voiceMailNumber;
60. info+="\n Phone Network Type:"+strphoneType;
61. info+="\n In Roaming? :"+isRoaming;
62.
63. textView1.setText(info);//displaying the information in the textView
64. }
65.
66.
67. }

AndroidManifest.xml

You need to provide READ_PHONE_STATE permission in the AndroidManifest.xml


file.

File: AndroidManifest.xml

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


2. <manifest xmlns:androclass="http://schemas.android.com/apk/res/android"
3. package="com.javatpoint.telephonymanager"
4. android:versionCode="1"
5. android:versionName="1.0" >
6.
7. <uses-sdk
8. android:minSdkVersion="8"
9. android:targetSdkVersion="17" />
10.
11. <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
12.
13. <application
14. android:allowBackup="true"
15. android:icon="@drawable/ic_launcher"
16. android:label="@string/app_name"
17. android:theme="@style/AppTheme" >
18. <activity
19. android:name="com.javatpoint.telephonymanager.MainActivity"

Email:[email protected]
235 | P a g e APS Microtech Pvt Ltd

20. android:label="@string/app_name" >


21. <intent-filter>
22. <action android:name="android.intent.action.MAIN" />
23.
24. <category android:name="android.intent.category.LAUNCHER" />
25. </intent-filter>
26. </activity>
27. </application>
28.
29. </manifest>

download this android example

Output:

Android Call State Example


We can also get the information of call state using the TelephonyManager class. For this
purpose, we need to call the listen method of TelephonyManager class by passing the

Email:[email protected]
236 | P a g e APS Microtech Pvt Ltd

PhonStateListener instance.

The PhoneStateListener interface must be implemented to get the call state. It provides
one method onCallStateChanged().

Android Call State Example

Let's see the example, where we are determining whether phone is ringing or phone is in a
call or phone is neither ringing nor in a call.

activity_main.xml

In this example, we don't have any component in this file..

Activity class

Let's write the code to know the call state.

File: MainActivity.java

1. package com.javatpoint.callstates;
2.
3. import android.os.Bundle;
4. import android.app.Activity;
5. import android.content.Context;
6. import android.telephony.PhoneStateListener;
7. import android.telephony.TelephonyManager;
8. import android.view.Menu;
9. import android.widget.Toast;
10.
11. public class MainActivity extends Activity {
12.
13. @Override
14. protected void onCreate(Bundle savedInstanceState) {
15. super.onCreate(savedInstanceState);
16. setContentView(R.layout.activity_main);
17.
18. TelephonyManager telephonyManager =
19. (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
20.
21. PhoneStateListener callStateListener = new PhoneStateListener() {
22. public void onCallStateChanged(int state, String incomingNumber)
23. {
24. if(state==TelephonyManager.CALL_STATE_RINGING){

Email:[email protected]
237 | P a g e APS Microtech Pvt Ltd

25. Toast.makeText(getApplicationContext(),"Phone Is Riging",


26. Toast.LENGTH_LONG).show();
27. }
28. if(state==TelephonyManager.CALL_STATE_OFFHOOK){
29. Toast.makeText(getApplicationContext(),"Phone is Currently in A call",
30. Toast.LENGTH_LONG).show();
31. }
32.
33. if(state==TelephonyManager.CALL_STATE_IDLE){
34. Toast.makeText(getApplicationContext(),"phone is neither ringing nor in a call
",
35. Toast.LENGTH_LONG).show();
36. }
37. }
38. };
39. telephonyManager.listen(callStateListener,PhoneStateListener.LISTEN_CALL_STATE);

40.
41. }
42.
43. @Override
44. public boolean onCreateOptionsMenu(Menu menu) {
45. // Inflate the menu; this adds items to the action bar if it is present.
46. getMenuInflater().inflate(R.menu.main, menu);
47. return true;
48. }
49.
50. }

AndroidManifest.xml

You need to provide READ_PHONE_STATE permission in the AndroidManifest.xml


file.

File: AndroidManifest.xml

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


2. <manifest xmlns:androclass="http://schemas.android.com/apk/res/android"
3. package="com.javatpoint.callstates"
4. android:versionCode="1"
5. android:versionName="1.0" >
6.
7. <uses-sdk
8. android:minSdkVersion="8"
9. android:targetSdkVersion="17" />

Email:[email protected]
238 | P a g e APS Microtech Pvt Ltd

10.
11.
12. <uses-permission android:name="android.permission.READ_PHONE_STATE" />
13.
14. <application
15. android:allowBackup="true"
16. android:icon="@drawable/ic_launcher"
17. android:label="@string/app_name"
18. android:theme="@style/AppTheme" >
19. <activity
20. android:name="com.javatpoint.callstates.MainActivity"
21. android:label="@string/app_name" >
22. <intent-filter>
23. <action android:name="android.intent.action.MAIN" />
24.
25. <category android:name="android.intent.category.LAUNCHER" />
26. </intent-filter>
27. </activity>
28. </application>
29.
30. </manifest>

download this android example

Output:

Email:[email protected]
239 | P a g e APS Microtech Pvt Ltd

Email:[email protected]
240 | P a g e APS Microtech Pvt Ltd

Android Call State BroadCastReceiver


Example
Android Call State BroadCastReceiver Example

activity_main.xml
File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".MainActivity" >
10.
11. <TextView
12. android:layout_width="wrap_content"
13. android:layout_height="wrap_content"
14. android:text="@string/hello_world" />
15.
16. </RelativeLayout>

Activity class
File: MainActivity.java

1. package com.example.callstatebroadcastreceiver;
2.
3. import android.os.Bundle;
4. import android.app.Activity;
5. import android.view.Menu;
6.
7. public class MainActivity extends Activity {
8.
9. @Override
10. protected void onCreate(Bundle savedInstanceState) {
11. super.onCreate(savedInstanceState);
12. setContentView(R.layout.activity_main);
13. }
14.
15.

Email:[email protected]
241 | P a g e APS Microtech Pvt Ltd

16. @Override
17. public boolean onCreateOptionsMenu(Menu menu) {
18. // Inflate the menu; this adds items to the action bar if it is present.
19. getMenuInflater().inflate(R.menu.main, menu);
20. return true;
21. }
22.
23. }

IncommingCallReceiver
File: IncommingCallReceiver.java

1. package com.example.callstatebroadcastreceiver;
2.
3. import android.content.BroadcastReceiver;
4. import android.content.Context;
5. import android.content.Intent;
6. import android.telephony.TelephonyManager;
7. import android.widget.Toast;
8.
9.
10. public class IncommingCallReceiver extends BroadcastReceiver{
11. Context context;
12.
13. @Override
14. public void onReceive(Context context, Intent intent){
15. try{
16. String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
17.
18. if(state.equals(TelephonyManager.EXTRA_STATE_RINGING)){
19. Toast.makeText(context, "Phone Is Ringing", Toast.LENGTH_LONG).show();
20. }
21.
22. if(state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
23. Toast.makeText(context, "Call Recieved", Toast.LENGTH_LONG).show();
24. }
25.
26. if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)){
27. Toast.makeText(context, "Phone Is Idle", Toast.LENGTH_LONG).show();
28. }
29. }
30. catch(Exception e){e.printStackTrace();}
31. }
32.
33. }

Email:[email protected]
242 | P a g e APS Microtech Pvt Ltd

Android Simple Caller Talker Example


Email:[email protected]
243 | P a g e APS Microtech Pvt Ltd

Android provides the facility to know the incoming number and speak it by the help of
android speech api and telephony manager.

Here, we are going to develop a basic android app that speaks the incoming number while
phone is in ringing mode.

In the next page, we will see the full version of this app that speaks the caller name and
provides the setting option to change the speed rate and pitch. Additionaly, it provides
option to add text before and after the incoming number or caller name.

activity_main.xml

We have not done anything special here. It has the simple textview.

File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".MainActivity" >
10.
11. <TextView
12. android:layout_width="wrap_content"
13. android:layout_height="wrap_content"
14. android:text="@string/hello_world" />
15.
16. </RelativeLayout>

Activity class

In this activity, we have written the code to know the phone state, and speak the incoming
number by the help of TextToSpeech class.

File: MainActivity.java

1. package com.example.callertalker;
2. import java.util.Locale;
3. import android.media.AudioManager;
4. import android.os.Bundle;

Email:[email protected]
244 | P a g e APS Microtech Pvt Ltd

5. import android.app.Activity;
6. import android.content.Context;
7. import android.telephony.PhoneStateListener;
8. import android.telephony.TelephonyManager;
9. import android.util.Log;
10. import android.widget.Toast;
11. import android.speech.tts.TextToSpeech;
12.
13. public class MainActivity extends Activity implements TextToSpeech.OnInitListener {
14. private TextToSpeech tts;
15. @Override
16. protected void onCreate(Bundle savedInstanceState) {
17. super.onCreate(savedInstanceState);
18. setContentView(R.layout.activity_main);
19.
20. tts = new TextToSpeech(this, this);
21.
22. TelephonyManager telephonyManager = (TelephonyManager)getSystemService(
23. Context.TELEPHONY_SERVICE);
24.
25. PhoneStateListener callStateListener = new PhoneStateListener() {
26. public void onCallStateChanged(int state, String incomingNumber){
27. if(state==TelephonyManager.CALL_STATE_RINGING){
28. tts.speak(incomingNumber+" calling", TextToSpeech.QUEUE_FLUSH, null);
29. Toast.makeText(getApplicationContext(),"Phone is Ringing : "+incomingNumbe
r,
30. Toast.LENGTH_LONG).show();
31. }
32. if(state==TelephonyManager.CALL_STATE_OFFHOOK){
33. Toast.makeText(getApplicationContext(),"Phone in a call or call picked",
34. Toast.LENGTH_LONG).show();
35. }
36. if(state==TelephonyManager.CALL_STATE_IDLE){
37. //phone is neither ringing nor in a call
38. }
39. }
40. };
41. telephonyManager.listen(callStateListener,PhoneStateListener.LISTEN_CALL_STATE);

42. }
43.
44. @Override
45. public void onInit(int status) {
46. if (status == TextToSpeech.SUCCESS) {
47. int result = tts.setLanguage(Locale.US);
48. if (result == TextToSpeech.LANG_MISSING_DATA
49. || result == TextToSpeech.LANG_NOT_SUPPORTED) {

Email:[email protected]
245 | P a g e APS Microtech Pvt Ltd

50. Log.e("TTS", "This Language is not supported");


51. } else {
52. }
53.
54. } else {
55. Log.e("TTS", "Initilization Failed!");
56. }
57. }
58.
59. @Override
60. public void onDestroy() {
61. // Don't forget to shutdown tts!
62. if (tts != null) {
63. tts.stop();
64. tts.shutdown();
65. }
66. super.onDestroy();
67. }
68. }

AndroidManifest.xml

You need to add READ_PHONE_STATE uses permission in this xml file. Let's see the
full code.

File: AndroidManifest.xml

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


2. <manifest xmlns:androclass="http://schemas.android.com/apk/res/android"
3. package="com.example.callertalker"
4. android:versionCode="1"
5. android:versionName="1.0" >
6.
7. <uses-sdk
8. android:minSdkVersion="8"
9. android:targetSdkVersion="17" />
10.
11. <uses-permission android:name="android.permission.READ_PHONE_STATE" />
12.
13. <application
14. android:allowBackup="true"
15. android:icon="@drawable/ic_launcher"
16. android:label="@string/app_name"
17. android:theme="@style/AppTheme" >
18. <activity
19. android:name="com.example.callertalker.MainActivity"
20. android:label="@string/app_name" >

Email:[email protected]
246 | P a g e APS Microtech Pvt Ltd

21. <intent-filter>
22. <action android:name="android.intent.action.MAIN" />
23.
24. <category android:name="android.intent.category.LAUNCHER" />
25. </intent-filter>
26. </activity>
27. </application>
28.
29. </manifest>

download this android example

Output:

Run it on the actual device like mobile phone and make call to this from another mobile,
then you will listen the incoming number.

How to make a phone call in android


We are able to make a phone call in android via intent. You need to write only three lines

Email:[email protected]
247 | P a g e APS Microtech Pvt Ltd

of code to make a phone call.

1. Intent callIntent = new Intent(Intent.ACTION_CALL);


2. callIntent.setData(Uri.parse("tel:"+8802177690));//change the number
3. startActivity(callIntent);

Example of phone call in android

activity_main.xml

Drag the EditText and Button from the pallete, now the activity_main.xml file will like
this:

File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <Button
8. android:id="@+id/button1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentTop="true"
12. android:layout_centerHorizontal="true"
13. android:layout_marginTop="118dp"
14. android:text="Call" />
15.
16. <EditText
17. android:id="@+id/editText1"
18. android:layout_width="wrap_content"
19. android:layout_height="wrap_content"
20. android:layout_alignParentTop="true"
21. android:layout_centerHorizontal="true"
22. android:layout_marginTop="25dp"
23. android:ems="10" />
24.
25. </RelativeLayout>

Write the permission code in Android-Manifest.xml file

Email:[email protected]
248 | P a g e APS Microtech Pvt Ltd

You need to write CALL_PHONE permission as given below:

1. <uses-permission android:name="android.permission.CALL_PHONE" />

File: Android-Manifest.xml

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


2.
3. <manifest xmlns:androclass="http://schemas.android.com/apk/res/android"
4. package="com.example.phonecall"
5. android:versionCode="1"
6. android:versionName="1.0" >
7.
8. <uses-sdk
9. android:minSdkVersion="8"
10. android:targetSdkVersion="16" />
11.
12. <uses-permission android:name="android.permission.CALL_PHONE" />
13. <application
14. android:allowBackup="true"
15. android:icon="@drawable/ic_launcher"
16. android:label="@string/app_name"
17. android:theme="@style/AppTheme" >
18. <activity
19. android:name="com.example.phonecall.MainActivity"
20. android:label="@string/app_name" >
21. <intent-filter>
22. <action android:name="android.intent.action.MAIN" />
23.
24. <category android:name="android.intent.category.LAUNCHER" />
25. </intent-filter>
26. </activity>
27. </application>
28.
29. </manifest>

Activity class

Let's write the code to make the phone call via intent.

File: MainActivity.java

1. package com.example.phonecall;
2.

Email:[email protected]
249 | P a g e APS Microtech Pvt Ltd

3. import android.net.Uri;
4. import android.os.Bundle;
5. import android.app.Activity;
6. import android.content.Intent;
7. import android.view.Menu;
8. import android.view.View;
9. import android.view.View.OnClickListener;
10. import android.widget.Button;
11. import android.widget.EditText;
12.
13. public class MainActivity extends Activity {
14. EditText edittext1;
15. Button button1;
16. @Override
17. protected void onCreate(Bundle savedInstanceState) {
18. super.onCreate(savedInstanceState);
19. setContentView(R.layout.activity_main);
20.
21. //Getting the edittext and button instance
22. edittext1=(EditText)findViewById(R.id.editText1);
23. button1=(Button)findViewById(R.id.button1);
24.
25. //Performing action on button click
26. button1.setOnClickListener(new OnClickListener(){
27.
28. @Override
29. public void onClick(View arg0) {
30. String number=edittext1.getText().toString();
31. Intent callIntent = new Intent(Intent.ACTION_CALL);
32. callIntent.setData(Uri.parse("tel:"+number));
33. startActivity(callIntent);
34. }
35.
36. });
37. }
38.
39. @Override
40. public boolean onCreateOptionsMenu(Menu menu) {
41. // Inflate the menu; this adds items to the action bar if it is present.
42. getMenuInflater().inflate(R.menu.activity_main, menu);
43. return true;
44. }
45.
46. }

download this example

Email:[email protected]
250 | P a g e APS Microtech Pvt Ltd

Install and Run the apk file on the Real Device (e.g. Mobile) to make the phone call.

Output:

Email:[email protected]
251 | P a g e APS Microtech Pvt Ltd

Email:[email protected]
252 | P a g e APS Microtech Pvt Ltd

How to send sms in android


We can send sms in android via intent. You need to write only 4 lines of code the send
sms in android.

1. //Getting intent and PendingIntent instance


2. Intent intent=new Intent(getApplicationContext(),MainActivity.class);
3. PendingIntent pi=PendingIntent.getActivity(getApplicationContext(), 0, intent,0);
4.
5. //Get the SmsManager instance and call the sendTextMessage method to send message

6. SmsManager sms=SmsManager.getDefault();
7. sms.sendTextMessage("8802177690", null, "hello javatpoint", pi,null);

Example of sending sms in android

activity_main.xml

Drag the 2 edittexts, 2 textviews and 1 button from the pallete, now the activity_main.xml
file will like this:

File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <EditText
8. android:id="@+id/editText1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentRight="true"
12. android:layout_alignParentTop="true"
13. android:layout_marginRight="20dp"
14. android:ems="10" />
15.
16. <EditText
17. android:id="@+id/editText2"
18. android:layout_width="wrap_content"
19. android:layout_height="wrap_content"
20. android:layout_alignLeft="@+id/editText1"
21. android:layout_below="@+id/editText1"

Email:[email protected]
253 | P a g e APS Microtech Pvt Ltd

22. android:layout_marginTop="26dp"
23. android:ems="10"
24. android:inputType="textMultiLine" />
25.
26. <TextView
27. android:id="@+id/textView1"
28. android:layout_width="wrap_content"
29. android:layout_height="wrap_content"
30. android:layout_alignBaseline="@+id/editText1"
31. android:layout_alignBottom="@+id/editText1"
32. android:layout_toLeftOf="@+id/editText1"
33. android:text="Mobile No:" />
34.
35. <TextView
36. android:id="@+id/textView2"
37. android:layout_width="wrap_content"
38. android:layout_height="wrap_content"
39. android:layout_alignBaseline="@+id/editText2"
40. android:layout_alignBottom="@+id/editText2"
41. android:layout_alignLeft="@+id/textView1"
42. android:text="Message:" />
43.
44. <Button
45. android:id="@+id/button1"
46. android:layout_width="wrap_content"
47. android:layout_height="wrap_content"
48. android:layout_alignLeft="@+id/editText2"
49. android:layout_below="@+id/editText2"
50. android:layout_marginLeft="34dp"
51. android:layout_marginTop="48dp"
52. android:text="Send SMS" />
53.
54. </RelativeLayout>

Write the permission code in Android-Manifest.xml file

You need to write SEND_SMS permission as given below:

1. <uses-permission android:name="android.permission.SEND_SMS"/>
2.

File: Android-Manifest.xml

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


2. <manifest

Email:[email protected]
254 | P a g e APS Microtech Pvt Ltd

3. xmlns:androclass="http://schemas.android.com/apk/res/android"
4. package="com.example.sendsms"
5. android:versionCode="1"
6. android:versionName="1.0" >
7.
8. <uses-sdk
9. android:minSdkVersion="8"
10. android:targetSdkVersion="16" />
11.
12. <uses-permission android:name="android.permission.SEND_SMS"/>
13.
14. <uses-permission android:name="android.permission.RECEIVE_SMS"/>
15.
16. <application
17. android:allowBackup="true"
18. android:icon="@drawable/ic_launcher"
19. android:label="@string/app_name"
20. android:theme="@style/AppTheme" >
21. <activity
22. android:name="com.example.sendsms.MainActivity"
23. android:label="@string/app_name" >
24. <intent-filter>
25. <action android:name="android.intent.action.MAIN" />
26.
27. <category android:name="android.intent.category.LAUNCHER" />
28. </intent-filter>
29. </activity>
30. </application>
31.
32. </manifest>

Activity class

Let's write the code to make the phone call via intent.

File: MainActivity.java

1. package com.example.sendsms;
2.
3. import android.os.Bundle;
4. import android.app.Activity;
5. import android.app.PendingIntent;
6. import android.content.Intent;
7. import android.telephony.SmsManager;
8. import android.view.Menu;

Email:[email protected]
255 | P a g e APS Microtech Pvt Ltd

9. import android.view.View;
10. import android.view.View.OnClickListener;
11. import android.widget.Button;
12. import android.widget.EditText;
13. import android.widget.Toast;
14.
15. public class MainActivity extends Activity {
16.
17. EditText mobileno,message;
18. Button sendsms;
19. @Override
20. protected void onCreate(Bundle savedInstanceState) {
21. super.onCreate(savedInstanceState);
22. setContentView(R.layout.activity_main);
23.
24. mobileno=(EditText)findViewById(R.id.editText1);
25. message=(EditText)findViewById(R.id.editText2);
26. sendsms=(Button)findViewById(R.id.button1);
27.
28. //Performing action on button click
29. sendsms.setOnClickListener(new OnClickListener() {
30.
31. @Override
32. public void onClick(View arg0) {
33. String no=mobileno.getText().toString();
34. String msg=message.getText().toString();
35.
36. //Getting intent and PendingIntent instance
37. Intent intent=new Intent(getApplicationContext(),MainActivity.class);
38. PendingIntent pi=PendingIntent.getActivity(getApplicationContext(), 0, intent,0)
;
39.
40. //Get the SmsManager instance and call the sendTextMessage method to send
message
41. SmsManager sms=SmsManager.getDefault();
42. sms.sendTextMessage(no, null, msg, pi,null);
43.
44. Toast.makeText(getApplicationContext(), "Message Sent successfully!",
45. Toast.LENGTH_LONG).show();
46. }
47. });
48. }
49.
50. @Override
51. public boolean onCreateOptionsMenu(Menu menu) {
52. // Inflate the menu; this adds items to the action bar if it is present.
53. getMenuInflater().inflate(R.menu.activity_main, menu);

Email:[email protected]
256 | P a g e APS Microtech Pvt Ltd

54. return true;


55. }
56.
57. }

download this example

Install and Run the apk file on the Real Device (e.g. Mobile) to send the sms.

Output:

Email:[email protected]
257 | P a g e APS Microtech Pvt Ltd

Email:[email protected]
258 | P a g e APS Microtech Pvt Ltd

How to send email in android using intent


We can easily send email in android via intent. You need to write few lines of code only
as given below

1. Intent email = new Intent(Intent.ACTION_SEND);


2. email.putExtra(Intent.EXTRA_EMAIL, new String[]{ to});
3. email.putExtra(Intent.EXTRA_SUBJECT, subject);
4. email.putExtra(Intent.EXTRA_TEXT, message);
5.
6. //need this to prompts email client only
7. email.setType("message/rfc822");
8.
9. startActivity(Intent.createChooser(email, "Choose an Email client :"));

Example of phone call in android

activity_main.xml

Drag the 2 EditTexts, 1 MultiLine EditText, 3 TextViews and 1 Button from the pallete,
now the activity_main.xml file will like this:

File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <EditText
8. android:id="@+id/editText1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentRight="true"
12. android:layout_alignParentTop="true"
13. android:layout_marginRight="22dp"
14. android:layout_marginTop="16dp"
15. android:ems="10" />
16.
17. <EditText
18. android:id="@+id/editText2"
19. android:layout_width="wrap_content"
20. android:layout_height="wrap_content"

Email:[email protected]
259 | P a g e APS Microtech Pvt Ltd

21. android:layout_alignLeft="@+id/editText1"
22. android:layout_below="@+id/editText1"
23. android:layout_marginTop="18dp"
24. android:ems="10" >
25.
26. <requestFocus />
27. </EditText>
28.
29. <EditText
30. android:id="@+id/editText3"
31. android:layout_width="wrap_content"
32. android:layout_height="wrap_content"
33. android:layout_alignLeft="@+id/editText2"
34. android:layout_below="@+id/editText2"
35. android:layout_marginTop="28dp"
36. android:ems="10"
37. android:inputType="textMultiLine" />
38.
39. <TextView
40. android:id="@+id/textView1"
41. android:layout_width="wrap_content"
42. android:layout_height="wrap_content"
43. android:layout_alignBaseline="@+id/editText1"
44. android:layout_alignBottom="@+id/editText1"
45. android:layout_alignParentLeft="true"
46. android:text="To:" />
47.
48. <TextView
49. android:id="@+id/textView2"
50. android:layout_width="wrap_content"
51. android:layout_height="wrap_content"
52. android:layout_alignBaseline="@+id/editText2"
53. android:layout_alignBottom="@+id/editText2"
54. android:layout_alignParentLeft="true"
55. android:text="Subject:" />
56.
57. <TextView
58. android:id="@+id/textView3"
59. android:layout_width="wrap_content"
60. android:layout_height="wrap_content"
61. android:layout_alignBaseline="@+id/editText3"
62. android:layout_alignBottom="@+id/editText3"
63. android:layout_alignParentLeft="true"
64. android:text="Message:" />
65.
66. <Button
67. android:id="@+id/button1"

Email:[email protected]
260 | P a g e APS Microtech Pvt Ltd

68. android:layout_width="wrap_content"
69. android:layout_height="wrap_content"
70. android:layout_alignLeft="@+id/editText3"
71. android:layout_below="@+id/editText3"
72. android:layout_marginLeft="76dp"
73. android:layout_marginTop="20dp"
74. android:text="Send" />
75.
76. </RelativeLayout>

Activity class

Let's write the code to send email via intent.

File: MainActivity.java

1. package com.example.sendemail;
2.
3. import android.os.Bundle;
4. import android.app.Activity;
5. import android.content.Intent;
6. import android.view.Menu;
7. import android.view.View;
8. import android.view.View.OnClickListener;
9. import android.widget.Button;
10. import android.widget.EditText;
11.
12. public class MainActivity extends Activity {
13. EditText editTextTo,editTextSubject,editTextMessage;
14. Button send;
15. @Override
16. protected void onCreate(Bundle savedInstanceState) {
17. super.onCreate(savedInstanceState);
18. setContentView(R.layout.activity_main);
19.
20. editTextTo=(EditText)findViewById(R.id.editText1);
21. editTextSubject=(EditText)findViewById(R.id.editText2);
22. editTextMessage=(EditText)findViewById(R.id.editText3);
23.
24. send=(Button)findViewById(R.id.button1);
25.
26. send.setOnClickListener(new OnClickListener(){
27.
28. @Override
29. public void onClick(View arg0) {

Email:[email protected]
261 | P a g e APS Microtech Pvt Ltd

30. String to=editTextTo.getText().toString();


31. String subject=editTextSubject.getText().toString();
32. String message=editTextMessage.getText().toString();
33.
34.
35. Intent email = new Intent(Intent.ACTION_SEND);
36. email.putExtra(Intent.EXTRA_EMAIL, new String[]{ to});
37. email.putExtra(Intent.EXTRA_SUBJECT, subject);
38. email.putExtra(Intent.EXTRA_TEXT, message);
39.
40. //need this to prompts email client only
41. email.setType("message/rfc822");
42.
43. startActivity(Intent.createChooser(email, "Choose an Email client :"));
44.
45. }
46.
47. });
48. }
49.
50. @Override
51. public boolean onCreateOptionsMenu(Menu menu) {
52. // Inflate the menu; this adds items to the action bar if it is present.
53. getMenuInflater().inflate(R.menu.activity_main, menu);
54. return true;
55. }
56.
57. }

Android Bluetooth Tutorial


Email:[email protected]
262 | P a g e APS Microtech Pvt Ltd

Bluetooth is a way to exchange data with other devices wirelessly. Android provides
Bluetooth API to perform several tasks such as:

 scan bluetooth devices


 connect and transfer data from and to other devices
 manage multiple connections etc.

Android Bluetooth API


The android.bluetooth package provides a lot of interfaces classes to work with bluetooth
such as:

 BluetoothAdapter
 BluetoothDevice
 BluetoothSocket
 BluetoothServerSocket
 BluetoothClass
 BluetoothProfile
 BluetoothProfile.ServiceListener
 BluetoothHeadset
 BluetoothA2dp
 BluetoothHealth
 BluetoothHealthCallback
 BluetoothHealthAppConfiguration

BluetoothAdapter class
By the help of BluetoothAdapter class, we can perform fundamental tasks such as initiate
device discovery, query a list of paired (bonded) devices, create a BluetoothServerSocket
instance to listen for connection requests etc.

Constants of BluetoothAdapter class

BluetoothAdapter class provides many constants. Some of them are as follows:

 String ACTION_REQUEST_ENABLE
 String ACTION_REQUEST_DISCOVERABLE
 String ACTION_DISCOVERY_STARTED
 String ACTION_DISCOVERY_FINISHED

Methods of BluetoothAdapter class

Email:[email protected]
263 | P a g e APS Microtech Pvt Ltd

Commonly used methods of BluetoothAdapter class are as follows:

 static synchronized BluetoothAdapter getDefaultAdapter() returns the instance of


BluetoothAdapter.
 boolean enable() enables the bluetooth adapter if it is disabled.
 boolean isEnabled() returns true if the bluetooth adapter is enabled.
 boolean disable() disables the bluetooth adapter if it is enabled.
 String getName() returns the name of the bluetooth adapter.
 boolean setName(String name) changes the bluetooth name.
 int getState() returns the current state of the local bluetooth adapter.
 Set<BluetoothDevice> getBondedDevices() returns a set of paired (bonded)
BluetoothDevice objects.
 boolean startDiscovery() starts the discovery process.

Android Bluetooth Example: enable, disable and make discovrable bluetooth


programmatically

You need to write few lines of code only, to enable or disable the bluetooth.

activity_main.xml

Drag one textview and three buttons from the pallete, now the activity_main.xml file will
like this:

File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <TextView android:text=""
8. android:id="@+id/out"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content">
11. </TextView>
12. <Button
13. android:id="@+id/button1"
14. android:layout_width="wrap_content"
15. android:layout_height="wrap_content"
16. android:layout_alignParentLeft="true"
17. android:layout_alignParentTop="true"
18. android:layout_marginLeft="30dp"

Email:[email protected]
264 | P a g e APS Microtech Pvt Ltd

19. android:layout_marginTop="49dp"
20. android:text="TURN_ON" />
21.
22. <Button
23. android:id="@+id/button2"
24. android:layout_width="wrap_content"
25. android:layout_height="wrap_content"
26. android:layout_alignLeft="@+id/button1"
27. android:layout_below="@+id/button1"
28. android:layout_marginTop="27dp"
29. android:text="DISCOVERABLE" />
30.
31. <Button
32. android:id="@+id/button3"
33. android:layout_width="wrap_content"
34. android:layout_height="wrap_content"
35. android:layout_alignLeft="@+id/button2"
36. android:layout_below="@+id/button2"
37. android:layout_marginTop="28dp"
38. android:text="TURN_OFF" />
39.
40. </RelativeLayout>

Provide Permission

You need to provide following permissions in AndroidManifest.xml file.

1. <uses-permission android:name="android.permission.BLUETOOTH" />


2. <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

The full code of AndroidManifest.xml file is given below.

File: AndroidManifest.xml

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


2. <manifest xmlns:androclass="http://schemas.android.com/apk/res/android"
3. package="com.example.bluetooth"
4. android:versionCode="1"
5. android:versionName="1.0" >
6.
7. <uses-sdk
8. android:minSdkVersion="8"
9. android:targetSdkVersion="16" />
10.
11. <uses-permission android:name="android.permission.BLUETOOTH" />

Email:[email protected]
265 | P a g e APS Microtech Pvt Ltd

12. <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />


13.
14. <application
15. android:allowBackup="true"
16. android:icon="@drawable/ic_launcher"
17. android:label="@string/app_name"
18. android:theme="@style/AppTheme" >
19. <activity
20. android:name="com.example.bluetooth.MainActivity"
21. android:label="@string/app_name" >
22. <intent-filter>
23. <action android:name="android.intent.action.MAIN" />
24.
25. <category android:name="android.intent.category.LAUNCHER" />
26. </intent-filter>
27. </activity>
28. </application>
29.
30. </manifest>

Activity class

Let's write the code to enable, disable and make bluetooth discoverable.

File: MainActivity.java

1. package com.example.bluetooth;
2. import android.os.Bundle;
3. import android.app.Activity;
4. import android.view.Menu;
5. import android.app.Activity;
6. import android.bluetooth.BluetoothAdapter;
7. import android.content.Context;
8. import android.content.Intent;
9. import android.os.Bundle;
10. import android.util.Log;
11. import android.view.View;
12. import android.widget.Button;
13. import android.widget.TextView;
14. import android.widget.Toast;
15.
16. public class MainActivity extends Activity {
17. private static final int REQUEST_ENABLE_BT = 0;
18. private static final int REQUEST_DISCOVERABLE_BT = 0;
19. @Override

Email:[email protected]
266 | P a g e APS Microtech Pvt Ltd

20. protected void onCreate(Bundle savedInstanceState) {


21. super.onCreate(savedInstanceState);
22. setContentView(R.layout.activity_main);
23. final TextView out=(TextView)findViewById(R.id.out);
24. final Button button1 = (Button) findViewById(R.id.button1);
25. final Button button2 = (Button) findViewById(R.id.button2);
26. final Button button3 = (Button) findViewById(R.id.button3);
27. final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
28. if (mBluetoothAdapter == null) {
29. out.append("device not supported");
30. }
31. button1.setOnClickListener(new View.OnClickListener() {
32. public void onClick(View v) {
33. if (!mBluetoothAdapter.isEnabled()) {
34. Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABL
E);
35. startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
36. }
37. }
38. });
39. button2.setOnClickListener(new View.OnClickListener() {
40. @Override
41. public void onClick(View arg0) {
42. if (!mBluetoothAdapter.isDiscovering()) {
43. //out.append("MAKING YOUR DEVICE DISCOVERABLE");
44. Toast.makeText(getApplicationContext(), "MAKING YOUR DEVICE DISCOVERAB
LE",
45. Toast.LENGTH_LONG);
46.
47. Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCO
VERABLE);
48. startActivityForResult(enableBtIntent, REQUEST_DISCOVERABLE_BT);
49.
50. }
51. }
52. });
53. button3.setOnClickListener(new View.OnClickListener() {
54. @Override
55. public void onClick(View arg0) {
56. mBluetoothAdapter.disable();
57. //out.append("TURN_OFF BLUETOOTH");
58. Toast.makeText(getApplicationContext(), "TURNING_OFF BLUETOOTH", Toast.LEN
GTH_LONG);
59.
60. }
61. });
62. }

Email:[email protected]
267 | P a g e APS Microtech Pvt Ltd

63.
64. @Override
65. public boolean onCreateOptionsMenu(Menu menu) {
66. // Inflate the menu; this adds items to the action bar if it is present.
67. getMenuInflater().inflate(R.menu.activity_main, menu);
68. return true;
69. }
70.
71. }

You need to run it on the real device (e.g. mobile) to test the application.

Android Bluetooth List Paired Devices


Example

Email:[email protected]
268 | P a g e APS Microtech Pvt Ltd

The getBoundedDevices() method of BluetoothAdapter class provides a set containing list of all
paired or bounded bluetooth devices.

In this example, we are checking if the bluetooth is turned off, if yes then turn it on and list all
the paired devices.

activity_main.xml

Drag one textview from the pallete, now the activity_main.xml file will like this:

File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <TextView
8. android:id="@+id/textView1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentLeft="true"
12. android:layout_alignParentTop="true"
13. android:layout_marginLeft="18dp"
14. android:layout_marginTop="61dp"
15. android:text="Showing Paired Devices:" />
16.
17. </RelativeLayout>

Provide Permission

You need to provide following permissions in AndroidManifest.xml file.

1. <uses-permission android:name="android.permission.BLUETOOTH" />


2. <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

The full code of AndroidManifest.xml file is given below.

File: AndroidManifest.xml

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


2. <manifest xmlns:androclass="http://schemas.android.com/apk/res/android"
3. package="com.example.bluetoothshowpaired"
4. android:versionCode="1"

Email:[email protected]
269 | P a g e APS Microtech Pvt Ltd

5. android:versionName="1.0" >
6.
7. <uses-sdk
8. android:minSdkVersion="8"
9. android:targetSdkVersion="17" />
10.
11. <uses-permission android:name="android.permission.BLUETOOTH" />
12. <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
13.
14. <application
15. android:allowBackup="true"
16. android:icon="@drawable/ic_launcher"
17. android:label="@string/app_name"
18. android:theme="@style/AppTheme" >
19. <activity
20. android:name="com.example.bluetoothshowpaired.MainActivity"
21. android:label="@string/app_name" >
22. <intent-filter>
23. <action android:name="android.intent.action.MAIN" />
24.
25. <category android:name="android.intent.category.LAUNCHER" />
26. </intent-filter>
27. </activity>
28. </application>
29.
30. </manifest>

Activity class

Let's write the code to provide the list of paired (bounded) bluetooth devices.

File: MainActivity.java

1. package com.example.bluetoothshowpaired;
2.
3. import android.os.Bundle;
4. import android.app.Activity;
5. import android.view.Menu;
6. import java.util.Set;
7. import android.bluetooth.BluetoothAdapter;
8. import android.bluetooth.BluetoothDevice;
9. import android.content.Intent;
10. import android.widget.TextView;
11.
12. public class MainActivity extends Activity {

Email:[email protected]
270 | P a g e APS Microtech Pvt Ltd

13. TextView textview1;


14. private static final int REQUEST_ENABLE_BT = 1;
15. BluetoothAdapter btAdapter;
16.
17. /** Called when the activity is first created. */
18. @Override
19. public void onCreate(Bundle savedInstanceState) {
20. super.onCreate(savedInstanceState);
21. setContentView(R.layout.activity_main);
22.
23. textview1 = (TextView) findViewById(R.id.textView1);
24.
25. // Getting the Bluetooth adapter
26. btAdapter = BluetoothAdapter.getDefaultAdapter();
27. textview1.append("\nAdapter: " + btAdapter);
28.
29. CheckBluetoothState();
30. }
31.
32. /* It is called when an activity completes.*/
33. @Override
34. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
35. super.onActivityResult(requestCode, resultCode, data);
36. if (requestCode == REQUEST_ENABLE_BT) {
37. CheckBluetoothState();
38. }
39. }
40.
41. @Override
42. protected void onDestroy() {
43. super.onDestroy();
44. }
45.
46. private void CheckBluetoothState() {
47. // Checks for the Bluetooth support and then makes sure it is turned on
48. // If it isn't turned on, request to turn it on
49. // List paired devices
50. if(btAdapter==null) {
51. textview1.append("\nBluetooth NOT supported. Aborting.");
52. return;
53. } else {
54. if (btAdapter.isEnabled()) {
55. textview1.append("\nBluetooth is enabled...");
56.
57. // Listing paired devices
58. textview1.append("\nPaired Devices are:");
59. Set<BluetoothDevice> devices = btAdapter.getBondedDevices();
60. for (BluetoothDevice device : devices) {

Email:[email protected]
271 | P a g e APS Microtech Pvt Ltd

61. textview1.append("\n Device: " + device.getName() + ", " + device);


62. }
63. } else {
64. //Prompt user to turn on Bluetooth
65. Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
66. startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
67. }
68. }
69. }
70.
71.
72. @Override
73. public boolean onCreateOptionsMenu(Menu menu) {
74. // Inflate the menu; this adds items to the action bar if it is present.
75. getMenuInflater().inflate(R.menu.activity_main, menu);
76. return true;
77. }
78.
79. }

You need to run it on the real device (e.g. mobile) to test the application.

Android Wifi Example


The android.net.wifi.WifiManager class can be used to manage the wifi connectivity. It can be
used to add network, disable network, scan for access points, disconnect etc.

Email:[email protected]
272 | P a g e APS Microtech Pvt Ltd

Android wifi example to enable and disable wifi

Let's see the simple example of wifi to enable and disable the wifi service.

activity_main.xml
File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <Button
8. android:id="@+id/button1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentLeft="true"
12. android:layout_alignParentTop="true"
13. android:layout_marginLeft="76dp"
14. android:layout_marginTop="67dp"
15. android:text="Enable Wifi" />
16.
17. <Button
18. android:id="@+id/button2"
19. android:layout_width="wrap_content"
20. android:layout_height="wrap_content"
21. android:layout_alignLeft="@+id/button1"
22. android:layout_below="@+id/button1"
23. android:layout_marginTop="44dp"
24. android:text="Disable Wifi" />
25.
26. </RelativeLayout>

Activity class
File: MainActivity.java

1. package com.example.wifi;
2.
3. import android.net.wifi.WifiManager;
4. import android.os.Bundle;
5. import android.app.Activity;
6. import android.content.Context;
7. import android.view.Menu;
8. import android.view.View;

Email:[email protected]
273 | P a g e APS Microtech Pvt Ltd

9. import android.view.View.OnClickListener;
10. import android.widget.Button;
11.
12. public class MainActivity extends Activity {
13. Button enableButton,disableButton;
14. @Override
15. protected void onCreate(Bundle savedInstanceState) {
16. super.onCreate(savedInstanceState);
17. setContentView(R.layout.activity_main);
18.
19. enableButton=(Button)findViewById(R.id.button1);
20. disableButton=(Button)findViewById(R.id.button2);
21.
22. enableButton.setOnClickListener(new OnClickListener(){
23. public void onClick(View v){
24. WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
25. wifi.setWifiEnabled(true);
26. }
27. });
28. disableButton.setOnClickListener(new OnClickListener(){
29. public void onClick(View v){
30. WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
31. wifi.setWifiEnabled(false);
32. }
33. });
34. }
35.
36. @Override
37. public boolean onCreateOptionsMenu(Menu menu) {
38. // Inflate the menu; this adds items to the action bar if it is present.
39. getMenuInflater().inflate(R.menu.activity_main, menu);
40. return true;
41. }
42.
43. }

Add Permission in AndroidManifest.xml

You need to add following permissions in AndroidManifest.xml file.

1. <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />


2. <uses-permission android:name="android.permission.INTERNET" />
3. <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>

download this android example

Email:[email protected]
274 | P a g e APS Microtech Pvt Ltd

Output:

Android Camera Tutorial


Camera is mainly used to capture picture and video. We can control the camera by using
methods of camera api.

Android provides the facility to work on camera by 2 ways:


Email:[email protected]
275 | P a g e APS Microtech Pvt Ltd

1. By Camera Intent
2. By Camera API

Understanding basic classes of Camera Intent and API


There are mainly four classes that we are going to discuss.

Intent

By the help of 2 constants of MediaStore class, we can capture picture and video without using
the instance of Camera class.

1. ACTION_IMAGE_CAPTURE
2. ACTION_VIDEO_CAPTURE

Camera

It is main class of camera api, that can be used to take picture and video.

SurfaceView

It represents a surface view ore preview of live camera.

MediaRecorder

It is used to record video using camera. It can also be used to record audio files as we have seen
in the previous example of media framework.

Android camera app example by camera intent

In this example, we are writing the simple code to capture image using camera and displaying
the image using imageview.

activity_main.xml

Drag one imageview and one button from the pallete, now the xml file will look like this:

File: activity_main.xml

Email:[email protected]
276 | P a g e APS Microtech Pvt Ltd

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <Button
8. android:id="@+id/button1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentBottom="true"
12. android:layout_centerHorizontal="true"
13. android:text="Take a Photo" >
14. </Button>
15.
16. <ImageView
17. android:id="@+id/imageView1"
18. android:layout_width="fill_parent"
19. android:layout_height="fill_parent"
20. android:layout_above="@+id/button1"
21. android:layout_alignParentTop="true"
22. android:src="@drawable/ic_launcher" >
23. </ImageView>
24. </RelativeLayout>

Activity class

Let's write the code to capture image using camera and displaying it on the image view.

File: MainActivity.java

1. package com.example.simplecamera;
2.
3. import android.app.Activity;
4. import android.content.Intent;
5. import android.graphics.Bitmap;
6. import android.os.Bundle;
7. import android.view.Menu;
8. import android.view.View;
9. import android.widget.Button;
10. import android.widget.ImageView;
11.
12. public class MainActivity extends Activity {
13. private static final int CAMERA_REQUEST = 1888;
14. ImageView imageView;

Email:[email protected]
277 | P a g e APS Microtech Pvt Ltd

15. public void onCreate(Bundle savedInstanceState) {


16.
17. super.onCreate(savedInstanceState);
18. setContentView(R.layout.activity_main);
19.
20. imageView = (ImageView) this.findViewById(R.id.imageView1);
21. Button photoButton = (Button) this.findViewById(R.id.button1);
22.
23. photoButton.setOnClickListener(new View.OnClickListener() {
24.
25. @Override
26. public void onClick(View v) {
27. Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTU
RE);
28. startActivityForResult(cameraIntent, CAMERA_REQUEST);
29. }
30. });
31. }
32.
33. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
34. if (requestCode == CAMERA_REQUEST) {
35. Bitmap photo = (Bitmap) data.getExtras().get("data");
36. imageView.setImageBitmap(photo);
37. }
38. }
39.
40. @Override
41. public boolean onCreateOptionsMenu(Menu menu) {
42. // Inflate the menu; this adds items to the action bar if it is present.
43. getMenuInflater().inflate(R.menu.activity_main, menu);
44. return true;
45. }
46.
47. }

download this android example

Email:[email protected]
278 | P a g e APS Microtech Pvt Ltd

Output:

Android Sensor Tutorial


Sensors can be used to monitor the three-dimensional device movement or change in the
environment of the device.

Email:[email protected]
279 | P a g e APS Microtech Pvt Ltd

Android provides sensor api to work with different types of sensors.

Types of Sensors
Android supports three types of sensors:

1) Motion Sensors

These are used to measure acceleration forces and rotational forces along with three axes.

2) Position Sensors

These are used to measure the physical position of device.

3) Environmental Sensors

These are used to measure the environmental changes such as temperature, humidity etc.

Email:[email protected]
280 | P a g e APS Microtech Pvt Ltd

Android Sensor API


Android sensor api provides many classes and interface. The important classes and interfaces of
sensor api are as follows:

1) SensorManager class

The android.hardware.SensorManager class provides methods :

 to get sensor instance,


 to access and list sensors,
 to register and unregister sensor listeners etc.

You can get the instance of SensorManager by calling the method getSystemService() and
passing the SENSOR_SERVICE constant in it.

1. SensorManager sm = (SensorManager)getSystemService(SENSOR_SERVICE);

2) Sensor class

The android.hardware.Sensor class provides methods to get information of the sensor such as
sensor name, sensor type, sensor resolution, sensor type etc.

3) SensorEvent class

Its instance is created by the system. It provides information about the sensor.

4) SensorEventListener interface

It provides two call back methods to get information when sensor values (x,y and z) change or
sensor accuracy changes.

Public and abstract methods Description

void onAccuracyChanged(Sensor sensor, int accuracy) it is called when sensor accuracy is changed.

void onSensorChanged(SensorEvent event) it is called when sensor values are changed.

Android simple sensor app example

Let's see the two sensor examples.

1. A sensor example that prints x, y and z axis values. Here, we are going to see that.

Email:[email protected]
281 | P a g e APS Microtech Pvt Ltd

2. A sensor example that changes the background color when device is shuffled. Click for changing
background color of activity sensor example

activity_main.xml

There is only one textview in this file.

File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <TextView
8. android:id="@+id/textView1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentLeft="true"
12. android:layout_alignParentTop="true"
13. android:layout_marginLeft="92dp"
14. android:layout_marginTop="114dp"
15. android:text="TextView" />
16.
17. </RelativeLayout>

Activity class

Let's write the code that prints values of x axis, y axis and z axis.

File: MainActivity.java

1. package com.example.sensorsimple;
2. import android.app.Activity;
3. import android.os.Bundle;
4. import android.widget.TextView;
5. import android.widget.Toast;
6. import android.hardware.SensorManager;
7. import android.hardware.SensorEventListener;
8. import android.hardware.SensorEvent;
9. import android.hardware.Sensor;
10. import java.util.List;
11. public class MainActivity extends Activity {
12. SensorManager sm = null;

Email:[email protected]
282 | P a g e APS Microtech Pvt Ltd

13. TextView textView1 = null;


14. List list;
15.
16. SensorEventListener sel = new SensorEventListener(){
17. public void onAccuracyChanged(Sensor sensor, int accuracy) {}
18. public void onSensorChanged(SensorEvent event) {
19. float[] values = event.values;
20. textView1.setText("x: "+values[0]+"\ny: "+values[1]+"\nz: "+values[2]);
21. }
22. };
23.
24. @Override
25. public void onCreate(Bundle savedInstanceState) {
26. super.onCreate(savedInstanceState);
27. setContentView(R.layout.activity_main);
28.
29. /* Get a SensorManager instance */
30. sm = (SensorManager)getSystemService(SENSOR_SERVICE);
31.
32. textView1 = (TextView)findViewById(R.id.textView1);
33.
34. list = sm.getSensorList(Sensor.TYPE_ACCELEROMETER);
35. if(list.size()>0){
36. sm.registerListener(sel, (Sensor) list.get(0), SensorManager.SENSOR_DELAY_NORMAL);
37. }else{
38. Toast.makeText(getBaseContext(), "Error: No Accelerometer.", Toast.LENGTH_LONG).sho
w();
39. }
40. }
41.
42. @Override
43. protected void onStop() {
44. if(list.size()>0){
45. sm.unregisterListener(sel);
46. }
47. super.onStop();
48. }
49. }

download this android example

Email:[email protected]
283 | P a g e APS Microtech Pvt Ltd

Output:

Global Variable Or Application Context Variable - Android Example

In this example defining variable in application context and you can use this variable as a Global
variable. You can set value in this variable and get value on any activity / broadcast recieiver /
service in application context(environment).

In Further examples you will see good use of this way to follow SINGALTON pattern and MVC
pattern in android.

The problem is how to save value across several Activities and all parts of your application
context. You can achieve this by creating static variable but it is not the good way it influencing

Email:[email protected]
284 | P a g e APS Microtech Pvt Ltd

towards memory leaks. The way in Android is to associate your variable with the Application
context.

Every Application has a context, and Android guarantees that Application context will exist as a
instance across your application.

The way to do this is to create a class and extends with android.app.Application, and specify
your class in the application tag in your AndroidManifest.xml file. Android will create an
instance of that class and make it available for your entire application context. You can get
object of your class on any activity / broadcast reciever / service in application
context(environment) by Context.getApplicationContext() method.

Example WorkFlow :

Project Structure :

Email:[email protected]
285 | P a g e APS Microtech Pvt Ltd

File : src/GlobalClass.java

Email:[email protected]
286 | P a g e APS Microtech Pvt Ltd

Create your custom class subclass of android.app.Application class. you will use this class as
global class for your Application environment(Conext).

package com.androidexample.globalvariable;

import android.app.Application;

public class GlobalClass extends Application{

private String name;


private String email;

public String getName() {

return name;
}

public void setName(String aName) {

name = aName;

public String getEmail() {

return email;
}

public void setEmail(String aEmail) {

email = aEmail;
}

File : AndroidManifest.xml

Assign GlobalClass.java in application tag, see this line in application tag


android:name="com.androidexample.globalvariable.GlobalClass"
After assign you can get GlobalClass.java instance on any activity / broadcast reciever / service
in application context.

Email:[email protected]
287 | P a g e APS Microtech Pvt Ltd

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidexample.globalvariable"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="9" />

<application
android:name="com.androidexample.globalvariable.GlobalClass"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.androidexample.globalvariable.FirstScreen"
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=".SecondScreen" ></activity>


<activity android:name=".ThirdScreen" ></activity>
</application>

</manifest>

File : src/FirstScreen.java

getApplicationContext() method of Context will give GlobalClass.java instance and set


name/email values and maintain state of GlobalClass.java instance.

package com.androidexample.globalvariable;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.app.Activity;

Email:[email protected]
288 | P a g e APS Microtech Pvt Ltd

import android.content.Intent;

public class FirstScreen extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.firstscreen);

final Button secondBtn = (Button) findViewById(R.id.second);

// Calling Application class (see application tag in


AndroidManifest.xml)
final GlobalClass globalVariable = (GlobalClass)
getApplicationContext();

//Set name and email in global/application context


globalVariable.setName("Android Example context variable");
globalVariable.setEmail("[email protected]");

secondBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {

Intent i = new Intent(getBaseContext(), SecondScreen.class);


startActivity(i);
}
});
}
}

File : src/SecondScreen.java

Call getApplicationContext() method of Context and get GlobalClass.java instance , By


GlobalClass.java instance you can get set values for name/email variables.

package com.androidexample.globalvariable;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

Email:[email protected]
289 | P a g e APS Microtech Pvt Ltd

public class SecondScreen extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondscreen);

TextView showGlobal = (TextView) findViewById(R.id.showGlobal);


final Button thirdBtn = (Button) findViewById(R.id.third);

// Calling Application class (see application tag in


AndroidManifest.xml)
final GlobalClass globalVariable = (GlobalClass)
getApplicationContext();

// Get name and email from global/application context


final String name = globalVariable.getName();
final String email = globalVariable.getEmail();

String showString = "

Name : "+name+"
"+
"Email : "+email+"

";

// Show name/email values in TextView


showGlobal.setText(showString);

thirdBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {

Intent i = new Intent(getBaseContext(), ThirdScreen.class);


startActivity(i);
}
});

@Override
protected void onDestroy() {

super.onDestroy();

}
}

Email:[email protected]
290 | P a g e APS Microtech Pvt Ltd

File : src/ThirdScreen.java

Call getApplicationContext() method of Context and get GlobalClass.java instance , By


GlobalClass.java instance you can get set values for name/email variables.

package com.androidexample.globalvariable;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class ThirdScreen extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.thirdscreen);

TextView showGlobal = (TextView) findViewById(R.id.showGlobal);

// Calling Application class (see application tag in


AndroidManifest.xml)
final GlobalClass globalVariable = (GlobalClass)
getApplicationContext();

// Get name and email from global/application context


final String name = globalVariable.getName();
final String email = globalVariable.getEmail();

String showString = "

Name : "+name+"
"+
"Email : "+email+"

";

// Show name/email values in TextView


showGlobal.setText(showString);

}
}

Email:[email protected]
291 | P a g e APS Microtech Pvt Ltd

Android Simple Graphics Example


The android.graphics.Canvas can be used to draw graphics in android. It provides methods to
draw oval, rectangle, picture, text, line etc.

The android.graphics.Paint class is used with canvas to draw objects. It holds the information
of color and style.

In this example, we are going to display 2D graphics in android.

activity_main.xml
File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".MainActivity" >
10.
11. <TextView
12. android:layout_width="wrap_content"
13. android:layout_height="wrap_content"
14. android:text="@string/hello_world" />
15.
16. </RelativeLayout>

Activity class
File: MainActivity.java

1. package com.example.simplegraphics;
2.
3. import android.os.Bundle;
4. import android.app.Activity;
5. import android.view.Menu;
6. import android.content.Context;
7. import android.graphics.Canvas;

Email:[email protected]
292 | P a g e APS Microtech Pvt Ltd

8. import android.graphics.Color;
9. import android.graphics.Paint;
10. import android.view.View;
11.
12. public class MainActivity extends Activity {
13.
14. DemoView demoview;
15. /** Called when the activity is first created. */
16. @Override
17. public void onCreate(Bundle savedInstanceState) {
18. super.onCreate(savedInstanceState);
19. demoview = new DemoView(this);
20. setContentView(demoview);
21. }
22.
23. private class DemoView extends View{
24. public DemoView(Context context){
25. super(context);
26. }
27.
28. @Override protected void onDraw(Canvas canvas) {
29. super.onDraw(canvas);
30.
31. // custom drawing code here
32. Paint paint = new Paint();
33. paint.setStyle(Paint.Style.FILL);
34.
35. // make the entire canvas white
36. paint.setColor(Color.WHITE);
37. canvas.drawPaint(paint);
38.
39. // draw blue circle with anti aliasing turned off
40. paint.setAntiAlias(false);
41. paint.setColor(Color.BLUE);
42. canvas.drawCircle(20, 20, 15, paint);
43.
44. // draw green circle with anti aliasing turned on
45. paint.setAntiAlias(true);
46. paint.setColor(Color.GREEN);
47. canvas.drawCircle(60, 20, 15, paint);
48.
49. // draw red rectangle with anti aliasing turned off
50. paint.setAntiAlias(false);
51. paint.setColor(Color.RED);
52. canvas.drawRect(100, 5, 200, 30, paint);
53.
54. // draw the rotated text
55. canvas.rotate(-45);

Email:[email protected]
293 | P a g e APS Microtech Pvt Ltd

56.
57. paint.setStyle(Paint.Style.FILL);
58. canvas.drawText("Graphics Rotation", 40, 180, paint);
59.
60. //undo the rotate
61. canvas.restore();
62. }
63. }
64. @Override
65. public boolean onCreateOptionsMenu(Menu menu) {
66. // Inflate the menu; this adds items to the action bar if it is present.
67. getMenuInflater().inflate(R.menu.main, menu);
68. return true;
69. }
70. }

download this android example

Output:

Email:[email protected]
294 | P a g e APS Microtech Pvt Ltd

Android Animation Example


Android provides a large number of classes and interface for the animation development. Most
of the classes and interfaces are given in android.animation package.

Android Animation enables you to change the object property and behavior at run time. There
are various ways to do animation in android.

The AnimationDrawable class provides methods to start and end the animation. Even, you can
use time based animation.

Let's have a look at the simple example of android animation.

activity_main.xml

You need to have a view only.

File: activity_main.xml

1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".MainActivity" >
10.
11. <View
12. />
13.
14. </RelativeLayout>

File: logo.xml

Have a image view only.

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


2. <ImageView xmlns:android="http://schemas.android.com/apk/res/android"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:id="@+id/anm"
6. >
7.
8. </ImageView>

Email:[email protected]
295 | P a g e APS Microtech Pvt Ltd

MainActivity class
File: MainActivity.java

1. package com.javatpoint.animation;
2.
3. import android.os.Bundle;
4. import android.app.Activity;
5. import android.graphics.drawable.AnimationDrawable;
6. import android.widget.ImageView;
7.
8. public class MainActivity extends Activity {
9.
10. ImageView anm;
11. public void onCreate(Bundle savedInstanceState) {
12. super.onCreate(savedInstanceState);
13. setContentView(R.layout.logo);
14. anm = (ImageView)findViewById(R.id.anm);
15.
16. anm.setBackgroundResource(R.drawable.animation);
17. // the frame-by-frame animation defined as a xml file within the drawable folder
18.
19. /*
20. * NOTE: It's not possible to start the animation during the onCreate.
21. */
22. }
23. public void onWindowFocusChanged (boolean hasFocus) {
24. super.onWindowFocusChanged(hasFocus);
25. AnimationDrawable frameAnimation =
26. (AnimationDrawable) anm.getBackground();
27. if(hasFocus) {
28. frameAnimation.start();
29. } else {
30. frameAnimation.stop();
31. }
32. }
33.
34. }

You need to create animation.xml file inside res/drawable-hdpi directory.

You need to have many images. Here, we are using 14 images and all the 14 images are located
inside res/drawable-mdpi directory.

Email:[email protected]
296 | P a g e APS Microtech Pvt Ltd

File: animation.xml

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


2. <animation-list xmlns:android="http://schemas.android.com/apk/res/android"
3. android:oneshot="false">
4.
5. <item android:drawable="@drawable/frame0" android:duration="120" />
6. <item android:drawable="@drawable/frame1" android:duration="120" />
7. <item android:drawable="@drawable/frame2" android:duration="120" />
8. <item android:drawable="@drawable/frame3" android:duration="120" />
9. <item android:drawable="@drawable/frame4" android:duration="120" />
10. <item android:drawable="@drawable/frame5" android:duration="120" />
11. <item android:drawable="@drawable/frame6" android:duration="120" />
12. <item android:drawable="@drawable/frame7" android:duration="120" />
13. <item android:drawable="@drawable/frame8" android:duration="120" />
14. <item android:drawable="@drawable/frame9" android:duration="120" />
15. <item android:drawable="@drawable/frame10" android:duration="120" />
16. <item android:drawable="@drawable/frame11" android:duration="120" />
17. <item android:drawable="@drawable/frame12" android:duration="120" />
18. <item android:drawable="@drawable/frame13" android:duration="120" />
19. <item android:drawable="@drawable/frame14" android:duration="120" />
20. <item android:drawable="@drawable/frame14" android:duration="120" />
21. <item android:drawable="@drawable/frame13" android:duration="120" />
22. <item android:drawable="@drawable/frame12" android:duration="120" />
23. <item android:drawable="@drawable/frame11" android:duration="120" />
24. <item android:drawable="@drawable/frame10" android:duration="120" />
25. <item android:drawable="@drawable/frame9" android:duration="120" />
26. <item android:drawable="@drawable/frame8" android:duration="120" />
27. <item android:drawable="@drawable/frame7" android:duration="120" />
28. <item android:drawable="@drawable/frame6" android:duration="120" />
29. <item android:drawable="@drawable/frame5" android:duration="120" />
30. <item android:drawable="@drawable/frame4" android:duration="120" />
31. <item android:drawable="@drawable/frame3" android:duration="120" />
32. <item android:drawable="@drawable/frame2" android:duration="120" />
33. <item android:drawable="@drawable/frame1" android:duration="120" />
34. <item android:drawable="@drawable/frame0" android:duration="120" />
35.
36. </animation-list>

download this android example

Email:[email protected]
297 | P a g e APS Microtech Pvt Ltd

Output:

Email:[email protected]
298 | P a g e APS Microtech Pvt Ltd

Email:[email protected]
299 | P a g e APS Microtech Pvt Ltd

Email:[email protected]
300 | P a g e APS Microtech Pvt Ltd

Android Web Service Tutorial


Creating web service application in android is not a difficult task. We can easily create a restful
web service application in android to authenticate or save information into the external database
such as oracle, mysql, postgre sql, sql server using other application developed in java, .net, php
etc languages. That is what we are going to do.

Android Restful Web Service Tutorial


Before developing web services application, you must have basic knowledge of SOAP and
Restful web services. That is why, we are going to discuss basic points about web services such
as what is web service and brief information about SOAP and Restful web services.

What is Web Service?


A web service is a standard for exchanging information between different types of applications
irrespective of language and platform. For example, an android application can interact with java
or .net application using web services.

Android Restful Web Service Example


File: activity_main.xml

1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".MainActivity" >
10.
11. <EditText
12. android:id="@+id/editText1"
13. android:layout_width="wrap_content"
14. android:layout_height="wrap_content"
15. android:layout_alignParentTop="true"
16. android:layout_centerHorizontal="true"
17. android:hint="Username"
18. android:ems="10" >
19.
20. <requestFocus />
21. </EditText>

Email:[email protected]
301 | P a g e APS Microtech Pvt Ltd

22.
23. <EditText
24. android:id="@+id/editText2"
25. android:layout_width="wrap_content"
26. android:layout_height="wrap_content"
27. android:layout_alignLeft="@+id/editText1"
28. android:layout_below="@+id/editText1"
29. android:layout_marginTop="67dp"
30. android:ems="10"
31. android:hint="Password"
32. android:inputType="textPassword" />
33.
34. <Button
35. android:id="@+id/button2"
36. android:layout_width="wrap_content"
37. android:layout_height="wrap_content"
38. android:layout_alignParentBottom="true"
39. android:layout_marginBottom="24dp"
40. android:layout_toRightOf="@+id/button1"
41. android:text="New User" />
42.
43. <ProgressBar
44. android:id="@+id/progressBar1"
45. style="?android:attr/progressBarStyleLarge"
46. android:layout_width="wrap_content"
47. android:layout_height="wrap_content"
48. android:layout_alignLeft="@+id/button1"
49. android:layout_below="@+id/editText2"
50. android:layout_marginTop="22dp" />
51.
52. <Button
53. android:id="@+id/button1"
54. android:layout_width="wrap_content"
55. android:layout_height="wrap_content"
56. android:layout_alignLeft="@+id/editText2"
57. android:layout_below="@+id/progressBar1"
58. android:layout_marginLeft="22dp"
59. android:text="Login" />
60.
61. </RelativeLayout>

File: activity_register_user.xml

1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
2. android:layout_width="fill_parent"
3. android:layout_height="fill_parent" >
4.
5. <EditText

Email:[email protected]
302 | P a g e APS Microtech Pvt Ltd

6. android:id="@+id/editText1"
7. android:layout_width="wrap_content"
8. android:layout_height="wrap_content"
9. android:layout_alignParentTop="true"
10. android:layout_centerHorizontal="true"
11. android:layout_marginTop="15dp"
12. android:ems="10"
13. android:hint="Enter UserName" />
14.
15. <EditText
16. android:id="@+id/editText2"
17. android:layout_width="wrap_content"
18. android:layout_height="wrap_content"
19. android:layout_alignLeft="@+id/editText1"
20. android:layout_below="@+id/editText1"
21. android:layout_marginTop="50dp"
22. android:ems="10"
23. android:hint="Enter Password"
24. android:inputType="textPassword" />
25.
26. <Button
27. android:id="@+id/button1"
28. android:layout_width="wrap_content"
29. android:layout_height="wrap_content"
30. android:layout_alignParentBottom="true"
31. android:layout_centerHorizontal="true"
32. android:text="Resister" />
33.
34. <ProgressBar
35. android:id="@+id/progressBar1"
36. style="?android:attr/progressBarStyleLarge"
37. android:layout_width="wrap_content"
38. android:layout_height="wrap_content"
39. android:layout_alignLeft="@+id/button1"
40. android:layout_below="@+id/editText2"
41. android:layout_marginTop="87dp" />
42.
43. </RelativeLayout>

MainActivity class
File: MainActivity.java

1. package com.example.newrestapi;
2.
3. import java.io.BufferedReader;
4. import java.io.InputStream;

Email:[email protected]
303 | P a g e APS Microtech Pvt Ltd

5. import java.io.InputStreamReader;
6. import java.util.ArrayList;
7. import java.util.List;
8. import org.apache.http.HttpEntity;
9. import org.apache.http.HttpResponse;
10. import org.apache.http.NameValuePair;
11. import org.apache.http.client.HttpClient;
12. import org.apache.http.client.entity.UrlEncodedFormEntity;
13. import org.apache.http.client.methods.HttpPost;
14. import org.apache.http.impl.client.DefaultHttpClient;
15. import org.apache.http.message.BasicNameValuePair;
16. import android.os.AsyncTask;
17. import android.os.Bundle;
18. import android.app.Activity;
19. import android.content.Intent;
20. import android.view.View;
21. import android.view.View.OnClickListener;
22. import android.widget.Button;
23. import android.widget.EditText;
24. import android.widget.ProgressBar;
25. import android.widget.Toast;
26.
27. public class MainActivity extends Activity {
28. EditText password,userName;
29. Button login,resister;
30. ProgressBar progressBar;
31.
32.
33.
34. protected void onCreate(Bundle savedInstanceState) {
35. super.onCreate(savedInstanceState);
36. setContentView(R.layout.activity_main);
37. password=(EditText) findViewById(R.id.editText2);
38. userName=(EditText) findViewById(R.id.editText1);
39. login=(Button) findViewById(R.id.button1);
40. resister=(Button) findViewById(R.id.button2);
41.
42. //progess_msz.setVisibility(View.GONE);
43. progressBar=(ProgressBar) findViewById(R.id.progressBar1);
44. progressBar.setVisibility(View.GONE);
45.
46.
47. resister.setOnClickListener(new OnClickListener() {
48.
49. @Override
50. public void onClick(View arg0) {
51. // TODO Auto-generated method stub
52. Intent intent=new Intent(MainActivity.this,ResisterUser.class);

Email:[email protected]
304 | P a g e APS Microtech Pvt Ltd

53. startActivity(intent);
54. }
55. });
56. login.setOnClickListener(new OnClickListener() {
57.
58. public void onClick(View v) {
59. progressBar.setVisibility(View.VISIBLE);
60.
61. String s1=userName.getText().toString();
62. String s2=password.getText().toString();
63. new ExecuteTask().execute(s1,s2);
64.
65. }
66. });
67.
68.
69. }
70.
71. class ExecuteTask extends AsyncTask<String, Integer, String>
72. {
73.
74. @Override
75. protected String doInBackground(String... params) {
76.
77. String res=PostData(params);
78.
79. return res;
80. }
81.
82. @Override
83. protected void onPostExecute(String result) {
84. progressBar.setVisibility(View.GONE);
85. //progess_msz.setVisibility(View.GONE);
86. Toast.makeText(getApplicationContext(), result, 3000).show();
87. }
88.
89. }
90.
91. public String PostData(String[] valuse) {
92. String s="";
93. try
94. {
95. HttpClient httpClient=new DefaultHttpClient();
96. HttpPost httpPost=new HttpPost("http://10.0.0.8:7777/HttpPostServlet/servlet/Login");
97.
98. List<NameValuePair> list=new ArrayList<NameValuePair>();
99. list.add(new BasicNameValuePair("name", valuse[0]));
100. list.add(new BasicNameValuePair("pass",valuse[1]));

Email:[email protected]
305 | P a g e APS Microtech Pvt Ltd

101. httpPost.setEntity(new UrlEncodedFormEntity(list));


102. HttpResponse httpResponse= httpClient.execute(httpPost);
103.
104. HttpEntity httpEntity=httpResponse.getEntity();
105. s= readResponse(httpResponse);
106.
107. }
108. catch(Exception exception) {}
109. return s;
110.
111.
112. }
113. public String readResponse(HttpResponse res) {
114. InputStream is=null;
115. String return_text="";
116. try {
117. is=res.getEntity().getContent();
118. BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(is
));
119. String line="";
120. StringBuffer sb=new StringBuffer();
121. while ((line=bufferedReader.readLine())!=null)
122. {
123. sb.append(line);
124. }
125. return_text=sb.toString();
126. } catch (Exception e)
127. {
128.
129. }
130. return return_text;
131.
132. }
133.
134. }

RegisterUser class
File: RegisterUser.java

1. package com.example.newrestapi;
2.
3. import java.util.ArrayList;
4. import java.util.List;
5. import org.apache.http.NameValuePair;
6. import org.apache.http.client.HttpClient;
7. import org.apache.http.client.entity.UrlEncodedFormEntity;

Email:[email protected]
306 | P a g e APS Microtech Pvt Ltd

8. import org.apache.http.client.methods.HttpPost;
9. import org.apache.http.impl.client.DefaultHttpClient;
10. import org.apache.http.message.BasicNameValuePair;
11. import android.os.AsyncTask;
12. import android.os.Bundle;
13. import android.app.Activity;
14. import android.view.View;
15. import android.view.View.OnClickListener;
16. import android.widget.Button;
17. import android.widget.EditText;
18. import android.widget.ProgressBar;
19.
20. public class ResisterUser extends Activity {
21. EditText userName,passwprd;
22. Button resister,login;
23. ProgressBar progressBar;
24. protected void onCreate(Bundle savedInstanceState) {
25. super.onCreate(savedInstanceState);
26. setContentView(R.layout.activity_resister_user);
27. userName=(EditText) findViewById(R.id.editText1);;
28. passwprd=(EditText) findViewById(R.id.editText2);
29. resister=(Button) findViewById(R.id.button1);
30.
31. progressBar=(ProgressBar) findViewById(R.id.progressBar1);
32. progressBar.setVisibility(View.GONE);
33.
34. resister.setOnClickListener(new OnClickListener() {
35.
36. @Override
37. public void onClick(View v) {
38.
39. progressBar.setVisibility(View.VISIBLE);
40.
41. String s1=userName.getText().toString();
42. String s2=passwprd.getText().toString();
43. new ExecuteTask().execute(s1,s2);
44. }
45. });
46.
47.
48.
49.
50. }
51.
52. class ExecuteTask extends AsyncTask<String, Integer, String>
53. {
54.
55. @Override

Email:[email protected]
307 | P a g e APS Microtech Pvt Ltd

56. protected String doInBackground(String... params) {


57.
58. PostData(params);
59. return null;
60. }
61.
62. @Override
63. protected void onPostExecute(String result) {
64. progressBar.setVisibility(View.GONE);
65. }
66.
67. }
68.
69.
70.
71. public void PostData(String[] valuse) {
72. try
73. {
74. HttpClient httpClient=new DefaultHttpClient();
75. HttpPost httpPost=new HttpPost(
76. "http://10.0.0.8:7777/HttpPostServlet/servlet/httpPostServlet");
77. List<NameValuePair> list=new ArrayList<NameValuePair>();
78. list.add(new BasicNameValuePair("name", valuse[0]));
79. list.add(new BasicNameValuePair("pass",valuse[1]));
80. httpPost.setEntity(new UrlEncodedFormEntity(list));
81. httpClient.execute(httpPost);
82. }
83. catch(Exception e)
84. {
85. System.out.println(e);
86. }
87.
88. }
89.
90. }

File: AndroidManifest.xml

You need to provide INTERNET permission in AndroidManifest.xml file.

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


2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3. package="com.example.newrestapi"
4. android:versionCode="1"
5. android:versionName="1.0" >
6.

Email:[email protected]
308 | P a g e APS Microtech Pvt Ltd

7. <uses-sdk
8. android:minSdkVersion="8"
9. android:targetSdkVersion="17" />
10.
11. <uses-permission android:name="android.permission.INTERNET" />
12.
13. <application
14. android:allowBackup="true"
15. android:icon="@drawable/ic_launcher"
16. android:label="@string/app_name"
17. android:theme="@style/AppTheme" >
18. <activity
19. android:name="com.example.newrestapi.MainActivity"
20. android:label="@string/app_name" >
21. <intent-filter>
22. <action android:name="android.intent.action.MAIN" />
23.
24. <category android:name="android.intent.category.LAUNCHER" />
25. </intent-filter>
26. </activity>
27. <activity
28. android:name="com.example.newrestapi.ResisterUser"
29. android:label="@string/title_activity_resister_user" >
30. </activity>
31. </application>
32.
33. </manifest>

download this android example

Email:[email protected]
309 | P a g e APS Microtech Pvt Ltd

Output:

Email:[email protected]
310 | P a g e APS Microtech Pvt Ltd

Email:[email protected]
311 | P a g e APS Microtech Pvt Ltd

Email:[email protected]
312 | P a g e APS Microtech Pvt Ltd

Java Servlet Login and Register example using oracle


database
Create table javatpoint_user in the oracle database having three columns id, name and password.
Id must be primary key and generated through SEQUENCE.

1. CREATE TABLE "JAVATPOINT_USER"


2. ( "ID" NUMBER,
3. "NAME" VARCHAR2(4000),
4. "PASSWORD" VARCHAR2(4000),
5. CONSTRAINT "JAVATPOINT_USER_PK" PRIMARY KEY ("ID") ENABLE
6. )
7. /

New create two servlet classes to login and register user.

Login Servlet class


File: Login.java

1. package server;
2.
3. import java.io.IOException;
4. import java.io.ObjectOutputStream;
5. import java.sql.Connection;
6. import java.sql.DriverManager;
7. import java.sql.PreparedStatement;
8. import java.sql.ResultSet;
9. import javax.servlet.ServletException;
10. import javax.servlet.http.HttpServlet;
11. import javax.servlet.http.HttpServletRequest;
12. import javax.servlet.http.HttpServletResponse;
13.
14. public class Login extends HttpServlet {
15.
16.
17. public void doGet(HttpServletRequest request, HttpServletResponse response)
18. throws ServletException, IOException {
19. response.setContentType("text/html");
20.
21. ObjectOutputStream out=new ObjectOutputStream(response.getOutputStream());
22.
23. String n=request.getParameter("name");
24. String p=request.getParameter("pass");
25. System.out.println(n);
26. System.out.println(p);
27.

Email:[email protected]
313 | P a g e APS Microtech Pvt Ltd

28. if(validate(n, p)){


29. out.writeObject("success");
30.
31. }
32. else{
33. out.writeObject("Sorry username or password error");
34.
35. }
36.
37. out.close();
38. }
39.
40.
41. public static boolean validate(String name,String pass){
42. boolean status=false;
43. try{
44. Class.forName("oracle.jdbc.driver.OracleDriver");
45. Connection con=DriverManager.getConnection(
46. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
47.
48. PreparedStatement ps=con.prepareStatement(
49. "select * from javatpoint_user where name=? and password=?");
50. ps.setString(1,name);
51. ps.setString(2,pass);
52.
53. ResultSet rs=ps.executeQuery();
54. status=rs.next();
55.
56. }catch(Exception e){System.out.println(e);}
57. return status;
58. }
59. public void doPost(HttpServletRequest request,HttpServletResponse response)
60. throws ServletException, IOException {
61. doGet(request, response);
62.
63. }
64. }

httpPostServlet Servlet class


File: httpPostServlet.java

1. package server;
2.
3. import java.io.IOException;
4. import java.sql.Connection;
5. import java.sql.DriverManager;
6. import java.sql.PreparedStatement;

Email:[email protected]
314 | P a g e APS Microtech Pvt Ltd

7. import javax.servlet.ServletException;
8. import javax.servlet.http.HttpServlet;
9. import javax.servlet.http.HttpServletRequest;
10. import javax.servlet.http.HttpServletResponse;
11.
12.
13. public class httpPostServlet extends HttpServlet {
14.
15.
16. public void doGet(HttpServletRequest request,HttpServletResponse response)
17. throws ServletException, IOException {
18. response.setContentType("text/html");
19. String recived_data="";
20.
21.
22. String s1=request.getParameter("name");
23. String s2=request.getParameter("pass");
24. System.out.println(s1);
25. System.out.println(s2);
26.
27. try
28. {
29. Class.forName("oracle.jdbc.driver.OracleDriver");
30. Connection con=DriverManager.getConnection(
31. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
32. PreparedStatement ps=con.prepareStatement(
33. "insert into javatpoint_user(name,password) values(?,?)");
34. ps.setString(1, s1);
35. ps.setString(2,s2);
36. ps.executeUpdate();
37. con.close();
38. }
39. catch (Exception e) {
40. e.printStackTrace();
41. }
42.
43. }
44. public void doPost(HttpServletRequest request,HttpServletResponse response)
45. throws ServletException, IOException {
46. doGet(request, response);
47. }
48.
49. }

index.jsp

1. <form action="servlet/Login">
2. Name:<input type="text" name="name"/><br/>

Email:[email protected]
315 | P a g e APS Microtech Pvt Ltd

3. Password:<input type="password" name="pass"/><br/>


4. <input type="submit" value="login"/>
5. </form>

Android Interview Questions

Email:[email protected]
316 | P a g e APS Microtech Pvt Ltd

Android programming is growing day by day. The questions asked by interviewers in android is
given below. A list of top android interview questions and answers are given below.

1) What is Android?

Android is an open-source, linux-based operating system that is used in mobiles, tablets,


televisions etc.

2) Who is the founder of Android?

Andy Rubin.

3) What are the code names of android?

1. Aestro
2. Blender
3. Cupcake
4. Donut
5. Eclair
6. Froyo
7. Gingerbread
8. Honycomb
9. Ice Cream Sandwitch
10. Jelly Bean
11. Kitkat
12. Lollipop
13. Marshmallow

More details...

4) What are the advantages of android?

Open-source: It means no licence, distribution and development fee.

Platform-independent: It supports windows, mac and linux platforms.

Supports various technologies: It supports camera, bluetooth, wifi, speech, EDGE etc.
technologies.

Email:[email protected]
317 | P a g e APS Microtech Pvt Ltd

Highly optimized Virtual Machine: Android uses highly optimized virtual machine for mobile
devices, called DVM (Dalvik Virtual Machine).

5) Does android support other language than java?

Yes, android app can be developed in C/C++ also using android NDK (Native Development
Kit). It makes the performance faster. It should be used with android SDK.

6) What are the core building blocks of android?

The core building blocks of android are:

 Activity
 View
 Intent
 Service
 Content Provider
 Fragment etc.

More details...

7) What is activity?

Activity is like a frame or window in java that represents GUI. It represents one screen of
android.

8) What are the life cycle methods of android activity?

There are 7 life-cycle methods of activity. They are as follows:

1. onCreate()
2. onStart()
3. onResume()
4. onPause()
5. onStop()
6. onRestart()
7. onDestroy()

More details...

Email:[email protected]
318 | P a g e APS Microtech Pvt Ltd

9) What is intent?

It is a kind of message or information that is passed to the components. It is used to launch an


activity, display a web page, send sms, send email etc. There are two types of intents in android:

1. Implicit Intent
2. Explicit Intent

10) What is implicit intent in android?

Implicit intent is used to invoke the system components.

11) What is explicit intent in android?

Explicit intent is used to invoke the activity class.

12) How to call another activity in android?

1. Intent i = new Intent(getApplicationContext(), ActivityTwo.class);


2. startActivity(i);

13) What is service in android?

A service is a component that runs in the background. It is used to play music, handle network
transaction etc.

More details...

14) What is the name of database used in android?

SQLite: An opensource and lightweight relational database for mobile devices.

More details...

Email:[email protected]
319 | P a g e APS Microtech Pvt Ltd

15) What is AAPT?

AAPT is an acronym for android asset packaging tool. It handles the packaging process.

16) What is content provider?

Content providers are used to share information between android applications.

17) What is fragment?

Fragment is a part of Activity. By the help of fragments, we can display multiple screens on one
activity.

18) What is ADB?

ADB stands for Android Debug Bridge. It is a command line tool that is used to communicate
with the emulator instance.

19) What is NDK?

NDK stands for Native Development Kit. By using NDK, you can develop a part of app using
native language such as C/C++ to boost the performance.

20) What is ANR?

ANR stands for Application Not Responding. It is a dialog box that appears if the application is
no longer responding.

21) What is DDMS?

DDMS stands for Dalvik Debug Monitor Server. It gives the wide array of debugging features:

1. Port forwarding services


2. Screen capture
3. Thread and heap information

Email:[email protected]
320 | P a g e APS Microtech Pvt Ltd

4. Network traffic tracking


5. Location data spoofing

22) Define Android Architecture?

Android architecture consists of 4 components:

1. Linux Kernal
2. Libraries
3. Android Framework
4. Android Applications

More details...

23) What is a portable wi-fi hotspot?

The portable wi-fi hotspot is used to share internet connection to other wireless devices.

24) Name the dialog box which are supported by android?

 Alert Dialog
 Progress Dialog
 Date Picker Dialog
 Time picker Dialog

25) Name some exceptions in android?

 Inflate Exception
 Surface.OutOfResourceException
 SurfaceHolder.BadSurfaceTypeException
 WindowManager.BadTokenException

26) What are the basic tools used to develop an android app?

 JDK
 Eclipse+ADT plugin
 SDK Tools

Email:[email protected]
321 | P a g e APS Microtech Pvt Ltd

Email:[email protected]

You might also like