You are on page 1of 218

Android Tutorial

Android is a complete set of software for mobile devices such as tablet computers,
notebooks, smartphones, electronic book readers, set-top boxes etc.
It contains a linux-based Operating System, middleware and key mobile
applications.
It can be thought of as a mobile operating system. But it is not limited to mobile only.
It is currently used in various devices such as mobiles, tablets, televisions etc.

This tutorial is developed for beginners and experienced persons. Let's see the topics
of android that we are going to learn.

Basics of Android
In this fundamental chapter, you will learn about android, its components, how to
create first android application, internal of first android application etc.

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.

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 commited to advance
open standards, provide services and deploy handsets using the Android Plateform.

Features of Android

There are many advantages of android. They are as follows:


 It is open-source.
 Anyone can customize the Android Platform.
 There are a lot of mobile applications that can be choosen by the consumer.
 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.

History of Android
The history and versions of android are interesting to know. The codenames of
android ranges from A to J currently, such as Aestro, Blender, Cupcake, Donut,
Eclair, Froyo, Gingerbread, Honeycomb, Ice Cream Sandwitch,Jelly Bean and
KitKat. Let's understand the android history pointly:
 Initially, Andy Rubin founded Android Incorporation in Palo Alto,
California, United States in October, 2003.
 In 17th August 2005, Google acquired android Incorporation. Since then, it is
in the subsidiary of Google Incorporation.
 The key employees of Android Incorporation are Andy Rubin, Rich Miner,
Chris White and Nick Sears.

Android Versions, Codename and API


Let's see the android versions codename and API provided by Google.
Version Codename API
1.5 Cupcake 3
1.6 Donut 4
2.1 Eclair 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
4.1, 4.2 and 4.3 Jelly Bean 16, 17 and 18
4.4 KitKat 19

Android Versions Image

Android Software Stack


Android software stack (also known as android architecture) includes linux kernal,
native libraries (middleware), Android Runtime, Application Framework and
Applications.

Linux Kernal is responsible for device drivers, power management, resource access
etc. OS tasks.
On the top of linux kernal, 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.
The main Android API's are UI (User Interface), telephony, resources, locations,
Content Providers (data) and package managers.

Android Core Building Blocks


A 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

Intent intent=new Intent(Intent.ACTION_VIEW);


intent.setData(Uri.parse("http://www.javatpoint.com"));
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 acvities, 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.

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.
Installing softwares for 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.

Simple way by ADT Bundle

It is the simplest technique to install required softwares for android application. It


includes:
 Eclipse IDE
 Android SDK
 Eclipse Plugin

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.
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 ADT plugin for Eclipse IDE. Let's see the softwares 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

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

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

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

After the installing ADT plugin, now tell the eclipse IDE for your android SDK
location. For this:
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

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

Example of Hello Android

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
3. Fill the Details in this diaglog box and click finish
Now an android project have been created. You can explore the android project and see the
simple program, it looks like:

2) Write the message

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

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

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:
Internal Details of Hello Android
Example
Here, we are going to learn the details of first android program.
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

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

(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/andr
oid"  
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:layout_width="wrap_content"  
9.         android:layout_height="wrap_content"  
10.         android:layout_centerHorizontal="true"  
11.         android:layout_centerVertical="true"  
12.         android:text="@string/hello_world" />  
13.   
14. </RelativeLayout>  

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.   
4.     <string name="app_name">helloandroid</string>  
5.     <string name="hello_world">Hello world!</string>  
6.     <string name="menu_settings">Settings</string>  
7.   
8. </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.   
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 
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. }  

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.
For more information about manifest file visit here: Android Manifest.xml file.

Dalvik Virtual Machine


As we know the modern JVM is high performance and provides excellent memory
management. But it need to be optimized for low-powered handheld devices.
The Dalvik Virtual Machine (DVM) is optimized for mobile devices. It optimizes the
JVM 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 files that run on the Dalvik
VM.
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.

AndroidManifest.xml file in android


The AndroidManifest.xml file contains information about 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 instumentation 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.

<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.

Android R.java file


It is an auto-generated file by aapt (Android Asset Packaging Tool) that contains
resouce 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 
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. }  

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_FULLS
CREEN,  
8.                 WindowManager.LayoutParams.FLAG_FULLSCREEN);//int flag, i
nt 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/andr
oid"  
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.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_FUL
LSCREEN, 
18.                   WindowManager.LayoutParams.FLAG_FULLSCREEN);//int flag, 
int mask 
19.       */  
20.         setContentView(R.layout.activity_main);  
21.           
22.     }  
23.   
24.   
25. }  

Android Screen Orientation Example


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:

1. <activity  
2.             android:name="com.example.screenorientation.MainActivity"  
3.             android:label="@string/app_name"   
4.             android:screenOrientation="landscape"  
5.             >  

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

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/andr
oid"  
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_marginLeft="66dp"  
16.         android:layout_marginTop="73dp"  
17.         android:text="Button"  
18.         android:onClick="onClick"  
19.          />  
20.   
21.     <EditText  
22.         android:id="@+id/editText1"  
23.         android:layout_width="wrap_content"  
24.         android:layout_height="wrap_content"  
25.         android:layout_centerHorizontal="true"  
26.         android:ems="10" />  
27.   
28. </RelativeLayout>  
Activity class

File: MainActivity.java

1. package com.example.f;  
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.EditText;  
10.   
11. public class MainActivity extends Activity{  
12.     EditText editText1;  
13.     Button button1;  
14.     @Override  
15.     protected void onCreate(Bundle savedInstanceState) {  
16.         super.onCreate(savedInstanceState);  
17.         setContentView(R.layout.activity_main);  
18.           
19.         editText1=(EditText)findViewById(R.id.editText1);  
20.         button1=(Button)findViewById(R.id.button1);  
21.     }  
22.     public void onClick(View v) {  
23.         editText1.setText("O android");  
24.     }  
25. }  

AndroidManifest.xml

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.screenorientation"  
4.     android:versionCode="1"  
5.     android:versionName="1.0" >  
6.   
7.     <uses-sdk  
8.         android:minSdkVersion="8"  
9.         android:targetSdkVersion="16" />  
10.   
11.     <application  
12.         android:allowBackup="true"  
13.         android:icon="@drawable/ic_launcher"  
14.         android:label="@string/app_name"  
15.         android:theme="@style/AppTheme" >  
16.         <activity  
17.             android:name="com.example.screenorientation.MainActivity"  
18.             android:label="@string/app_name"   
19.             android:screenOrientation="landscape"  
20.             >  
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 UI Widgets
There are given a lot of UI widgets with simplified examples such as Button,
EditText, AutoCompleteTextView, ToggleButton, DatePicker, TimePicker,
ProgressBar etc.
Working with 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.
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.

Android Working with Button


Here, we are going to create two textfields and one button for sum of two numbers. If
user clicks one the 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.
The generated code for the ui components will be like this:
File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/andr
oid"  
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_alignParentTop="true"  
12.         android:layout_centerHorizontal="true"  
13.         android:layout_marginTop="24dp"  
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"  
22.         android:layout_marginTop="34dp"  
23.         android:ems="10" >  
24.   
25.         <requestFocus />  
26.     </EditText>  
27.   
28.     <Button  
29.         android:id="@+id/button1"  
30.         android:layout_width="wrap_content"  
31.         android:layout_height="wrap_content"  
32.         android:layout_centerHorizontal="true"  
33.         android:layout_centerVertical="true"  
34.         android:text="@string/Button" />  
35.   
36. </RelativeLayout>  

Activity class

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


File: MainActivity.java

1. package com.example.sumof2numbers;  
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.EditText;  
10. import android.widget.Toast;  
11.   
12. public class MainActivity extends Activity {  
13.     private EditText edittext1,edittext2;  
14.     private Button buttonSum;  
15.     @Override  
16.     protected void onCreate(Bundle savedInstanceState) {  
17.         super.onCreate(savedInstanceState);  
18.         setContentView(R.layout.activity_main);  
19.           
20.         addListenerOnButton();  
21.           
22.     }  
23.     public void addListenerOnButton(){  
24.         edittext1=(EditText)findViewById(R.id.editText1);  
25.         edittext2=(EditText)findViewById(R.id.editText2);  
26.         buttonSum=(Button)findViewById(R.id.button1);  
27.           
28.         buttonSum.setOnClickListener(new OnClickListener(){  
29.   
30.             @Override  
31.             public void onClick(View view) {  
32.                 String value1=edittext1.getText().toString();  
33.                 String value2=edittext2.getText().toString();  
34.                 int a=Integer.parseInt(value1);  
35.                 int b=Integer.parseInt(value2);  
36.                 int sum=a+b;  
37.     Toast.makeText(getApplicationContext(),String.valueOf(sum),Toast.LENG
TH_LONG).show();  
38.             }  
39.               
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.activity_main, menu);  
47.         return true;  
48.     }  
49.   
50. }  

download this example


It is developed by adt bundle on android 4.2 using minimum sdk 8 and target sdk
16.

Output:
Android Toast Example
Toast can be used to display information for the short period of time. You can also
create custom toast such as toast displaying image etc.

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

 public static final int LENGTH_LONG


 public static final int LENGTH_SHORT

Methods of Toast class

 public static Toast makeText(Context context, CharSequence text, int


duration)
 public void show ()
 public void setMargin (float horizontalMargin, float verticalMargin)

Simple example to diaplay the toast

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

Another code:

1. Toast toast=Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toas
t.LENGTH_SHORT);  
2. toast.setMargin(50,50);  
3. toast.show();  

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

Full code of Activity class

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;  
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 Javatpoint",Toast.LE
NGTH_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:
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

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/andr
oid"  
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:layout_width="wrap_content"  
9.         android:layout_height="wrap_content"  
10.         android:layout_centerHorizontal="true"  
11.         android:layout_centerVertical="true"  
12.         android:text="@string/hello_world" />  
13.   
14. </RelativeLayout>  

customtoast.xml

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

1. <?xml version="1.0" encoding="utf-8"?>  
2. <LinearLayout xmlns:androclass="http://schemas.android.com/apk/res/androi
d"  
3.       android:id="@+id/custom_toast_layout"  
4.     android:layout_width="match_parent"  
5.     android:layout_height="match_parent"  
6.     android:orientation="vertical"  
7.     android:background="#F14E23"  
8.      >  
9.        
10.     <ImageView  
11.         android:id="@+id/custom_toast_image"  
12.         android:layout_width="wrap_content"  
13.         android:layout_height="wrap_content"  
14.         android:contentDescription="@string/hello_world"  
15.         android:src="@drawable/ic_launcher"/>  
16.       
17. <TextView  
18.         android:id="@+id/custom_toast_message"  
19.         android:layout_width="wrap_content"  
20.         android:layout_height="wrap_content"  
21.         android:contentDescription="@string/Toast"  
22.         android:text="@string/Toast" />  
23. </LinearLayout>  

Activity class

Now write the code to display the custom toast.


File: MainActivity.java

1. package com.example.customtoast2;  
2. import android.os.Bundle;  
3. import android.app.Activity;  
4. import android.view.Gravity;  
5. import android.view.LayoutInflater;  
6. import android.view.Menu;  
7. import android.view.View;  
8. import android.view.ViewGroup;  
9. import android.widget.Toast;  
10.   
11. public class MainActivity extends Activity {  
12.      @Override  
13.         public void onCreate(Bundle savedInstanceState) {  
14.             super.onCreate(savedInstanceState);  
15.             setContentView(R.layout.activity_main);  
16.               
17.         //Creating the LayoutInflater instance  
18.             LayoutInflater li = getLayoutInflater();  
19.         //Getting the View object as defined in the customtoast.xml file  
20.             View layout = li.inflate(R.layout.customtoast,  
21.               (ViewGroup) findViewById(R.id.custom_toast_layout));  
22.            
23.         //Creating the Toast object   
24.             Toast toast = new Toast(getApplicationContext());  
25.             toast.setDuration(Toast.LENGTH_SHORT);  
26.             toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);  
27.             toast.setView(layout);//setting the view of custom toast layout  
28.             toast.show();  
29.         }  
30.         @Override  
31.         public boolean onCreateOptionsMenu(Menu menu) {  
32.             getMenuInflater().inflate(R.menu.activity_main, menu);  
33.             return true;  
34.         }  
35.   
36. }  

Output:

Android Toggle Button Example


Toggle Button can be used to display checked/unchecked (On/Off) state on the
button. It can be used to On/Off Sound, Wifi, Bluetooth etc.

ToggleButton class
ToggleButton class provides the facility of creating the toggle button.

Constants of ToggleButton class

 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.

Methods of ToggleButton class

 CharSequence getTextOff() Returns the text when the button is not in the
checked state.
 CharSequence getTextOn() Returns the text for when the button is in the
checked state.
 void setChecked(boolean checked) Changes the checked state of this button.

Example of ToggleButton

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

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/andr
oid"  
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.     <ToggleButton  
8.         android:id="@+id/toggleButton1"  
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="60dp"  
14.         android:layout_marginTop="18dp"  
15.         android:text="ToggleButton1"  
16.         android:textOff="Off"  
17.         android:textOn="On" />  
18.   
19.     <ToggleButton  
20.         android:id="@+id/toggleButton2"  
21.         android:layout_width="wrap_content"  
22.         android:layout_height="wrap_content"  
23.         android:layout_alignBaseline="@+id/toggleButton1"  
24.         android:layout_alignBottom="@+id/toggleButton1"  
25.         android:layout_marginLeft="44dp"  
26.         android:layout_toRightOf="@+id/toggleButton1"  
27.         android:text="ToggleButton2"  
28.         android:textOff="Off"  
29.         android:textOn="On" />  
30.   
31.     <Button  
32.         android:id="@+id/button1"  
33.         android:layout_width="wrap_content"  
34.         android:layout_height="wrap_content"  
35.         android:layout_below="@+id/toggleButton2"  
36.         android:layout_marginTop="82dp"  
37.         android:layout_toRightOf="@+id/toggleButton1"  
38.         android:text="submit" />  
39.   
40. </RelativeLayout>  

Activity class

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


File: MainActivity.java

1. package com.example.togglebutton;  
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.Toast;  
10. import android.widget.ToggleButton;  
11.   
12. public class MainActivity extends Activity {  
13.     private ToggleButton toggleButton1, toggleButton2;  
14.     private Button buttonSubmit;  
15.     @Override  
16.     protected void onCreate(Bundle savedInstanceState) {  
17.         super.onCreate(savedInstanceState);  
18.         setContentView(R.layout.activity_main);  
19.           
20.         addListenerOnButtonClick();  
21.     }  
22.     public void addListenerOnButtonClick(){  
23.         //Getting the ToggleButton and Button instance from the layout xml file  
24.         toggleButton1=(ToggleButton)findViewById(R.id.toggleButton1);  
25.         toggleButton2=(ToggleButton)findViewById(R.id.toggleButton2);  
26.         buttonSubmit=(Button)findViewById(R.id.button1);  
27.   
28.         //Performing action on button click  
29.         buttonSubmit.setOnClickListener(new OnClickListener(){  
30.   
31.             @Override  
32.             public void onClick(View view) {  
33.                 StringBuilder result = new StringBuilder();  
34.                    result.append("ToggleButton1 : ").append(toggleButton1.getText()
);  
35.                    result.append("\nToggleButton2 : ").append(toggleButton2.getTex
t());  
36.                 //Displaying the message in toast  
37.                 Toast.makeText(getApplicationContext(), result.toString(),Toast.LE
NGTH_LONG).show();  
38.             }  
39.               
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.activity_main, menu);  
47.         return true;  
48.     }  
49.   
50. }  

download this example

Output:

Android CheckBox Example


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.
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, Button etc. classes in the
CheckBox class. Some of them are as follows:
 public boolean isChecked() Returns true if it is checked otherwise false.
 public void setChecked(boolean staus) changes the state of the
CheckBox.???

Example of Android CheckBox

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

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.     <CheckBox  
8.         android:id="@+id/checkBox1"  
9.         android:layout_width="wrap_content"  
10.         android:layout_height="wrap_content"  
11.         android:layout_alignParentLeft="true"  
12.         android:layout_alignParentTop="true"  
13.         android:text="Pizza" />  
14.   
15.     <CheckBox  
16.         android:id="@+id/checkBox2"  
17.         android:layout_width="wrap_content"  
18.         android:layout_height="wrap_content"  
19.         android:layout_alignParentTop="true"  
20.         android:layout_toRightOf="@+id/checkBox1"  
21.         android:text="Coffe" />  
22.   
23.     <CheckBox  
24.         android:id="@+id/checkBox3"  
25.         android:layout_width="wrap_content"  
26.         android:layout_height="wrap_content"  
27.         android:layout_alignParentTop="true"  
28.         android:layout_toRightOf="@+id/checkBox2"  
29.         android:text="Burger" />  
30.   
31.     <Button  
32.         android:id="@+id/button1"  
33.         android:layout_width="wrap_content"  
34.         android:layout_height="wrap_content"  
35.         android:layout_below="@+id/checkBox2"  
36.         android:layout_marginTop="32dp"  
37.         android:layout_toLeftOf="@+id/checkBox3"  
38.         android:text="Order" />  
39.   
40. </RelativeLayout>  

Activity class

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


File: MainActivity.java

1. package com.example.checkbox;  
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.*;  
9.   
10. public class MainActivity extends Activity {  
11.     CheckBox pizza,coffe,burger;  
12.     Button buttonOrder;  
13.     @Override  
14.     protected void onCreate(Bundle savedInstanceState) {  
15.         super.onCreate(savedInstanceState);  
16.         setContentView(R.layout.activity_main);  
17.         addListenerOnButtonClick();  
18.     }  
19. public void addListenerOnButtonClick(){  
20.     //Getting instance of CheckBoxes and Button from the activty_main.xml fil
e  
21.     pizza=(CheckBox)findViewById(R.id.checkBox1);  
22.     coffe=(CheckBox)findViewById(R.id.checkBox2);  
23.     burger=(CheckBox)findViewById(R.id.checkBox3);  
24.     buttonOrder=(Button)findViewById(R.id.button1);  
25.   
26.     //Applying the Listener on the Button click  
27.     buttonOrder.setOnClickListener(new OnClickListener(){  
28.   
29.         @Override  
30.         public void onClick(View view) {  
31.             int totalamount=0;  
32.             StringBuilder result=new StringBuilder();  
33.             result.append("Selected Items:");  
34.             if(pizza.isChecked()){  
35.                 result.append("\nPizza 100Rs");  
36.                 totalamount+=100;  
37.             }  
38.             if(coffe.isChecked()){  
39.                 result.append("\nCoffe 50Rs");  
40.                 totalamount+=50;  
41.             }  
42.             if(burger.isChecked()){  
43.                 result.append("\nBurger 120Rs");  
44.                 totalamount+=120;  
45.             }  
46.             result.append("\nTotal: "+totalamount+"Rs");  
47.             //Displaying the message on the toast  
48.             Toast.makeText(getApplicationContext(), result.toString(), Toast.LEN
GTH_LONG).show();  
49.         }  
50.           
51.     });  
52. }  
53.     @Override  
54.     public boolean onCreateOptionsMenu(Menu menu) {  
55.         // Inflate the menu; this adds items to the action bar if it is present.  
56.         getMenuInflater().inflate(R.menu.activity_main, menu);  
57.         return true;  
58.     }  
59.   
60. }  

download this example

Output:
Android AlertDialog Example
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.

Example of Android AlertDialog

activity_main.xml

You can have multiple components, here we are having only a textview.
File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/andr
oid"  
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:layout_width="wrap_content"  
9.         android:layout_height="wrap_content"  
10.         android:layout_centerHorizontal="true"  
11.         android:layout_centerVertical="true"  
12.         android:text="@string/hello_world" />  
13.   
14. </RelativeLayout>  
strings.xml

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

1. <?xml version="1.0" encoding="utf-8"?>  
2. <resources>  
3.   
4.     <string name="app_name">alertdialog</string>  
5.     <string name="hello_world">Hello world!</string>  
6.     <string name="menu_settings">Settings</string>  
7.     <string name="dialog_message">Welcome to Alert Dialog</string>  
8.    
9.    <string name="dialog_title">Javatpoint Alert Dialog</string>  
10. </resources>  

Activity class

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


File: MainActivity.java

1. package com.example.alertdialog;  
2.   
3. import android.os.Bundle;  
4. import android.app.Activity;  
5. import android.app.AlertDialog;  
6. import android.content.DialogInterface;  
7. import android.view.Menu;  
8.   
9. public class MainActivity extends Activity {  
10.   
11.     @Override  
12.     protected void onCreate(Bundle savedInstanceState) {  
13.         super.onCreate(savedInstanceState);  
14.           
15.         AlertDialog.Builder builder = new AlertDialog.Builder(this);  
16.         //Uncomment the below code to Set the message and title from the strings
.xml file  
17.         //builder.setMessage(R.string.dialog_message) .setTitle(R.string.dialog_ti
tle);  
18.           
19.         //Setting message manually and performing action on button click  
20.         builder.setMessage("Do you want to close this application ?")  
21.             .setCancelable(false)  
22.             .setPositiveButton("Yes", new DialogInterface.OnClickListener() {  
23.                 public void onClick(DialogInterface dialog, int id) {  
24.                 finish();  
25.                 }  
26.             })  
27.             .setNegativeButton("No", new DialogInterface.OnClickListener() {  
28.                 public void onClick(DialogInterface dialog, int id) {  
29.                 //  Action for 'NO' Button  
30.                 dialog.cancel();  
31.              }  
32.             });  
33.   
34.         //Creating dialog box  
35.         AlertDialog alert = builder.create();  
36.         //Setting the title manually  
37.         alert.setTitle("AlertDialogExample");  
38.         alert.show();  
39.         setContentView(R.layout.activity_main);  
40.     }  
41.   
42.     @Override  
43.     public boolean onCreateOptionsMenu(Menu menu) {  
44.         // Inflate the menu; this adds items to the action bar if it is present.  
45.         getMenuInflater().inflate(R.menu.activity_main, menu);  
46.         return true;  
47.     }  
48.   
49. }  

download this example

Output:
Android Spinner Example
Spinner is like the combox box of AWT or Swing. It can be used to display the
multiple options to the user. Only one item can be selected by the user.
In this example, we are going to display the country list. You need to use
ArrayAdapter class to store the country list.

Example of Android Spinner

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

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/andr
oid"  
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.     <Spinner  
8.         android:id="@+id/spinner1"  
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="83dp" />  
14.   
15. </RelativeLayout>  

Activity class

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

1. package com.example.spinner;  
2. import android.app.Activity;  
3. import android.os.Bundle;  
4. import android.view.Menu;  
5. import android.view.View;  
6. import android.widget.AdapterView;  
7. import android.widget.ArrayAdapter;  
8. import android.widget.Spinner;  
9. import android.widget.TextView;  
10. import android.widget.Toast;  
11.   
12. public class MainActivity extends Activity implements  
13. AdapterView.OnItemSelectedListener {  
14.   
15.     String[] country = { "India", "USA", "China", "Japan", "Other",  };  
16.   
17.     @Override  
18.     protected void onCreate(Bundle savedInstanceState) {  
19.         super.onCreate(savedInstanceState);  
20.         setContentView(R.layout.activity_main);  
21.         //Getting the instance of Spinner and applying OnItemSelectedListener o
n it  
22.         Spinner spin = (Spinner) findViewById(R.id.spinner1);  
23.         spin.setOnItemSelectedListener(this);  
24.           
25.         //Creating the ArrayAdapter instance having the country list  
26.         ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinn
er_item,country);  
27.         aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdo
wn_item);  
28.         //Setting the ArrayAdapter data on the Spinner  
29.         spin.setAdapter(aa);  
30.     }  
31.   
32.       
33.     //Performing action onItemSelected and onNothing selected  
34.     @Override  
35.     public void onItemSelected(AdapterView<?> arg0, View arg1, int position
,long id) {  
36.         Toast.makeText(getApplicationContext(),country[position] ,Toast.LENG
TH_LONG).show();  
37.     }  
38.   
39.     @Override  
40.     public void onNothingSelected(AdapterView<?> arg0) {  
41.         // TODO Auto-generated method stub  
42.           
43.     }  
44.   
45.     @Override  
46.     public boolean onCreateOptionsMenu(Menu menu) {  
47.         // Inflate the menu; this adds items to the action bar if it is present.  
48.         getMenuInflater().inflate(R.menu.activity_main, menu);  
49.         return true;  
50.     }  
51. }  

download this example

Output:
Android AutoCompleteTextView
Example
The AutoCompleteTextView completes the word based on the reserved words, so no
need to write all the characters of the word.
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.
Example of Android AutoCompleteTextView

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

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/andr
oid"  
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_marginTop="15dp"  
14.         android:text="@string/what_is_your_favourite_programming_language_
" />  
15.   
16.     <AutoCompleteTextView  
17.         android:id="@+id/autoCompleteTextView1"  
18.         android:layout_width="wrap_content"  
19.         android:layout_height="wrap_content"  
20.         android:layout_alignParentLeft="true"  
21.         android:layout_below="@+id/textView1"  
22.         android:layout_marginLeft="36dp"  
23.         android:layout_marginTop="17dp"  
24.         android:ems="10"  
25.         android:text="">  
26.   
27.         <requestFocus />  
28.     </AutoCompleteTextView>  
29.       
30. </RelativeLayout>  

Activity class

Let's write the code of AutoCompleteTextView.


File: MainActivity.java
1. package com.example.autocompletetextview;  
2.   
3. import android.os.Bundle;  
4. import android.app.Activity;  
5. import android.graphics.Color;  
6. import android.view.Menu;  
7. import android.widget.ArrayAdapter;  
8. import android.widget.AutoCompleteTextView;  
9.   
10. public class MainActivity extends Activity {  
11.     String[] language ={"C","C+
+","Java",".NET","iPhone","Android","ASP.NET","PHP"};  
12.     @Override  
13.     protected void onCreate(Bundle savedInstanceState) {  
14.         super.onCreate(savedInstanceState);  
15.         setContentView(R.layout.activity_main);  
16.           
17.         //Creating the instance of ArrayAdapter containing list of language names 
 
18.            ArrayAdapter<String> adapter = new ArrayAdapter<String>  
19.             (this,android.R.layout.select_dialog_item,language);  
20.         //Getting the instance of AutoCompleteTextView  
21.            AutoCompleteTextView actv= (AutoCompleteTextView)findViewByI
d(R.id.autoCompleteTextView1);  
22.            actv.setThreshold(1);//will start working from first character  
23.            actv.setAdapter(adapter);//setting the adapter data into the AutoComple
teTextView  
24.            actv.setTextColor(Color.RED);  
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. }  

download this example

Output:
Android RatingBar Example
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.
The getRating() method of RatingBar class returns the rating number.

Example of Android RatingBar

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

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/andr
oid"  
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.     <RatingBar  
8.         android:id="@+id/ratingBar1"  
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="44dp" />  
14.   
15.     <Button  
16.         android:id="@+id/button1"  
17.         android:layout_width="wrap_content"  
18.         android:layout_height="wrap_content"  
19.         android:layout_alignLeft="@+id/ratingBar1"  
20.         android:layout_below="@+id/ratingBar1"  
21.         android:layout_marginLeft="92dp"  
22.         android:layout_marginTop="66dp"  
23.         android:text="submit" />  
24.   
25. </RelativeLayout>  

Activity class

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


File: MainActivity.java

1. package com.example.rating;  
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.RatingBar;  
10. import android.widget.Toast;  
11.   
12. public class MainActivity extends Activity {  
13.     RatingBar ratingbar1;  
14.     Button button;  
15.     @Override  
16.     protected void onCreate(Bundle savedInstanceState) {  
17.         super.onCreate(savedInstanceState);  
18.         setContentView(R.layout.activity_main);  
19.         addListenerOnButtonClick();  
20.     }  
21.   
22.     public void addListenerOnButtonClick(){  
23.         ratingbar1=(RatingBar)findViewById(R.id.ratingBar1);  
24.         button=(Button)findViewById(R.id.button1);  
25.         //Performing action on Button Click  
26.         button.setOnClickListener(new OnClickListener(){  
27.   
28.             @Override  
29.             public void onClick(View arg0) {  
30.                 //Getting the rating and displaying it on the toast  
31.                 String rating=String.valueOf(ratingbar1.getRating());  
32.                 Toast.makeText(getApplicationContext(), rating, Toast.LENGTH_L
ONG).show();  
33.             }  
34.               
35.         });  
36.     }  
37.     @Override  
38.     public boolean onCreateOptionsMenu(Menu menu) {  
39.         // Inflate the menu; this adds items to the action bar if it is present.  
40.         getMenuInflater().inflate(R.menu.activity_main, menu);  
41.         return true;  
42.     }  
43.   
44. }  

download this example


Output:

Android Datepicker Example


Android Datepicker Example

activity_main.xml

File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/andr
oid"  
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="50dp"  
14.         android:layout_marginTop="36dp"  
15.         android:text="Current Date:" />  
16.   
17.     <Button  
18.         android:id="@+id/button1"  
19.         android:layout_width="wrap_content"  
20.         android:layout_height="wrap_content"  
21.         android:layout_alignParentBottom="true"  
22.         android:layout_centerHorizontal="true"  
23.         android:layout_marginBottom="140dp"  
24.         android:text="Change Date" />  
25.   
26.     <DatePicker  
27.         android:id="@+id/datePicker1"  
28.         android:layout_width="wrap_content"  
29.         android:layout_height="wrap_content"  
30.         android:layout_above="@+id/button1"  
31.         android:layout_centerHorizontal="true"  
32.         android:layout_marginBottom="30dp" />  
33.   
34. </RelativeLayout>  

Activity class

File: MainActivity.java

1. package com.example.datepicker2;  
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.DatePicker;  
10. import android.widget.TextView;  
11. import android.widget.Toast;  
12.   
13. public class MainActivity extends Activity {  
14.     DatePicker picker;  
15.     Button displayDate;  
16.     TextView textview1;  
17.     @Override  
18.     protected void onCreate(Bundle savedInstanceState) {  
19.         super.onCreate(savedInstanceState);  
20.         setContentView(R.layout.activity_main);  
21.           
22.         textview1=(TextView)findViewById(R.id.textView1);  
23.         picker=(DatePicker)findViewById(R.id.datePicker1);  
24.         displayDate=(Button)findViewById(R.id.button1);  
25.           
26.         textview1.setText(getCurrentDate());  
27.           
28.         displayDate.setOnClickListener(new OnClickListener(){  
29.             @Override  
30.             public void onClick(View view) {  
31.                 textview1.setText(getCurrentDate());  
32.             }  
33.               
34.         });  
35.     }  
36.     public String getCurrentDate(){  
37.         StringBuilder builder=new StringBuilder();  
38.         builder.append("Current Date: ");  
39.         builder.append((picker.getMonth() + 1)+"/");//month is 0 based  
40.         builder.append(picker.getDayOfMonth()+"/");  
41.         builder.append(picker.getYear());  
42.         return builder.toString();  
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 TimePicker Example


Android TimePicker Example

activity_main.xml

File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/andr
oid"  
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>  

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;  
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
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.
The android.widget.AnalogClock and android.widget.DigitalClock classes
provides the functionality to display analog and digital clocks.

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.

activity_main.xml

Now, drag the anaglog and digital clocks, now the xml file will look like this.
File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/andr
oid"  
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.     <AnalogClock  
8.         android:id="@+id/analogClock1"  
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="22dp" />  
14.   
15.     <DigitalClock  
16.         android:id="@+id/digitalClock1"  
17.         android:layout_width="wrap_content"  
18.         android:layout_height="wrap_content"  
19.         android:layout_below="@+id/analogClock1"  
20.         android:layout_centerHorizontal="true"  
21.         android:layout_marginTop="81dp"  
22.         android:text="DigitalClock" />  
23.   
24. </RelativeLayout>  

Activity class

We have not write any code here.


File: MainActivity.java

1. package com.example.analogdigital;  
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.     @Override  
16.     public boolean onCreateOptionsMenu(Menu menu) {  
17.         // Inflate the menu; this adds items to the action bar if it is present.  
18.         getMenuInflater().inflate(R.menu.activity_main, menu);  
19.         return true;  
20.     }  
21. }  

download this android example

Output:

Android ProgressBar Example


We can display the progress bar dialog box to display the status of work being done
e.g. downloading file etc.
In this example, we are displaying the progress dialog for dummy file download.
The ProgressDialog class provides methods to work on progress bar like
setProgress(), setMessage(), show() etc.

activity_main.xml

Drag one button 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/andr
oid"  
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="116dp"  
14.         android:text="download file" />  
15.   
16. </RelativeLayout>  

Activity class

Let's write the code to display the progress bar dialog box.
File: MainActivity.java

1. package com.example.progressbar1;  
2.   
3. import android.app.Activity;  
4. import android.app.ProgressDialog;  
5. import android.os.Bundle;  
6. import android.os.Handler;  
7. import android.widget.Button;  
8. import android.view.Menu;  
9. import android.view.View;  
10. import android.view.View.OnClickListener;  
11.   
12. public class MainActivity extends Activity {  
13.     Button btnStartProgress;  
14.     ProgressDialog progressBar;  
15.     private int progressBarStatus = 0;  
16.     private Handler progressBarHandler = new Handler();  
17.     private long fileSize = 0;  
18.       
19.     @Override  
20.     protected void onCreate(Bundle savedInstanceState) {  
21.         super.onCreate(savedInstanceState);  
22.         setContentView(R.layout.activity_main);  
23.         addListenerOnButtonClick();  
24.     }  
25.       
26.     public void addListenerOnButtonClick() {  
27.            
28.         btnStartProgress = (Button) findViewById(R.id.button1);  
29.         btnStartProgress.setOnClickListener(new OnClickListener(){  
30.    
31.            @Override  
32.            public void onClick(View v) {  
33.    
34.             // creating progress bar dialog  
35.             progressBar = new ProgressDialog(v.getContext());  
36.             progressBar.setCancelable(true);  
37.             progressBar.setMessage("File downloading ...");  
38.             progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL
);  
39.             progressBar.setProgress(0);  
40.             progressBar.setMax(100);  
41.             progressBar.show();  
42.    
43.             //reset progress bar and filesize status  
44.             progressBarStatus = 0;  
45.             fileSize = 0;  
46.    
47.             new Thread(new Runnable() {  
48.               public void run() {  
49.                 while (progressBarStatus < 100) {  
50.    
51.                   // performing operation  
52.                   progressBarStatus = doOperation();  
53.    
54.                   try {  
55.                     Thread.sleep(1000);  
56.                   } catch (InterruptedException e) {  
57.                     e.printStackTrace();  
58.                   }  
59.    
60.                   // Updating the progress bar  
61.                   progressBarHandler.post(new Runnable() {  
62.                     public void run() {  
63.                       progressBar.setProgress(progressBarStatus);  
64.                     }  
65.                   });  
66.                 }  
67.    
68.                 // performing operation if file is downloaded,  
69.                 if (progressBarStatus >= 100) {  
70.    
71.                     // sleeping for 1 second after operation completed  
72.                     try {  
73.                         Thread.sleep(1000);  
74.                     } catch (InterruptedException e) {e.printStackTrace();}  
75.    
76.                     // close the progress bar dialog  
77.                     progressBar.dismiss();  
78.                 }  
79.               }  
80.              }).start();  
81.             }//end of onClick method  
82.           });  
83.          }  
84.    
85.     // checking how much file is downloaded and updating the filesize   
86.     public int doOperation() {  
87.         //The range of ProgressDialog starts from 0 to 10000  
88.         while (fileSize <= 10000) {  
89.             fileSize++;  
90.             if (fileSize == 1000) {  
91.                 return 10;  
92.             } else if (fileSize == 2000) {  
93.                 return 20;  
94.             } else if (fileSize == 3000) {  
95.                 return 30;  
96.             } else if (fileSize == 4000) {  
97.             return 40;  
98.             } else if (fileSize == 5000) {  
99.                 return 50;  
100.             } else if (fileSize == 6000) {  
101.                 return 60;  
102.             }  
103.              else if (fileSize == 7000) {  
104.                     return 70;  
105.             }  
106.              else if (fileSize == 8000) {  
107.                     return 80;  
108.             }  
109.              else if (fileSize == 9000) {  
110.                     return 90;  
111.             }  
112.              else if (fileSize == 10000) {  
113.                     return 100;  
114.             }  
115.         }//end of while  
116.         return 100;  
117.     }//end of doOperation  
118.   
119.     @Override  
120.     public boolean onCreateOptionsMenu(Menu menu) {  
121.         // Inflate the menu; this adds items to the action bar if it is present. 
 
122.         getMenuInflater().inflate(R.menu.main, menu);  
123.         return true;  
124.     }  
125. }  
download this android example

Output:

Android Life Cycle of Activity


We can control and manage the resource through the life cycle methods of activity.
There are 7 life cycle methods of android.app.Activity class. They are as follows:
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.
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 Life Cycle Example

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

1. package com.example.activitylifecycle;  
2.   
3. import android.os.Bundle;  
4. import android.app.Activity;  
5. import android.util.Log;  
6. import android.view.Menu;  
7.   
8. public class MainActivity extends Activity {  
9.   
10.     @Override  
11.     protected void onCreate(Bundle savedInstanceState) {  
12.         super.onCreate(savedInstanceState);  
13.         setContentView(R.layout.activity_main);  
14.         Log.d("lifecycle","onCreate invoked");  
15.     }  
16.     @Override  
17.     protected void onStart() {  
18.         super.onStart();  
19.          Log.d("lifecycle","onStart invoked");  
20.     }  
21.     @Override  
22.     protected void onResume() {  
23.           
24.         super.onResume();  
25.          Log.d("lifecycle","onResume invoked");  
26.     }  
27.       
28.   
29.     @Override  
30.     protected void onPause() {  
31.           
32.         super.onPause();  
33.          Log.d("lifecycle","onPause invoked");  
34.     }  
35.     @Override  
36.     protected void onStop() {  
37.           
38.         super.onStop();  
39.          Log.d("lifecycle","onStop invoked");  
40.     }  
41.       
42.        @Override  
43.     protected void onRestart() {  
44.           
45.         super.onRestart();  
46.          Log.d("lifecycle","onRestart invoked");  
47.     }     
48.     @Override  
49.     protected void onDestroy() {  
50.           
51.         super.onDestroy();  
52.          Log.d("lifecycle","onDestroy invoked");  
53.     }  
54. }  
download this example

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.
Now click on the HOME Button. You will see onPause method is invoked.
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.

Now see on the logcat: onRestart, onStart and onResume methods are invoked.
If you see the emulator, application is started again.

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.
Android Intent Tutorial
Intent is the message that is passed between components such as activities, content
providers, broadcast receivers, services etc.
The dictionary meaning of intent is intention or purpose. So, it can be described as
the intention to do action.
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.

Types of Intents

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

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.javatpoint.com"));  
3. startActivity(intent);  

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
1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/andr
oid"  
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_alignParentTop="true"  
12.         android:layout_centerHorizontal="true"  
13.         android:layout_marginTop="44dp"  
14.         android:ems="10" />  
15.   
16.     <Button  
17.         android:id="@+id/button1"  
18.         android:layout_width="wrap_content"  
19.         android:layout_height="wrap_content"  
20.         android:layout_below="@+id/editText1"  
21.         android:layout_centerHorizontal="true"  
22.         android:layout_marginTop="54dp"  
23.         android:text="Visit" />  
24.   
25. </RelativeLayout>  

Activity class

File: MainActivity.java

1. package org.sssit.implicitintent;  
2.   
3. import android.net.Uri;  
4. import android.os.Bundle;  
5. import android.app.Activity;  
6. import android.content.Intent;  
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.   
14.     @Override  
15.     protected void onCreate(Bundle savedInstanceState) {  
16.         super.onCreate(savedInstanceState);  
17.         setContentView(R.layout.activity_main);  
18.           
19.         final EditText editText1=(EditText)findViewById(R.id.editText1);  
20.         Button button1=(Button)findViewById(R.id.button1);  
21.           
22.         button1.setOnClickListener(new OnClickListener() {  
23.               
24.             @Override  
25.             public void onClick(View arg0) {  
26.                 String url=editText1.getText().toString();  
27.                 Intent intent=new Intent(Intent.ACTION_VIEW,Uri.parse(url));  
28.                 startActivity(intent);  
29.             }  
30.         });  
31.     }  
32.   
33. }  

download this android example

Output:
Android Explicit Intent Example
Explicit intent specifies the component that is which class to be invoked. We can
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

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/andr
oid"  
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/Button01"  
9.         android:layout_width="wrap_content"  
10.         android:layout_height="wrap_content"  
11.         android:layout_alignParentLeft="true"  
12.         android:layout_below="@+id/TextView01"  
13.         android:layout_marginLeft="65dp"  
14.         android:layout_marginTop="38dp"  
15.         android:onClick="onClick"  
16.         android:text="Call second activity" />  
17.   
18.     <TextView  
19.         android:id="@+id/TextView01"  
20.         android:layout_width="wrap_content"  
21.         android:layout_height="wrap_content"  
22.         android:layout_alignLeft="@+id/Button01"  
23.         android:layout_alignParentTop="true"  
24.         android:layout_marginLeft="18dp"  
25.         android:layout_marginTop="27dp"  
26.         android:minHeight="60dip"  
27.         android:text="First Activity"  
28.         android:textSize="20sp" />  
29.   
30. </RelativeLayout>  

activitytwo_main.xml

File: activitytwo_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/andr
oid"  
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/Button01"  
9.         android:layout_width="wrap_content"  
10.         android:layout_height="wrap_content"  
11.         android:layout_alignParentLeft="true"  
12.         android:layout_below="@+id/TextView01"  
13.         android:layout_marginLeft="65dp"  
14.         android:layout_marginTop="38dp"  
15.         android:onClick="onClick"  
16.         android:text="Call First activity" />  
17.   
18.     <TextView  
19.         android:id="@+id/TextView01"  
20.         android:layout_width="wrap_content"  
21.         android:layout_height="wrap_content"  
22.         android:layout_alignLeft="@+id/Button01"  
23.         android:layout_alignParentTop="true"  
24.         android:layout_marginLeft="18dp"  
25.         android:layout_marginTop="27dp"  
26.         android:minHeight="60dip"  
27.         android:text="Second Activity"  
28.         android:textSize="20sp" />  
29.   
30. </RelativeLayout>  

ActivityOne class

File: MainActivityOne.java

1. package com.example.explicitintent2;  
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.Toast;  
11.   
12. public class ActivityOne extends Activity {  
13.         
14.     /** Called when the activity is first created. */  
15.   
16.       @Override  
17.       public void onCreate(Bundle savedInstanceState) {  
18.         super.onCreate(savedInstanceState);  
19.         setContentView(R.layout.activity_main);  
20.           
21.         Button button1=(Button)findViewById(R.id.Button01);  
22.           
23.         button1.setOnClickListener(new OnClickListener(){  
24.          public void onClick(View view) {  
25.           Intent i = new Intent(getApplicationContext(), ActivityTwo.class);  
26.           i.putExtra("Value1", "Android By Javatpoint");  
27.           i.putExtra("Value2", "Simple Tutorial");  
28.           // Set the request code to any code you like, you can identify the  
29.           // callback via this code  
30.           startActivity(i);  
31.          }  
32.          });  
33.   
34.       }  
35.   
36.            
37.     }   

ActivityTwo class

File: MainActivityTwo.java

1. package com.example.explicitintent2;  
2.   
3. import android.app.Activity;  
4. import android.content.Intent;  
5. import android.os.Bundle;  
6. import android.view.View;  
7. import android.view.View.OnClickListener;  
8. import android.widget.Button;  
9. import android.widget.EditText;  
10. import android.widget.TextView;  
11. import android.widget.Toast;  
12.   
13. public class ActivityTwo extends Activity {  
14.   
15.     
16. /** Called when the activity is first created. */  
17.   
18.   @Override  
19.   public void onCreate(Bundle bundle) {  
20.     super.onCreate(bundle);  
21.       
22.     TextView tv=new TextView(this);  
23.     tv.setText("second activity");  
24.     setContentView(R.layout.activity_two);  
25.       
26.     Bundle extras = getIntent().getExtras();  
27.     String value1 = extras.getString("Value1");  
28.     String value2 = extras.getString("Value2");  
29.       
30.     Toast.makeText(getApplicationContext(),"Values are:\n First value: "+valu
e1+  
31.          "\n Second Value: "+value2,Toast.LENGTH_LONG).show();  
32.       
33.     Button button1=(Button)findViewById(R.id.Button01);  
34.       
35.     button1.setOnClickListener(new OnClickListener(){  
36.         public void onClick(View view) {  
37.             Intent i = new Intent(getApplicationContext(), ActivityOne.class);  
38.             startActivity(i);  
39.           }  
40.     });  
41.   }  
42. }   

download this android example

Output:
Android StartActivityForResult
Example
We can send information from one activity to another and vice-versa. The
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.

Android StartActivityForResult Example


Let's see the simple example of 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

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/andr
oid"  
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_alignLeft="@+id/button1"  
16.         android:layout_alignParentTop="true"  
17.         android:layout_marginTop="48dp"  
18.         android:text="Default Message" />  
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/textView1"  
25.         android:layout_centerHorizontal="true"  
26.         android:layout_marginTop="42dp"  
27.         android:text="GetMessage" />  
28.   
29. </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

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/andr
oid"  
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=".SecondActivity" >  
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_marginTop="61dp"  
17.         android:layout_toRightOf="@+id/textView1"  
18.         android:ems="10" />  
19.   
20.     <TextView  
21.         android:id="@+id/textView1"  
22.         android:layout_width="wrap_content"  
23.         android:layout_height="wrap_content"  
24.         android:layout_alignBaseline="@+id/editText1"  
25.         android:layout_alignBottom="@+id/editText1"  
26.         android:layout_alignParentLeft="true"  
27.         android:text="Enter Message:" />  
28.   
29.     <Button  
30.         android:id="@+id/button1"  
31.         android:layout_width="wrap_content"  
32.         android:layout_height="wrap_content"  
33.         android:layout_below="@+id/editText1"  
34.         android:layout_centerHorizontal="true"  
35.         android:layout_marginTop="34dp"  
36.         android:text="Submit" />  
37.   
38. </RelativeLayout>  

Activity class

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

1. package com.javatpoint.startactivityforresult;  
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.TextView;  
11.   
12. public class MainActivity extends Activity {  
13.     TextView textView1;  
14.     Button button1;  
15.     @Override  
16.     protected void onCreate(Bundle savedInstanceState) {  
17.         super.onCreate(savedInstanceState);  
18.         setContentView(R.layout.activity_main);  
19.           
20.         textView1=(TextView)findViewById(R.id.textView1);  
21.         button1=(Button)findViewById(R.id.button1);  
22.           
23.         button1.setOnClickListener(new OnClickListener() {  
24.               
25.             @Override  
26.             public void onClick(View arg0) {  
27.                 Intent intent=new Intent(MainActivity.this,SecondActivity.class);  
28.                 startActivityForResult(intent, 2);// Activity is started with requestCo
de 2  
29.             }  
30.         });  
31.     }  
32.   
33.  // Call Back method  to get the Message form other Activity  
34.     @Override  
35.        protected void onActivityResult(int requestCode, int resultCode, Intent da
ta)  
36.        {  
37.                  super.onActivityResult(requestCode, resultCode, data);  
38.                      
39.                   // check if the request code is same as what is passed  here it is 2  
40.                    if(requestCode==2)  
41.                          {  
42.                             String message=data.getStringExtra("MESSAGE");   
43.                             textView1.setText(message);  
44.                  
45.                          }  
46.      
47.      }  
48.   
49.     @Override  
50.     public boolean onCreateOptionsMenu(Menu menu) {  
51.         // Inflate the menu; this adds items to the action bar if it is present.  
52.         getMenuInflater().inflate(R.menu.main, menu);  
53.         return true;  
54.     }  
55.       
56. }  

SecondActivity class

Let's write the code that displays the content of second activity layout file.
File: SecondActivity.java

1. package com.javatpoint.startactivityforresult;  
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. import android.widget.TextView;  
12.   
13. public class SecondActivity 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_second);  
20.           
21.             editText1=(EditText)findViewById(R.id.editText1);  
22.             button1=(Button)findViewById(R.id.button1);  
23.               
24.             button1.setOnClickListener(new OnClickListener() {  
25.                   
26.                 @Override  
27.                 public void onClick(View arg0) {  
28.                     String message=editText1.getText().toString();  
29.                     Intent intent=new Intent();  
30.                     intent.putExtra("MESSAGE",message);  
31.                       
32.                     setResult(2,intent);  
33.                       
34.                     finish();//finishing activity  
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.second, menu);  
43.         return true;  
44.     }  
45.   
46. }  

download this android example

Output:
Android Option Menu Example
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

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/andr
oid"  
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>  

menu_main.xml

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

1. <menu xmlns:androclass="http://schemas.android.com/apk/res/android" >  
2.   
3.     <item  android:id="@+id/item1"  
4.         android:title="Item 1"/>  
5.   
6.     <item  android:id="@+id/item2"  
7.         android:title="Item 2"/>  
8.      
9.     <item  android:id="@+id/item3"  
10.         android:title="Item 3"/>  
11.     
12. </menu>  

Activity class

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

1. package com.javatpoint.optionmenu;  
2. import android.os.Bundle;  
3. import android.app.Activity;  
4. import android.view.Menu;  
5. import android.view.MenuItem;  
6. import android.widget.Toast;  
7.   
8. public class MainActivity extends Activity {  
9.     @Override  
10.     protected void onCreate(Bundle savedInstanceState) {  
11.         super.onCreate(savedInstanceState);  
12.         setContentView(R.layout.activity_main);  
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.main, menu);//Menu Resource, Menu  
18.         return true;  
19.     }  
20.       
21.     @Override  
22.     public boolean onOptionsItemSelected(MenuItem item) {  
23.         switch (item.getItemId()) {  
24.             case R.id.item1:  
25.               Toast.makeText(getApplicationContext(),"Item 1 Selected",Toast.LE
NGTH_LONG).show();  
26.             return true;     
27.   
28.             case R.id.item2:  
29.                 Toast.makeText(getApplicationContext(),"Item 2 Selected",Toast.L
ENGTH_LONG).show();  
30.               return true;     
31.               
32.             case R.id.item3:  
33.                 Toast.makeText(getApplicationContext(),"Item 3 Selected",Toast.L
ENGTH_LONG).show();  
34.               return true;     
35.   
36.               default:  
37.                 return super.onOptionsItemSelected(item);  
38.         }  
39.     }  
40. }  

download this android example

Output:

Output without clicking on the menu button.

Output after clicking on the menu button.


Output after clicking on the second menu item .

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.   
3.     <item  android:id="@+id/item1"  
4.         android:icon="@drawable/add"  
5.         android:title="Item 1"/>  
6.   
7.     <item  android:id="@+id/item2"  
8.         android:icon="@drawable/minus"  
9.         android:title="Item 2"/>  
10.      
11.     <item  android:id="@+id/item3"  
12.         android:icon="@drawable/delete"  
13.         android:title="Item 3"/>  
14.       
15. </menu>  

Android Context Menu Example


The 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

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.     <ListView  
12.         android:id="@+id/listView1"  
13.         android:layout_width="match_parent"  
14.         android:layout_height="wrap_content"  
15.         android:layout_alignParentLeft="true"  
16.         android:layout_alignParentTop="true"  
17.         android:layout_marginLeft="66dp"  
18.         android:layout_marginTop="53dp" >  
19.     </ListView>  
20.   
21. </RelativeLayout>  

Activity class

Let's write the code to display the context menu on press of the listview.
File: MainActivity.java

1. package com.javatpoint.contextmenu;  
2. import android.os.Bundle;  
3. import android.app.Activity;  
4. import android.view.ContextMenu;  
5. import android.view.ContextMenu.ContextMenuInfo;  
6. import android.view.Menu;  
7. import android.view.MenuItem;  
8. import android.view.View;  
9. import android.widget.AdapterView;  
10. import android.widget.ArrayAdapter;  
11. import android.widget.ListView;  
12. import android.widget.Toast;  
13.   
14. public class MainActivity extends Activity {  
15.     ListView listView1;  
16.     String contacts[]={"Ajay","Sachin","Sumit","Tarun","Yogesh"};  
17.       
18.     @Override  
19.     protected void onCreate(Bundle savedInstanceState) {  
20.         super.onCreate(savedInstanceState);  
21.         setContentView(R.layout.activity_main);  
22.           
23.         listView1=(ListView)findViewById(R.id.listView1);  
24.           
25.         ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.
R.layout.simple_list_item_1,contacts);  
26.         listView1.setAdapter(adapter);  
27.           
28.         // Register the ListView  for Context menu  
29.         registerForContextMenu(listView1);  
30.     }  
31.   
32.     @Override   
33.     public void onCreateContextMenu(ContextMenu menu, View v, ContextMe
nuInfo menuInfo)  
34.     {  
35.             super.onCreateContextMenu(menu, v, menuInfo);  
36.             menu.setHeaderTitle("Select The Action");    
37.             menu.add(0, v.getId(), 0, "Call");//groupId, itemId, order, title   
38.             menu.add(0, v.getId(), 0, "SMS");   
39.     }   
40.       
41.     @Override    
42.     public boolean onContextItemSelected(MenuItem item){    
43.             if(item.getTitle()=="Call"){  
44.                 Toast.makeText(getApplicationContext(),"calling code",Toast.LEN
GTH_LONG).show();  
45.             }    
46.             else if(item.getTitle()=="SMS"){  
47.                 Toast.makeText(getApplicationContext(),"sending sms code",Toast.
LENGTH_LONG).show();  
48.             }else{  
49.                return false;  
50.             }    
51.           return true;    
52.       }    
53.     }  

download this android example

Output:

Output after long press on the listview.


Output after clicking on the context menu.

Android Popup Menu Example


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.

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

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/andr
oid"  
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="62dp"  
18.         android:layout_marginTop="50dp"  
19.         android:text="Show Popup" />  
20.   
21. </RelativeLayout>  

popup_menu.xml

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

1. <menu xmlns:androclass="http://schemas.android.com/apk/res/android" >  
2.   
3.     <item  
4.         android:id="@+id/one"  
5.         android:title="One"/>  
6.       
7.     <item  
8.         android:id="@+id/two"  
9.         android:title="Two"/>  
10.         
11.     <item  
12.         android:id="@+id/three"  
13.         android:title="Three"/>  
14.           
15. </menu>  

Activity class
It displays the popup menu on button click.
File: MainActivity.java

1. package com.javatpoint.popupmenu;  
2. import android.os.Bundle;  
3. import android.app.Activity;  
4. import android.view.Menu;  
5. import android.view.MenuItem;  
6. import android.view.View;  
7. import android.view.View.OnClickListener;  
8. import android.widget.Button;  
9. import android.widget.PopupMenu;  
10. import android.widget.Toast;  
11. public class MainActivity extends Activity {  
12. Button button1;  
13.            
14.          @Override  
15.          protected void onCreate(Bundle savedInstanceState) {  
16.           super.onCreate(savedInstanceState);  
17.           setContentView(R.layout.activity_main);  
18.             
19.           button1 = (Button) findViewById(R.id.button1);  
20.           button1.setOnClickListener(new OnClickListener() {  
21.            
22.            @Override  
23.            public void onClick(View v) {  
24.             //Creating the instance of PopupMenu  
25.             PopupMenu popup = new PopupMenu(MainActivity.this, button1);  
26.             //Inflating the Popup using xml file  
27.             popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu
());  
28.            
29.             //registering popup with OnMenuItemClickListener  
30.             popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemCl
ickListener() {  
31.              public boolean onMenuItemClick(MenuItem item) {  
32.               Toast.makeText(MainActivity.this,"You Clicked : " + item.getTitle(),
Toast.LENGTH_SHORT).show();  
33.               return true;  
34.              }  
35.             });  
36.   
37.             popup.show();//showing popup menu  
38.            }  
39.           });//closing the setOnClickListener method  
40.          }  
41.     }  

download this android example


Output:

Android Service Tutorial


A 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).

Understanding the Life Cycle of Service

There can be two forms of a service.


1. Started
2. Bound

The lifecycle of service can follow two different paths: started or 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 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.
activity_main.xml

Drag the 3 buttons from the pallete, now the activity_main.xml will look like this:
File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/andr
oid"  
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/buttonStart"  
13.         android:layout_width="wrap_content"  
14.         android:layout_height="wrap_content"  
15.         android:layout_alignParentTop="true"  
16.         android:layout_centerHorizontal="true"  
17.         android:layout_marginTop="19dp"  
18.         android:text="Start Service" />  
19.   
20.     <Button  
21.         android:id="@+id/buttonStop"  
22.         android:layout_width="wrap_content"  
23.         android:layout_height="wrap_content"  
24.         android:layout_above="@+id/buttonNext"  
25.         android:layout_alignRight="@+id/buttonStart"  
26.         android:layout_marginBottom="35dp"  
27.         android:text="Stop Service" />  
28.   
29.     <Button  
30.         android:id="@+id/buttonNext"  
31.         android:layout_width="wrap_content"  
32.         android:layout_height="wrap_content"  
33.         android:layout_alignLeft="@+id/buttonStop"  
34.         android:layout_centerVertical="true"  
35.         android:text="Next Page" />  
36.   
37. </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

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/andr
oid"  
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="96dp"  
18.         android:layout_marginTop="112dp"  
19.         android:text="Next Page" />  
20.   
21. </RelativeLayout>  

Service class

Now create the service implemenation class by inheriting the Service class and
overridding its callback methods.
File: MyService.java

1. package com.example.serviceexampleaudio;  
2.   
3. import android.app.Service;  
4. import android.content.Intent;  
5. import android.media.MediaPlayer;  
6. import android.os.IBinder;  
7. import android.widget.Toast;  
8.   
9. public class MyService extends Service {  
10.  MediaPlayer myPlayer;  
11.   
12.  @Override  
13.  public IBinder onBind(Intent intent) {  
14.   return null;  
15.  }  
16.   
17.  @Override  
18.  public void onCreate() {  
19.   Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();  
20.     
21.   myPlayer = MediaPlayer.create(this, R.raw.sun);  
22.   myPlayer.setLooping(false); // Set looping  
23.  }  
24.   
25.  @Override  
26.  public void onStart(Intent intent, int startid) {  
27.   Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();  
28.   myPlayer.start();  
29.  }  
30.    
31.  @Override  
32.  public void onDestroy() {  
33.   Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();  
34.   myPlayer.stop();  
35.  }  
36. }  

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

1. package com.example.serviceexampleaudio;  
2.   
3. import android.app.Activity;  
4. import android.content.Intent;  
5. import android.os.Bundle;  
6. import android.view.View;  
7. import android.view.View.OnClickListener;  
8. import android.widget.Button;  
9.   
10. public class MainActivity extends Activity implements OnClickListener {  
11.      Button buttonStart, buttonStop,buttonNext;  
12.   
13.      @Override  
14.      public void onCreate(Bundle savedInstanceState) {  
15.       super.onCreate(savedInstanceState);  
16.       setContentView(R.layout.activity_main);  
17.   
18.       buttonStart = (Button) findViewById(R.id.buttonStart);  
19.       buttonStop = (Button) findViewById(R.id.buttonStop);  
20.       buttonNext = (Button) findViewById(R.id.buttonNext);  
21.   
22.       buttonStart.setOnClickListener(this);  
23.       buttonStop.setOnClickListener(this);  
24.       buttonNext.setOnClickListener(this);  
25.      }  
26.   
27.      public void onClick(View src) {  
28.       switch (src.getId()) {  
29.       case R.id.buttonStart:  
30.        startService(new Intent(this, MyService.class));  
31.        break;  
32.       case R.id.buttonStop:  
33.        stopService(new Intent(this, MyService.class));  
34.        break;  
35.       case R.id.buttonNext:  
36.        Intent intent=new Intent(this,NextPage.class);  
37.        startActivity(intent);  
38.        break;  
39.       }  
40.      }  
41. }  

NextPage class

Now, create another activity.


File: NextPage.java

1. package com.example.serviceexampleaudio;  
2. import android.app.Activity;  
3. import android.os.Bundle;  
4.   
5. public class NextPage extends Activity {  
6.  @Override  
7.  public void onCreate(Bundle savedInstanceState) {  
8.   super.onCreate(savedInstanceState);  
9.   setContentView(R.layout.activity_next);  
10.   
11.  }  
12. }  

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

1. <?xml version="1.0" encoding="utf-8"?>  
2. <manifest xmlns:androclass="http://schemas.android.com/apk/res/android"  
3.     package="com.example.serviceexampleaudio"  
4.     android:versionCode="1"  
5.     android:versionName="1.0" >  
6.   
7.     <uses-sdk  
8.         android:minSdkVersion="8"  
9.         android:targetSdkVersion="17" />  
10.   
11.     <application  
12.         android:allowBackup="true"  
13.         android:icon="@drawable/ic_launcher"  
14.         android:label="@string/app_name"  
15.         android:theme="@style/AppTheme" >  
16.         <activity  
17.             android:name="com.example.serviceexampleaudio.MainActivity"  
18.             android:label="@string/app_name" >  
19.             <intent-filter>  
20.                 <action android:name="android.intent.action.MAIN" />  
21.   
22.                 <category android:name="android.intent.category.LAUNCHER" />  
23.             </intent-filter>  
24.         </activity>  
25.           
26.         <service  
27.             android:name=".MyService"  
28.             android:enabled="true" />  
29.          <activity  
30.             android:name=".NextPage"/>  
31.     </application>  
32.   
33. </manifest>  

download this android example

Output:
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.

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

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.     <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"  
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>  

Activity class

Let's write the code to write and read data from the internal storage.
File: MainActivity.java

1. package com.example.internalstorage;  
2.   
3. import java.io.BufferedReader;  
4. import java.io.FileInputStream;  
5. import java.io.FileNotFoundException;  
6. import java.io.FileOutputStream;  
7. import java.io.IOException;  
8. import java.io.InputStreamReader;  
9.   
10. import android.os.Bundle;  
11. import android.app.Activity;  
12. import android.content.Context;  
13. import android.view.Menu;  
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.Toast;  
19.   
20. public class MainActivity extends Activity {  
21.     EditText editTextFileName,editTextData;  
22.     Button saveButton,readButton;  
23.     @Override  
24.     protected void onCreate(Bundle savedInstanceState) {  
25.         super.onCreate(savedInstanceState);  
26.         setContentView(R.layout.activity_main);  
27.           
28.         editTextFileName=(EditText)findViewById(R.id.editText1);  
29.         editTextData=(EditText)findViewById(R.id.editText2);  
30.         saveButton=(Button)findViewById(R.id.button1);  
31.         readButton=(Button)findViewById(R.id.button2);  
32.           
33.         //Performing Action on Read Button  
34.         saveButton.setOnClickListener(new OnClickListener(){  
35.   
36.             @Override  
37.             public void onClick(View arg0) {  
38.                 String filename=editTextFileName.getText().toString();  
39.                 String data=editTextData.getText().toString();  
40.                   
41.                 FileOutputStream fos;  
42.                    try {  
43.                     fos = openFileOutput(filename, Context.MODE_PRIVATE);  
44.                     //default mode is PRIVATE, can be APPEND etc.  
45.                     fos.write(data.getBytes());  
46.                     fos.close();  
47.                      
48.                     Toast.makeText(getApplicationContext(),filename + " saved",  
49.                             Toast.LENGTH_LONG).show();  
50.                       
51.                      
52.                    } catch (FileNotFoundException e) {e.printStackTrace();}  
53.                    catch (IOException e) {e.printStackTrace();}  
54.                   
55.             }  
56.               
57.         });  
58.           
59.         //Performing Action on Read Button  
60.         readButton.setOnClickListener(new OnClickListener(){  
61.   
62.             @Override  
63.             public void onClick(View arg0) {  
64.                 String filename=editTextFileName.getText().toString();  
65.                 StringBuffer stringBuffer = new StringBuffer();    
66.                 try {  
67.                     //Attaching BufferedReader to the FileInputStream by the help of 
InputStreamReader  
68.                     BufferedReader inputReader = new BufferedReader(new InputStr
eamReader(  
69.                             openFileInput(filename)));  
70.                     String inputString;  
71.                     //Reading data line by line and storing it into the stringbuffer          
      
72.                     while ((inputString = inputReader.readLine()) != null) {  
73.                         stringBuffer.append(inputString + "\n");  
74.                     }  
75.                       
76.                 } catch (IOException e) {  
77.                     e.printStackTrace();  
78.                 }  
79.                 //Displaying data on the toast  
80.                 Toast.makeText(getApplicationContext(),stringBuffer.toString(),  
81.                         Toast.LENGTH_LONG).show();  
82.                   
83.             }  
84.               
85.         });  
86.     }  
87.   
88.     @Override  
89.     public boolean onCreateOptionsMenu(Menu menu) {  
90.         // Inflate the menu; this adds items to the action bar if it is present.  
91.         getMenuInflater().inflate(R.menu.activity_main, menu);  
92.         return true;  
93.     }  
94.   
95. }  

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.   
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"  
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:nam
e="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:nam
e="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" />  
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);  
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);  
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. }  

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


There are two constructors of SQLiteOpenHelper class.
Constructor Description
creates an object for
SQLiteOpenHelper(Context context, String name,
creating, opening and
SQLiteDatabase.CursorFactory factory, int version)
managing the database.
creates an object for
SQLiteOpenHelper(Context context, String name,
creating, opening and
SQLiteDatabase.CursorFactory factory, int version,
managing the database. It
DatabaseErrorHandler errorHandler)
specifies the 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
public abstract void onCreate(SQLiteDatabase db) database is created for the first
time.
public abstract void onUpgrade(SQLiteDatabase called when database needs to
db, int oldVersion, int newVersion) be upgraded.
public synchronized void close () closes the database object.
public void onDowngrade(SQLiteDatabase db, int called when database needs to
oldVersion, int newVersion) be 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
void execSQL(String sql) executes the sql query not select query.
inserts a record on the database. The table
specifies the table name, nullColumnHack doesn't
long insert(String table, String
allow completely null values. If second argument
nullColumnHack, ContentValues
is null, android will store null values if values are
values)
empty. The third argument specifies the values to
be stored.
int update(String table,
ContentValues values, String updates a row.
whereClause, String[] whereArgs)
Cursor query(String table,
String[] columns, String selection,
String[] selectionArgs, String returns a cursor over the resultset.
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){  
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.     }  
23.    
24.     // Creating Tables  
25.     @Override  
26.     public void onCreate(SQLiteDatabase db) {  
27.         String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABL
E_CONTACTS + "("  
28.                 + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " T
EXT,"  
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  
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();  
117.     }  
118.    
119.     // Getting contacts Count  
120.     public int getContactsCount() {  
121.         String countQuery = "SELECT  * FROM " + TABLE_CONTAC
TS;  
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) {  
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:
Android Sqlite Example
In this example, we are adding a lable 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 oprations 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 lables or data.

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/andr
oid"  
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>  

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 OnItemSelectedListen
er{  
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.    
43.                 if (label.trim().length() > 0) {  
44.                     DatabaseHandler db = new DatabaseHandler(getApplicationCont
ext());  
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 nam
e",  
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> lables = db.getAllLabels();  
72.    
73.         // Creating adapter for spinner  
74.         ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,an
droid.R.layout.simple_spinner_item, lables);  
75.    
76.         // Drop down layout style - list view with radio button  
77.         dataAdapter.setDropDownViewResource(android.R.layout.simple_spinn
er_dropdown_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 positio
n,  
85.             long id) {  
86.         // On selecting a spinner item  
87.         String label = parent.getItemAtPosition(position).toString();  
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) {  
24.         // Category table create query  
25.         String CREATE_ITEM_TABLE = "CREATE TABLE " + TABLE_NA
ME + "("  
26.                 + COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_N
AME + " 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,selectedAr
guments  
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  
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:

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/andr
oid"  
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

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.   
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. }  

download this example

Output:
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/andr
oid"  
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

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) {  
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).getChildN
odes();  
49. Node node = (Node) nodeList.item(0);  
50. return node.getNodeValue();  
51. }  
52.   
53. }  

download this example

Output:
Android XMLPullParser Tutorial
Android recommends to use XMLPullParser to parse the xml file than SAX and
DOM becuase 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>  
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;  
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 {  
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. }  

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);  
40.         return true;  
41.     }  
42.       
43. }  

download this example

Output:
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", "Satur
day"]  

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. }  

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/andr
oid"  
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\":56000}}";  
11.   
12. @Override  
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("emp
loyee");  
21. String empname=emp.getString("name");  
22. int empsalary=emp.getInt("salary");  
23.   
24. String str="Employee Name:"+empname+"\n"+"Employee Salary:"+empsalar
y;  
25. textView1.setText(str);  
26.   
27. }catch (Exception e) {e.printStackTrace();}  
28.   
29. }  
30.   
31. }  

Output:

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);  
17.            
18.         String strJson="{ \"Employee\" :[{\"id\":\"101\",\"name\":\"Sonoo Jaiswa
l\",\"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("Employ
ee");  
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").to
String());  
35.                            
36.                         data += "Node"+i+" : \n id= "+ id +" \n Name= "+ name +" \n 
Salary= "+ salary +" \n ";  
37.                       }  
38.                     output.setText(data);  
39.                  } catch (JSONException e) {e.printStackTrace();}  
40.       }  
41. }  

download this example


Output:

Multimedia

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
public void setDataSource(String path)
url) to 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.
seeks to specified time in
public void seekTo(int millis)
miliseconds.
sets the player for looping or non-
public void setLooping(boolean looping)
looping.
checks if the player is looping or
public boolean isLooping()
non-looping.
it selects a track for the specified
public void selectTrack(int index)
index.
public int getCurrentPosition() returns the current playback position.
public int getDuration() returns duration of the file.
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. }  

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/andr
oid"  
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"  
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();  
24.         try{  
25.                 //you can change the path, here path is external directory(e.g. sdcard
) /Music/maine.mp3  
26.         mp.setDataSource(Environment.getExternalStorageDirectory().getPath()
+"/Music/maine.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:
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
controller) video 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 palyback.
public void suspend() suspends the palyback.
public void resume() resumes the palyback.
seeks to specified time in
public void seekTo(int millis)
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/andr
oid"  
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.     <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.                 
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. }  

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/andr
oid"  
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"   
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 {  
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 li
brary.  
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.getNam
e());  
68.         values.put(MediaStore.Audio.Media.DATE_ADDED, (int) (current / 100
0));  
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 avai
lable  
78.         sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN
_FILE, newUri));  
79.         Toast.makeText(this, "Added File " + newUri, Toast.LENGTH_LONG).s
how();  
80.       }  
81.     }   

download this mediarecorder Example

Output:

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
int speak (String text, int
QUEUE_ADD or QUEUE_FLUSH. Request parameters
queueMode, HashMap
can be null, KEY_PARAM_STREAM,
params)
KEY_PARAM_VALUME etc.
int setSpeechRate(float
it sets the speed for the speech.
speed)
int setPitch(float speed) it sets the pitch for the speech.
int setLanguage (Locale
it sets the locale specific language for the speech.
loc)
void shutdown() it releases the resource set by TextToSpeech Engine.
it interrupts the current utterance (whether played or
int stop() rendered to 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
void onInit (int Called to signal the completion of the TextToSpeech engine
status) initialization. The 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/andr
oid"  
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"  
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);  
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  
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. }  

Android TextToSpeech Example


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/andr
oid"  
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"  
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;  
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) {  
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  
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>(th
is,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_s
pinner_dropdown_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 p
osition,  
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. }  

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.
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/andr
oid"  
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;  
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  
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:nam
e="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"  
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 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){  
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).s
how();  
31.                 }  
32.                                   
33.                 if(state==TelephonyManager.CALL_STATE_IDLE){  
34.                     Toast.makeText(getApplicationContext(),"phone is neither ringin
g 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" />  
10.    
11.        
12.        <uses-permission android:nam
e="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>  

Output:
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/andr
oid"  
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.   
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_STAT
E);  
17.   
18.               if(state.equals(TelephonyManager.EXTRA_STATE_RINGING)){  
19.                    Toast.makeText(context, "Phone Is Ringing", Toast.LENGTH_LO
NG).show();  
20.               }  
21.                 
22.               if(state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){  
23.                    Toast.makeText(context, "Call Recieved", Toast.LENGTH_LON
G).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. }  

Android Simple Caller Talker Example


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/andr
oid"  
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;  
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.OnInit
Listener {  
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)getSystem
Service(  
23.                                                                          Context.TELEPHONY_SERVI
CE);  
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_FL
USH, null);  
29.                   Toast.makeText(getApplicationContext(),"Phone is Ringing : "+inc
omingNumber,   
30.                                                                                Toast.LENGTH_LONG).sho
w();  
31.                  }  
32.               if(state==TelephonyManager.CALL_STATE_OFFHOOK){  
33.                     Toast.makeText(getApplicationContext(),"Phone in a call or call 
picked",   
34.                                                                                   Toast.LENGTH_LONG).s
how();  
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) {  
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:nam
e="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" >  
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:

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 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/andr
oid"  
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

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.   
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

Install and Run the apk file on the Real Device (e.g. Mobile) to make the phone
call.

Output:
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/andr
oid"  
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"  
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   
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;  
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.clas
s);  
38.                 PendingIntent pi=PendingIntent.getActivity(getApplicationContext(
), 0, intent,0);  
39.                   
40.                 //Get the SmsManager instance and call the sendTextMessage metho
d to send message  
41.                 SmsManager sms=SmsManager.getDefault();  
42.                 sms.sendTextMessage(no, null, msg, pi,null);  
43.                   
44.                 Toast.makeText(getApplicationContext(), "Message Sent successful
ly!",  
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);  
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:
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/andr
oid"  
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"  
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"  
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) {  
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


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

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/andr
oid"  
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"  
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:nam
e="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" />  
12.     <uses-permission android:nam
e="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  
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.getDefault
Adapter();  
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_RE
QUEST_ENABLE);  
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 DE
VICE DISCOVERABLE",  
45.              Toast.LENGTH_LONG);  
46.   
47.                 Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_RE
QUEST_DISCOVERABLE);  
48.                 startActivityForResult(enableBtIntent, REQUEST_DISCOVERAB
LE_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 BLUETO
OTH", Toast.LENGTH_LONG);  
59.            
60.             }  
61.     });  
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.activity_main, menu);  
68.         return true;  
69.     }  
70.   
71. }  

Android Bluetooth List Paired Devices


Example
The getBoundedDevices() method of BluetoothAdapter class provides a set containg
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/andr
oid"  
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:nam
e="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"  
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:nam
e="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 {  
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 dat
a) {  
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) {  
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_REQU
EST_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. }  

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.

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/andr
oid"  
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;  
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.WIF
I_SERVICE);  
25.                 wifi.setWifiEnabled(true);  
26.             }  
27.         });  
28.         disableButton.setOnClickListener(new OnClickListener(){  
29.             public void onClick(View v){  
30.                 WifiManager wifi = (WifiManager) getSystemService(Context.WIF
I_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. }  

download this android example

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:
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

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/andr
oid"  
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>  
25. </textarae></div>  
26.   
27. <hr/>  
28. <h4 class="h4">Activity class</h4>  
29. <p>Let's write the code to capture image using camera and displaying it on the 
image view.</p>  
30. <div id="filename">File: MainActivity.java</div>  
31. <div class="codeblock"><textarea  name="code" class="java">  
32. package com.example.simplecamera;  
33.   
34. import android.app.Activity;  
35. import android.content.Intent;  
36. import android.graphics.Bitmap;  
37. import android.os.Bundle;  
38. import android.view.Menu;  
39. import android.view.View;  
40. import android.widget.Button;  
41. import android.widget.ImageView;  
42.   
43. public class MainActivity extends Activity {  
44.      private static final int CAMERA_REQUEST = 1888;  
45.      ImageView imageView;  
46.      public void onCreate(Bundle savedInstanceState) {  
47.   
48.          super.onCreate(savedInstanceState);  
49.          setContentView(R.layout.activity_main);  
50.   
51.          imageView = (ImageView) this.findViewById(R.id.imageView1);  
52.          Button photoButton = (Button) this.findViewById(R.id.button1);  
53.   
54.          photoButton.setOnClickListener(new View.OnClickListener() {  
55.   
56.          @Override  
57.          public void onClick(View v) {  
58.               Intent cameraIntent = new Intent(android.provider.MediaStore.ACTI
ON_IMAGE_CAPTURE);  
59.               startActivityForResult(cameraIntent, CAMERA_REQUEST);  
60.          }  
61.         });  
62.        }  
63.   
64.      protected void onActivityResult(int requestCode, int resultCode, Intent data
) {  
65.       if (requestCode == CAMERA_REQUEST) {  
66.        Bitmap photo = (Bitmap) data.getExtras().get("data");  
67.        imageView.setImageBitmap(photo);  
68.       }  
69.    }  
70.   
71.     @Override  
72.     public boolean onCreateOptionsMenu(Menu menu) {  
73.         // Inflate the menu; this adds items to the action bar if it is present.  
74.         getMenuInflater().inflate(R.menu.activity_main, menu);  
75.         return true;  
76.     }  
77.   
78. }  

download this android example

Output:
Android Sensor Tutorial
Sensors can be used to monitor the three-dimensional device movement or change in
the environment of the device.
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.

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_SERVIC
E);  

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 it is called when sensor accuracy is
accuracy) changed.
it is called when sensor values are
void onSensorChanged(SensorEvent event)
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.
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/andr
oid"  
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;  
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).show();  
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

Output:

What is next?

Android Sensor Example


In this example, we are going to create a sensor application that changes the
background color of activity when device is shaked.
For understanding about sensor basics, visit the previous page that provides details
about sensor api.

Android Sensor Example

activity_main.xml

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.    <TextView  
8.         android:id="@+id/textView"  
9.         android:layout_width="match_parent"  
10.         android:layout_height="match_parent"  
11.         android:text="Shake to switch color" />  
12.      
13. </RelativeLayout>  

Activity class

File: MainActivity.java

1. package com.example.sensor;  
2.   
3. import android.app.Activity;  
4. import android.graphics.Color;  
5. import android.hardware.Sensor;  
6. import android.hardware.SensorEvent;  
7. import android.hardware.SensorEventListener;  
8. import android.hardware.SensorManager;  
9. import android.os.Bundle;  
10. import android.view.View;  
11. import android.widget.Toast;  
12.   
13. public class MainActivity extends Activity implements SensorEventListener{  
14.     private SensorManager sensorManager;  
15.       private boolean isColor = false;  
16.       private View view;  
17.       private long lastUpdate;  
18.   
19.       @Override  
20.       public void onCreate(Bundle savedInstanceState) {  
21.         super.onCreate(savedInstanceState);  
22.         setContentView(R.layout.activity_main);  
23.         view = findViewById(R.id.textView);  
24.         view.setBackgroundColor(Color.GREEN);  
25.   
26.         sensorManager = (SensorManager) getSystemService(SENSOR_SERVI
CE);  
27.         lastUpdate = System.currentTimeMillis();  
28.       }  
29.       //overriding two methods of SensorEventListener  
30.       @Override  
31.       public void onAccuracyChanged(Sensor sensor, int accuracy) {}  
32.       @Override  
33.       public void onSensorChanged(SensorEvent event) {  
34.         if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {  
35.           getAccelerometer(event);  
36.         }  
37.   
38.       }  
39.   
40.       private void getAccelerometer(SensorEvent event) {  
41.         float[] values = event.values;  
42.         // Movement  
43.         float x = values[0];  
44.         float y = values[1];  
45.         float z = values[2];  
46.   
47.         float accelationSquareRoot = (x * x + y * y + z * z)  
48.             / (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_
EARTH);  
49.           
50.         long actualTime = System.currentTimeMillis();  
51.         Toast.makeText(getApplicationContext(),String.valueOf(accelationSquar
eRoot)+" "+  
52.                     SensorManager.GRAVITY_EARTH,Toast.LENGTH_SHORT).s
how();  
53.           
54.         if (accelationSquareRoot >= 2) //it will be executed if you shuffle  
55.         {  
56.             
57.           if (actualTime - lastUpdate < 200) {  
58.             return;  
59.           }  
60.           lastUpdate = actualTime;//updating lastUpdate for next shuffle  
61.            if (isColor) {  
62.             view.setBackgroundColor(Color.GREEN);  
63.   
64.           } else {  
65.             view.setBackgroundColor(Color.RED);  
66.           }  
67.           isColor = !isColor;  
68.         }  
69.       }  
70.   
71.       @Override  
72.       protected void onResume() {  
73.         super.onResume();  
74.         // register this class as a listener for the orientation and  
75.         // accelerometer sensors  
76.         sensorManager.registerListener(this,sensorManager.getDefaultSensor(Se
nsor.TYPE_ACCELEROMETER),  
77.                                     SensorManager.SENSOR_DELAY_NORMAL);  
78.       }  
79.   
80.       @Override  
81.       protected void onPause() {  
82.         // unregister listener  
83.         super.onPause();  
84.         sensorManager.unregisterListener(this);  
85.       }  
86.     }   

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/andr
oid"  
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;  
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);  
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:

You might also like