Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
55 views

Android

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views

Android

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 425

Android is a software package and linux based operating system for mobile devices

such as tablet computers and smartphones.

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

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

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

What is Open Handset Alliance (OHA)


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

It was established on 5th November, 2007, led by Google. It is committed to advance


open standards, provide services and deploy handsets using the Android Plateform.

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

1) It is open-source.

2) Anyone can customize the Android Platform.

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

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

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

Categories of Android applications


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

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

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

1) Initially, Andy Rubin founded Android Incorporation in Palo Alto, California,


United States in October, 2003.

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


the subsidiary of Google Incorporation.

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

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

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

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

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


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

Version Code name API Level

1.5 Cupcake 3

1.6 Donut 4

2.1 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

5.0 Lollipop 21

6.0 Marshmallow 23

7.0 Nougat 24-25

8.0 Oreo 26-27


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

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

There are two ways to install android.

1. By ADT Bundle
2. By Setup Eclipse Manually

1) By Android Studio
It is the simplest technique to install required software for android application. It
includes:

o Eclipse IDE
o Android SDK
o Eclipse Plugin

Click me to download android adt bundle

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

If you have downloaded the Android Studio, 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.
Android Architecture
android architecture or Android software stack is categorized into five parts:

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

Let's see the android architecture first.

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

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

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

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

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

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

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

The core building blocks or fundamental components of android are activities,


views, intents, services, content providers, fragments and AndroidManifest.xml.

Activity

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

View

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

Intent

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

o Start the service


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

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

Service

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

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

Content Provider

Content Providers are used to share data between the applications.

Fragment

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

AndroidManifest.xml

It contains informations about activities, content providers, permissions etc. It is like


the web.xml file in Java EE.

Android Virtual Device (AVD)

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

Android Emulator
The Android emulator is an Android Virtual Device (AVD), which represents a
specific Android device. We can use the Android emulator as a target device to
execute and test our Android application on our PC. The Android emulator provides
almost all the functionality of a real device. We can get the incoming phone calls and
text messages. It also gives the location of the device and simulates different network
speeds. Android emulator simulates rotation and other hardware sensors. It accesses
the Google Play store, and much more

Testing Android applications on emulator are sometimes faster and easier than
doing on a real device. For example, we can transfer data faster to the emulator than
to a real device connected through USB.

The Android emulator comes with predefined configurations for several Android
phones, Wear OS, tablet, Android TV devices.

Requirement and recommendations


The Android emulator takes additional requirements beyond the basic system
requirement for Android Studio. These requirements are given below:

o SDK Tools 26.1.1 or higher


o 64-bit processor
o Windows: CPU with UG (unrestricted guest) support
o HAXM 6.2.1 or later (recommended HAXM 7.2.0 or later)

Install the emulator


The Android emulator is installed while installing the Android Studio. However some
components of emulator may or may not be installed while installing Android Studio.
To install the emulator component, select the Android Emulator component in
the SDK Tools tab of the SDK Manager.

Run an Android app on the Emulator


We can run an Android app form the Android Studio project, or we can run an app
which is installed on the Android Emulator as we run any app on a device.

To start the Android Emulator and run an application in our project:

1. In Android Studio, we need to create an Android Virtual Device (AVD) that the
emulator can use to install and run your app. To create a new AVD:-

1.1 Open the AVD Manager by clicking Tools > AVD Manager.

1.2 Click on Create Virtual Device, at the bottom of the AVD Manager dialog.
Then Select Hardware page appears.
1.3 Select a hardware profile and then click Next. If we don?t see the hardware
profile we want, then we can create or import a hardware profile. The System
Image page appears.
1.4 Select the system image for the particular API level and click Next. This leads to
open a Verify Configuration page.

1.5 Change AVD properties if needed, and then click Finish.

2. In the toolbar, choose the AVD, which we want to run our app from the target
device from the drop-down menu.

3. Click Run.
Launch the Emulator without first running
an app
To start the emulator:

1. Open the AVD Manager.


2. Double-click an AVD, or click Run

While the emulator is running, we can run the Android Studio project and select the
emulator as the target device. We can also drag an APKs file to install on an
emulator, and then run them.

Start the emulator from the command line


The Android SDK includes the Android device emulator. Android emulator lets you
develop and test out the application without using a physical device.

Starting the emulator


Using the emulator command, we will start an emulator. It is an alternative to run
our project or start through the AVD Manager.

Here is the basic command-line syntax for starting a virtual device:

1. $ emulator -avd avd_name [ {-option [value]} ... ]

or

1. $ emulator @avd_name [ {-option [value]} ... ]

For example, if we execute the emulator from Android Studio on a Mac, the default
command line will be similar as follows:

1. $ /Users/user_name/Library/Android/sdk/emulator/emulator -avd Nexus_5X_A


PI_23 -netdelay none -netspeed full

To display the list of AVD names, enter the following command:

1. $ emulator -list-avds

Run and stop an emulator, and clear data


From the Virtual Device page, we can perform the following operation on emulator:

o To run an Android emulator that uses an AVD, double-click the AVD, or click Launch
o To stop the running emulator, right-click and select Stop, or click Menu ▼ and select
Stop.
o If we want to clear the data from an emulator and return it to the initial state when it
was first defined, then right-click an AVD and select Wipe Data. Or click menu ▼ and
select Wipe Data.

How to make android apps


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

1. Create the new android project


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

Hello Android Example


You need to follow the 3 steps mentioned above for creating the Hello android
application.
1) Create the New Android project
For creating the new android studio project:

1) Select Start a new Android Studio project

2) Provide the following information: Application name, Company domain, Project


location and Package name of application and click next.
3) Select the API level of application and click next.
4) Select the Activity type (Empty Activity).

5) Provide the Activity Name and click finish.


After finishing the Activity configuration, Android Studio auto generates the activity
class and other required configuration files.

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

2) Write the message


File: activity_main.xml
Android studio auto generates code for activity_main.xml file. You may edit this file
according to your requirement.

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


2. <android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="first.javatpoint.com.welcome.MainActivity">
8.
9. <TextView
10. android:layout_width="wrap_content"
11. android:layout_height="wrap_content"
12. android:text="Hello Android!"
13. app:layout_constraintBottom_toBottomOf="parent"
14. app:layout_constraintLeft_toLeftOf="parent"
15. app:layout_constraintRight_toRightOf="parent"
16. app:layout_constraintTop_toTopOf="parent" />
17.
18. </android.support.constraint.ConstraintLayout>
19. }

File: MainActivity.java

1. package first.javatpoint.com.welcome;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5.
6. public class MainActivity extends AppCompatActivity {
7. @Override
8. protected void onCreate(Bundle savedInstanceState) {
9. super.onCreate(savedInstanceState);
10. setContentView(R.layout.activity_main);
11. }
12. }
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, click the run icon on the toolbar or simply press Shift
+ F10.

The android emulator might take 2 or 3 minutes to boot. So please have patience.
After booting the emulator, the android studio 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 internal details or working of hello android example.

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

Java Source Code

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

File: MainActivity.java

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

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

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

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

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


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

File: activity_main.xml

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

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

File: strings.xml

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


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

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

Generated R.java file

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

File: R.java

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


2. *
3. * This class was automatically generated by the
4. * aapt tool from the resource data it found. It
5. * should not be modified by hand.
6. */
7. package com.example.helloandroid;
8. public final class R {
9. public static final class attr {
10. }
11. public static final class drawable {
12. public static final int ic_launcher=0x7f020000;
13. }
14. public static final class id {
15. public static final int menu_settings=0x7f070000;
16. }
17. public static final class layout {
18. public static final int activity_main=0x7f030000;
19. }
20. public static final class menu {
21. public static final int activity_main=0x7f060000;
22. }
23. public static final class string {
24. public static final int app_name=0x7f040000;
25. public static final int hello_world=0x7f040001;
26. public static final int menu_settings=0x7f040002;
27. }
28. public static final class style {
29. /**
30. Base application theme, dependent on API level. This theme is replaced
31. by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
32. Theme customizations available in newer API levels can go in
33. res/values-vXX/styles.xml, while customizations related to
34. backward-compatibility can go here.
35. Base application theme for API 11+. This theme completely replaces
36. AppBaseTheme from res/values/styles.xml on API 11+ devices.
37. API 11 theme customizations can go here.
38. Base application theme for API 14+. This theme completely replaces
39. AppBaseTheme from BOTH res/values/styles.xml and
40. res/values-v11/styles.xml on API 14+ devices.
41. API 14 theme customizations can go here.
42. */
43. public static final int AppBaseTheme=0x7f050000;
44. /** Application theme.
45. All customizations that are NOT specific to a particular API-level can go here.
46. */
47. public static final int AppTheme=0x7f050001;
48. }
49. }

APK File

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

Resources

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

Manifest file

It contains information about package including components such as activities,


services, content providers etc.

For more information about manifest file visit here: AndroidManifest.xml file.

Dalvik Virtual Machine | DVM


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

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

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

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

Let's see the compiling and packaging process from the source file:
The javac tool compiles the java source file into the class file.

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

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

AndroidManifest.xml file in android


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

It performs some other tasks also:

o It is responsible to protect the application to access any protected parts by


providing the permissions.
o It also declares the android api that the application is going to use.
o It lists the instrumentation classes. The instrumentation classes provides profiling
and other informations. These informations are removed just before the application is
published etc.

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

A simple AndroidManifest.xml file looks like this:


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

Elements of the AndroidManifest.xml file


The elements used in the above xml file are described below.

<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


Android R.java is an auto-generated file by aapt (Android Asset Packaging Tool) that
contains resource IDs for all the resources of res/ directory.
If you create any component in the activity_main.xml file, id for the corresponding
component is automatically created in this file. This id can be used in the activity
source file to perform any action on the component.

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

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

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


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


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

Code that hides title bar of activity


The getSupportActionBar() method is used to retrieve the instance of ActionBar
class. Calling the hide() method of ActionBar class hides the title bar.

1. requestWindowFeature(Window.FEATURE_NO_TITLE);//will hide the title


2. getSupportActionBar().hide(); //hide the title bar
Code that enables full screen mode of activity
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. this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,

2. WindowManager.LayoutParams.FLAG_FULLSCREEN); //show the activity in fu


ll screen
Android Hide Title Bar and Full Screen Example
Let's see the full code to hide the title bar in android.

activity_main.xml
File: activity_main.xml

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


2. <android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="first.javatpoint.com.hidetitlebar.MainActivity">
8.
9. <TextView
10. android:layout_width="wrap_content"
11. android:layout_height="wrap_content"
12. android:text="Hello World!"
13. app:layout_constraintBottom_toBottomOf="parent"
14. app:layout_constraintLeft_toLeftOf="parent"
15. app:layout_constraintRight_toRightOf="parent"
16. app:layout_constraintTop_toTopOf="parent" />
17.
18. </android.support.constraint.ConstraintLayout>

Activity class
File: MainActivity.java

1. package first.javatpoint.com.hidetitlebar;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.Window;
6. import android.view.WindowManager;
7.
8. public class MainActivity extends AppCompatActivity {
9.
10. @Override
11. protected void onCreate(Bundle savedInstanceState) {
12. super.onCreate(savedInstanceState);
13. requestWindowFeature(Window.FEATURE_NO_TITLE); //will hide the title

14. getSupportActionBar().hide(); // hide the title bar


15. this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSC
REEN,
16. WindowManager.LayoutParams.FLAG_FULLSCREEN); //enable full screen
17. setContentView(R.layout.activity_main);
18.
19.
20. }
21. }
Output: Hiding the Title Only
Output: Hiding the TitleBar and enabling FullScreen

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.

Syntax:

1. <activity android:name="package_name.Your_ActivityName"
2. android:screenOrientation="orirntation_type">
3. </activity>

Example:

1. <activity android:name=" example.javatpoint.com.screenorientation.MainActi


vity"
2. android:screenOrientation="portrait">
3. </activity>
1. <activity android:name=".SecondActivity"
2. android:screenOrientation="landscape">
3. </activity>

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 Portrait and Landscape mode


screen orientation example
In this example, we will create two activities of different screen orientation. The first
activity (MainActivity) will be as "portrait" orientation and second activity
(SecondActivity) as "landscape" orientation type.

activity_main.xml
File: activity_main.xml

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


2. <android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.screenorientation.MainActivity">
8.
9.
10. <Button
11. android:id="@+id/button1"
12. android:layout_width="wrap_content"
13. android:layout_height="wrap_content"
14. android:layout_marginBottom="8dp"
15. android:layout_marginTop="112dp"
16. android:onClick="onClick"
17. android:text="Launch next activity"
18. app:layout_constraintBottom_toBottomOf="parent"
19. app:layout_constraintEnd_toEndOf="parent"
20. app:layout_constraintHorizontal_bias="0.612"
21. app:layout_constraintStart_toStartOf="parent"
22. app:layout_constraintTop_toBottomOf="@+id/editText1"
23. app:layout_constraintVertical_bias="0.613" />
24.
25. <TextView
26. android:id="@+id/editText1"
27. android:layout_width="wrap_content"
28. android:layout_height="wrap_content"
29. android:layout_centerHorizontal="true"
30. android:layout_marginEnd="8dp"
31. android:layout_marginStart="8dp"
32. android:layout_marginTop="124dp"
33. android:ems="10"
34. android:textSize="22dp"
35. android:text="This activity is portrait orientation"
36. app:layout_constraintEnd_toEndOf="parent"
37. app:layout_constraintHorizontal_bias="0.502"
38. app:layout_constraintStart_toStartOf="parent"
39. app:layout_constraintTop_toTopOf="parent" />
40. </android.support.constraint.ConstraintLayout>

Activity class
File: MainActivity.java

1. package example.javatpoint.com.screenorientation;
2.
3. import android.content.Intent;
4. import android.support.v7.app.AppCompatActivity;
5. import android.os.Bundle;
6. import android.view.View;
7. import android.widget.Button;
8.
9. public class MainActivity extends AppCompatActivity {
10.
11. Button button1;
12. @Override
13. protected void onCreate(Bundle savedInstanceState) {
14. super.onCreate(savedInstanceState);
15. setContentView(R.layout.activity_main);
16.
17. button1=(Button)findViewById(R.id.button1);
18. }
19. public void onClick(View v) {
20. Intent intent = new Intent(MainActivity.this,SecondActivity.class);
21. startActivity(intent);
22. }
23. }
activity_second.xml
File: activity_second.xml

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


2. <android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.screenorientation.SecondActivity">
8.
9. <TextView
10. android:id="@+id/textView"
11. android:layout_width="wrap_content"
12. android:layout_height="wrap_content"
13. android:layout_marginEnd="8dp"
14. android:layout_marginStart="8dp"
15. android:layout_marginTop="180dp"
16. android:text="this is landscape orientation"
17. android:textSize="22dp"
18. app:layout_constraintEnd_toEndOf="parent"
19. app:layout_constraintHorizontal_bias="0.502"
20. app:layout_constraintStart_toStartOf="parent"
21. app:layout_constraintTop_toTopOf="parent" />
22. </android.support.constraint.ConstraintLayout>
SecondActivity class
File: SecondActivity.java

1. package example.javatpoint.com.screenorientation;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5.
6. public class SecondActivity extends AppCompatActivity {
7.
8. @Override
9. protected void onCreate(Bundle savedInstanceState) {
10. super.onCreate(savedInstanceState);
11. setContentView(R.layout.activity_second);
12.
13. }
14. }
AndroidManifest.xml
File: AndroidManifest.xml

In AndroidManifest.xml file add the screenOrientation attribute in activity and


provides its orientation. In this example, we provide "portrait" orientation for
MainActivity and "landscape" for SecondActivity.

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


2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3. package="example.javatpoint.com.screenorientation">
4.
5. <application
6. android:allowBackup="true"
7. android:icon="@mipmap/ic_launcher"
8. android:label="@string/app_name"
9. android:roundIcon="@mipmap/ic_launcher_round"
10. android:supportsRtl="true"
11. android:theme="@style/AppTheme">
12. <activity
13. android:name="example.javatpoint.com.screenorientation.MainActivity
"
14. android:screenOrientation="portrait">
15. <intent-filter>
16. <action android:name="android.intent.action.MAIN" />
17.
18. <category android:name="android.intent.category.LAUNCHER" />
19. </intent-filter>
20. </activity>
21. <activity android:name=".SecondActivity"
22. android:screenOrientation="landscape">
23. </activity>
24. </application>
25.
26. </manifest>
Output:
Android Widgets
There are given a lot of android widgets with simplified examples such as Button,
EditText, AutoCompleteTextView, ToggleButton, DatePicker, TimePicker, ProgressBar
etc.

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

Android Button

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

Android Toast

Displays information for the short duration of time.

Custom Toast

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

ToggleButton

It has two states ON/OFF.

CheckBox

Let's see the application of simple food ordering.

AlertDialog

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

Spinner

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

AutoCompleteTextView

Let's see the simple example of AutoCompleteTextView.

RatingBar

RatingBar displays the rating bar.


DatePicker

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

TimePicker

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

ProgressBar

ProgressBar displays progress task.

Android Button Example

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


TextView class and CompoundButton is the subclass of Button class.

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


CompoundButton etc.

Android Button Example with Listener


Here, we are going to create two textfields and one button for sum of two numbers.
If user clicks button, sum of two input values is displayed on the Toast.
We can perform action on button using different types such as calling listener on
button or adding onClick property of button in activity's xml file.

1. button.setOnClickListener(new View.OnClickListener() {
2. @Override
3. public void onClick(View view) {
4. //code
5. }
6. });
1. <Button
2. android:onClick="methodName"
3. />
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. <?xml version="1.0" encoding="utf-8"?>


2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.sumoftwonumber.MainActivity">
8.
9. <EditText
10. android:id="@+id/editText1"
11. android:layout_width="wrap_content"
12. android:layout_height="wrap_content"
13. android:layout_alignParentTop="true"
14. android:layout_centerHorizontal="true"
15. android:layout_marginTop="61dp"
16. android:ems="10"
17. android:inputType="number"
18. tools:layout_editor_absoluteX="84dp"
19. tools:layout_editor_absoluteY="53dp" />
20.
21. <EditText
22. android:id="@+id/editText2"
23. android:layout_width="wrap_content"
24. android:layout_height="wrap_content"
25. android:layout_below="@+id/editText1"
26. android:layout_centerHorizontal="true"
27. android:layout_marginTop="32dp"
28. android:ems="10"
29. android:inputType="number"
30. tools:layout_editor_absoluteX="84dp"
31. tools:layout_editor_absoluteY="127dp" />
32.
33. <Button
34. android:id="@+id/button"
35. android:layout_width="wrap_content"
36. android:layout_height="wrap_content"
37. android:layout_below="@+id/editText2"
38. android:layout_centerHorizontal="true"
39. android:layout_marginTop="109dp"
40. android:text="ADD"
41. tools:layout_editor_absoluteX="148dp"
42. tools:layout_editor_absoluteY="266dp" />
43. </RelativeLayout>

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

File: MainActivity.java

1. package example.javatpoint.com.sumoftwonumber;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.widget.Button;
7. import android.widget.EditText;
8. import android.widget.Toast;
9.
10. public class MainActivity extends AppCompatActivity {
11. private EditText edittext1, edittext2;
12. private Button buttonSum;
13.
14. @Override
15. protected void onCreate(Bundle savedInstanceState) {
16. super.onCreate(savedInstanceState);
17. setContentView(R.layout.activity_main);
18.
19. addListenerOnButton();
20. }
21.
22. public void addListenerOnButton() {
23. edittext1 = (EditText) findViewById(R.id.editText1);
24. edittext2 = (EditText) findViewById(R.id.editText2);
25. buttonSum = (Button) findViewById(R.id.button);
26.
27. buttonSum.setOnClickListener(new View.OnClickListener() {
28. @Override
29. public void onClick(View view) {
30. String value1=edittext1.getText().toString();
31. String value2=edittext2.getText().toString();
32. int a=Integer.parseInt(value1);
33. int b=Integer.parseInt(value2);
34. int sum=a+b;
35. Toast.makeText(getApplicationContext(),String.valueOf(sum), Toast.L
ENGTH_LONG).show();
36. }
37. });
38. }
39. }

Output:

Android Toast Example

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

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

You can also create custom toast as well for example toast displaying image. You can
visit next page to see the code for custom toast.
Toast class
Toast class is used to show notification for a particular interval of time. After
sometime it disappears. It doesn't block the user interaction.

Constants of Toast class

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

Constant Description

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

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

Methods of Toast class

The widely used methods of Toast class are given below.

Method Description

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

public void show() displays toast.

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

Android Toast Example


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

Another code:
1. Toast toast=Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.L
ENGTH_SHORT);
2. toast.setMargin(50,50);
3. toast.show();

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

Full code of activity class displaying Toast


Let's see the code to display the toast.

File: MainActivity.java

1. package example.javatpoint.com.toast;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.widget.Toast;
6.
7. public class MainActivity extends AppCompatActivity {
8.
9. @Override
10. protected 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.LENGTH
_SHORT).show();
16. }
17. }
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. <?xml version="1.0" encoding="utf-8"?>


2. <android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.customtoast.MainActivity">
8.
9. <TextView
10. android:layout_width="wrap_content"
11. android:layout_height="wrap_content"
12. android:text="Hello World!"
13. app:layout_constraintBottom_toBottomOf="parent"
14. app:layout_constraintLeft_toLeftOf="parent"
15. app:layout_constraintRight_toRightOf="parent"
16. app:layout_constraintTop_toTopOf="parent" />
17.
18. </android.support.constraint.ConstraintLayout>

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:android="http://schemas.android.com/apk/res/android"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:id="@+id/custom_toast_layout"
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="Hello world"
15. android:src="@drawable/jtp_logo"/>
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="To"
22. android:text="JavaTpoint custom Toast" />
23. </LinearLayout>

Activity class

Now write the code to display the custom toast.

File: MainActivity.java

1. package example.javatpoint.com.customtoast;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.Gravity;
6. import android.view.LayoutInflater;
7. import android.view.View;
8. import android.view.ViewGroup;
9. import android.widget.Toast;
10.
11. public class MainActivity extends AppCompatActivity {
12.
13. @Override
14. protected void onCreate(Bundle savedInstanceState) {
15. super.onCreate(savedInstanceState);
16. setContentView(R.layout.activity_main);
17.
18. //Creating the LayoutInflater instance
19. LayoutInflater li = getLayoutInflater();
20. //Getting the View object as defined in the customtoast.xml file
21. View layout = li.inflate(R.layout.customtoast,(ViewGroup) findViewById(R.i
d.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. }

Output:
Android ToggleButton Example

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


on the button.

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

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

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

Android ToggleButton class


ToggleButton class provides the facility of creating the toggle button.

XML Attributes of ToggleButton class


The 3 XML attributes of ToggleButton class.

XML Attribute Description


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

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

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

Methods of ToggleButton class


The widely used methods of ToggleButton class are given below.

Method Description

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

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

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


checked)

Android ToggleButton Example


activity_main.xml

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

File: activity_main.xml

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


2. <android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.togglebutton.MainActivity">
8.
9. <ToggleButton
10. android:id="@+id/toggleButton"
11. android:layout_width="wrap_content"
12. android:layout_height="wrap_content"
13. android:layout_marginLeft="8dp"
14. android:layout_marginTop="80dp"
15. android:text="ToggleButton"
16. android:textOff="Off"
17. android:textOn="On"
18. app:layout_constraintEnd_toStartOf="@+id/toggleButton2"
19. app:layout_constraintStart_toStartOf="parent"
20. app:layout_constraintTop_toTopOf="parent" />
21.
22. <ToggleButton
23. android:id="@+id/toggleButton2"
24. android:layout_width="wrap_content"
25. android:layout_height="wrap_content"
26. android:layout_marginRight="60dp"
27. android:layout_marginTop="80dp"
28. android:text="ToggleButton"
29. android:textOff="Off"
30. android:textOn="On"
31. app:layout_constraintEnd_toEndOf="parent"
32. app:layout_constraintTop_toTopOf="parent" />
33.
34. <Button
35. android:id="@+id/button"
36. android:layout_width="wrap_content"
37. android:layout_height="wrap_content"
38. android:layout_marginBottom="144dp"
39. android:layout_marginLeft="148dp"
40. android:text="Submit"
41. app:layout_constraintBottom_toBottomOf="parent"
42. app:layout_constraintStart_toStartOf="parent" />
43. </android.support.constraint.ConstraintLayout>
Activity class

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

File: MainActivity.java

1. package example.javatpoint.com.togglebutton;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.widget.Button;
7. import android.widget.Toast;
8. import android.widget.ToggleButton;
9.
10. public class MainActivity extends AppCompatActivity {
11. private ToggleButton toggleButton1, toggleButton2;
12. private Button buttonSubmit;
13. @Override
14. protected void onCreate(Bundle savedInstanceState) {
15. super.onCreate(savedInstanceState);
16. setContentView(R.layout.activity_main);
17.
18. addListenerOnButtonClick();
19. }
20.
21. public void addListenerOnButtonClick(){
22. //Getting the ToggleButton and Button instance from the layout xml file
23. toggleButton1=(ToggleButton)findViewById(R.id.toggleButton);
24. toggleButton2=(ToggleButton)findViewById(R.id.toggleButton2);
25. buttonSubmit=(Button)findViewById(R.id.button);
26.
27. //Performing action on button click
28. buttonSubmit.setOnClickListener(new View.OnClickListener(){
29.
30. @Override
31. public void onClick(View view) {
32. StringBuilder result = new StringBuilder();
33. result.append("ToggleButton1 : ").append(toggleButton1.getText());
34. result.append("\nToggleButton2 : ").append(toggleButton2.getText());
35. //Displaying the message in toast
36. Toast.makeText(getApplicationContext(), result.toString(),Toast.LENGTH_LON
G).show();
37. }
38.
39. });
40.
41. }
42. }

Output:
Android CheckBox Example

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

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

Android CheckBox class is the subclass of CompoundButton class.

Android CheckBox class


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

Methods of CheckBox class

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

Method Description

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

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


Android CheckBox Example
activity_main.xml

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

File: activity_main.xml

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


2. <android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.checkbox.MainActivity">
8.
9.
10. <CheckBox
11. android:id="@+id/checkBox"
12. android:layout_width="wrap_content"
13. android:layout_height="wrap_content"
14. android:layout_marginLeft="144dp"
15. android:layout_marginTop="68dp"
16. android:text="Pizza"
17. app:layout_constraintStart_toStartOf="parent"
18. app:layout_constraintTop_toTopOf="parent" />
19.
20. <CheckBox
21. android:id="@+id/checkBox2"
22. android:layout_width="wrap_content"
23. android:layout_height="wrap_content"
24. android:layout_marginLeft="144dp"
25. android:layout_marginTop="28dp"
26. android:text="Coffee"
27. app:layout_constraintStart_toStartOf="parent"
28. app:layout_constraintTop_toBottomOf="@+id/checkBox" />
29.
30. <CheckBox
31. android:id="@+id/checkBox3"
32. android:layout_width="wrap_content"
33. android:layout_height="wrap_content"
34. android:layout_marginLeft="144dp"
35. android:layout_marginTop="28dp"
36. android:text="Burger"
37. app:layout_constraintStart_toStartOf="parent"
38. app:layout_constraintTop_toBottomOf="@+id/checkBox2" />
39.
40. <Button
41. android:id="@+id/button"
42. android:layout_width="wrap_content"
43. android:layout_height="wrap_content"
44. android:layout_marginLeft="144dp"
45. android:layout_marginTop="184dp"
46. android:text="Order"
47. app:layout_constraintStart_toStartOf="parent"
48. app:layout_constraintTop_toBottomOf="@+id/checkBox3" />
49.
50. </android.support.constraint.ConstraintLayout>

Activity class

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

File: MainActivity.java

1. package example.javatpoint.com.checkbox;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.widget.Button;
7. import android.widget.CheckBox;
8. import android.widget.Toast;
9.
10. public class MainActivity extends AppCompatActivity {
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 file
21. pizza=(CheckBox)findViewById(R.id.checkBox);
22. coffe=(CheckBox)findViewById(R.id.checkBox2);
23. burger=(CheckBox)findViewById(R.id.checkBox3);
24. buttonOrder=(Button)findViewById(R.id.button);
25.
26. //Applying the Listener on the Button click
27. buttonOrder.setOnClickListener(new View.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.LENGTH_LO
NG).show();
49. }
50.
51. });
52. }
53. }

Output:
Android Custom CheckBox
Android provides facility to customize the UI of view elements rather than default.

You are able to create custom CheckBox in android. So, you can add some different
images of checkbox on the layout.

Example of Custom CheckBox


In this example, we create both default as well as custom checkbox. Add the
following code in activity_main.xml file.

activity_main.xml
File: activity_main.xml

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


2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.customcheckbox.MainActivity">
8.
9.
10. <TextView
11. android:id="@+id/textView1"
12. android:layout_width="fill_parent"
13. android:layout_height="wrap_content"
14. android:gravity="center_horizontal"
15. android:textSize="25dp"
16. android:text="Default Check Box"
17. android:layout_alignParentTop="true"
18. android:layout_alignParentLeft="true"
19. android:layout_alignParentStart="true" />
20.
21. <CheckBox
22. android:layout_width="wrap_content"
23. android:layout_height="wrap_content"
24. android:text="New CheckBox"
25. android:id="@+id/checkBox"
26. android:layout_below="@+id/textView1"
27. android:layout_centerHorizontal="true"
28. android:layout_marginTop="46dp" />
29.
30. <CheckBox
31. android:layout_width="wrap_content"
32. android:layout_height="wrap_content"
33. android:text="New CheckBox"
34. android:id="@+id/checkBox2"
35. android:layout_below="@+id/checkBox"
36. android:layout_alignLeft="@+id/checkBox"
37. android:layout_alignStart="@+id/checkBox" />
38.
39. <View
40. android:layout_width="fill_parent"
41. android:layout_height="1dp"
42. android:layout_marginTop="200dp"
43. android:background="#B8B894"
44. android:id="@+id/viewStub" />
45.
46. <CheckBox
47. android:layout_width="wrap_content"
48. android:layout_height="wrap_content"
49. android:text="CheckBox 1"
50. android:id="@+id/checkBox3"
51. android:button="@drawable/customcheckbox"
52. android:layout_below="@+id/viewStub"
53. android:layout_centerHorizontal="true"
54. android:layout_marginTop="58dp" />
55.
56. <CheckBox
57. android:layout_width="wrap_content"
58. android:layout_height="wrap_content"
59. android:text="CheckBox 2"
60. android:id="@+id/checkBox4"
61. android:button="@drawable/customcheckbox"
62. android:layout_below="@+id/checkBox3"
63. android:layout_alignLeft="@+id/checkBox3"
64. android:layout_alignStart="@+id/checkBox3" />
65.
66. <TextView
67. android:layout_width="wrap_content"
68. android:layout_height="wrap_content"
69. android:textAppearance="?android:attr/textAppearanceSmall"
70. android:textSize="25dp"
71. android:text="Custom Check Box"
72. android:id="@+id/textView"
73. android:layout_alignTop="@+id/viewStub"
74. android:layout_centerHorizontal="true" />
75.
76. <Button
77. android:layout_width="wrap_content"
78. android:layout_height="wrap_content"
79. android:text="Show Checked"
80. android:id="@+id/button"
81. android:layout_alignParentBottom="true"
82. android:layout_centerHorizontal="true" />
83.
84. </RelativeLayout>

Now implement a selector in another file (checkbox.xml) under drawable folder


which customizes the checkbox.

checkbox.xml
File: checkbox.xml

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


2. <selector xmlns:android="http://schemas.android.com/apk/res/android">
3. <item android:state_checked="true" android:drawable="@drawable/
checked" />
4. <item android:state_checked="false" android:drawable="@drawable/
unchecked"/>
5. </selector>
Activity class
File: MainActivity.java

1. package example.javatpoint.com.customcheckbox;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.widget.Button;
7. import android.widget.CheckBox;
8. import android.widget.Toast;
9.
10. public class MainActivity extends AppCompatActivity {
11. CheckBox cb1,cb2;
12. Button button;
13. @Override
14. protected void onCreate(Bundle savedInstanceState) {
15. super.onCreate(savedInstanceState);
16. setContentView(R.layout.activity_main);
17. cb1=(CheckBox)findViewById(R.id.checkBox3);
18. cb2=(CheckBox)findViewById(R.id.checkBox4);
19. button=(Button)findViewById(R.id.button);
20.
21. button.setOnClickListener(new View.OnClickListener() {
22. @Override
23. public void onClick(View v) {
24. StringBuilder sb=new StringBuilder("");
25.
26. if(cb1.isChecked()){
27. String s1=cb1.getText().toString();
28. sb.append(s1);
29. }
30.
31. if(cb2.isChecked()){
32. String s2=cb2.getText().toString();
33. sb.append("\n"+s2);
34.
35. }
36. if(sb!=null && !sb.toString().equals("")){
37. Toast.makeText(getApplicationContext(), sb, Toast.LENGTH_LONG
).show();
38.
39. }
40. else{
41. Toast.makeText(getApplicationContext(),"Nothing Selected", Toas
t.LENGTH_LONG).show();
42. }
43.
44. }
45.
46. });
47. }
48. }

Output
Android RadioButton
RadioButton is a two states button which is either checked or unchecked. If a single
radio button is unchecked, we can click it to make checked radio button. Once a
radio button is checked, it cannot be marked as unchecked by user.

RadioButton is generally used with RadioGroup. RadioGroup contains several radio


buttons, marking one radio button as checked makes all other radio buttons as
unchecked.

Example of Radio Button


In this example, we are going to implement single radio button separately as well as
radio button in RadioGroup.
activity_main.xml
File: activity_main.xml

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


2. <LinearLayout
3. xmlns:android="http://schemas.android.com/apk/res/android"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. android:orientation="vertical"
8. tools:context="example.javatpoint.com.radiobutton.MainActivity">
9.
10. <TextView
11. android:id="@+id/textView1"
12. android:layout_width="fill_parent"
13. android:layout_height="wrap_content"
14. android:layout_marginTop="30dp"
15. android:gravity="center_horizontal"
16. android:textSize="22dp"
17. android:text="Single Radio Buttons" />
18.
19.
20.
21. <!-- Default RadioButtons -->
22.
23. <RadioButton
24. android:id="@+id/radioButton1"
25. android:layout_width="fill_parent"
26. android:layout_height="wrap_content"
27. android:layout_gravity="center_horizontal"
28. android:text="Radio Button 1"
29. android:layout_marginTop="20dp"
30.
31. android:textSize="20dp" />
32. <RadioButton
33. android:id="@+id/radioButton2"
34. android:layout_width="fill_parent"
35. android:layout_height="wrap_content"
36. android:text="Radio Button 2"
37. android:layout_marginTop="10dp"
38.
39. android:textSize="20dp" />
40.
41.
42. <View
43. android:layout_width="fill_parent"
44. android:layout_height="1dp"
45. android:layout_marginTop="20dp"
46. android:background="#B8B894" />
47.
48. <TextView
49. android:id="@+id/textView2"
50. android:layout_width="fill_parent"
51. android:layout_height="wrap_content"
52. android:layout_marginTop="30dp"
53. android:gravity="center_horizontal"
54. android:textSize="22dp"
55. android:text="Radio button inside RadioGroup" />
56.
57.
58. <!-- Customized RadioButtons -->
59.
60.
61. <RadioGroup
62. android:layout_width="wrap_content"
63. android:layout_height="wrap_content"
64. android:id="@+id/radioGroup">
65.
66. <RadioButton
67. android:id="@+id/radioMale"
68. android:layout_width="fill_parent"
69. android:layout_height="wrap_content"
70. android:text=" Male"
71. android:layout_marginTop="10dp"
72. android:checked="false"
73. android:textSize="20dp" />
74.
75. <RadioButton
76. android:id="@+id/radioFemale"
77. android:layout_width="fill_parent"
78. android:layout_height="wrap_content"
79. android:text=" Female"
80. android:layout_marginTop="20dp"
81. android:checked="false"
82.
83. android:textSize="20dp" />
84. </RadioGroup>
85.
86. <Button
87. android:layout_width="wrap_content"
88. android:layout_height="wrap_content"
89. android:text="Show Selected"
90. android:id="@+id/button"
91. android:onClick="onclickbuttonMethod"
92. android:layout_gravity="center_horizontal" />
93.
94.
95. </LinearLayout>
Activity class
File: MainActivity.java

1. package example.javatpoint.com.radiobutton;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.widget.Button;
7. import android.widget.RadioButton;
8. import android.widget.RadioGroup;
9. import android.widget.Toast;
10.
11. public class MainActivity extends AppCompatActivity {
12. Button button;
13. RadioButton genderradioButton;
14. RadioGroup radioGroup;
15. @Override
16. protected void onCreate(Bundle savedInstanceState) {
17. super.onCreate(savedInstanceState);
18. setContentView(R.layout.activity_main);
19. radioGroup=(RadioGroup)findViewById(R.id.radioGroup);
20. }
21. public void onclickbuttonMethod(View v){
22. int selectedId = radioGroup.getCheckedRadioButtonId();
23. genderradioButton = (RadioButton) findViewById(selectedId);
24. if(selectedId==-1){
25. Toast.makeText(MainActivity.this,"Nothing selected", Toast.LENGTH_S
HORT).show();
26. }
27. else{
28. Toast.makeText(MainActivity.this,genderradioButton.getText(), Toast.LENGTH_S
HORT).show();
29. }
30.
31. }
32. }

Output
Android Dynamic RadioButton
Instead of creating RadioButton through drag and drop from palette, android also
facilitates you to create it programmatically (dynamically). For creating dynamic
RadioButton, we need to use android.view.ViewGroup.LayoutParams which
configures the width and height of views and
implements setOnCheckedChangeListener() method of RadioGroup class.

Example of Dynamic RadioButton


Let's see an example of Dynamic RadioButton.

activity_main.xml
File: activity_main.xml

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


2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. xmlns:tools="http://schemas.android.com/tools"
4. android:layout_width="match_parent"
5. android:layout_height="match_parent"
6. android:paddingBottom="@dimen/activity_vertical_margin"
7. android:paddingLeft="@dimen/activity_horizontal_margin"
8. android:paddingRight="@dimen/activity_horizontal_margin"
9. android:paddingTop="@dimen/activity_vertical_margin"
10. android:id="@+id/relativeLayout"
11. tools:context="com.example.test.dynamicradiobutton.MainActivity">
12.
13. </RelativeLayout>
Activity class
File: MainActivity.java

1. package com.example.test.dynamicradiobutton;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.widget.RadioButton;
6. import android.widget.RadioGroup;
7. import android.widget.RelativeLayout;
8.
9. import android.widget.RelativeLayout.LayoutParams;
10. import android.widget.Toast;
11.
12. public class MainActivity extends AppCompatActivity {
13. RadioGroup rg;
14. RelativeLayout rl;
15. RadioButton rb1,rb2;
16.
17. @Override
18. protected void onCreate(Bundle savedInstanceState) {
19. super.onCreate(savedInstanceState);
20. setContentView(R.layout.activity_main);
21.
22. rg = new RadioGroup(this);
23. rl = (RelativeLayout) findViewById(R.id.relativeLayout);
24. rb1 = new RadioButton(this);
25. rb2 = new RadioButton(this);
26.
27. rb1.setText("Male");
28. rb2.setText("Female");
29. rg.addView(rb1);
30. rg.addView(rb2);
31. rg.setOrientation(RadioGroup.HORIZONTAL);
32.
33. RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParam
s((int) LayoutParams.WRAP_CONTENT,(int)LayoutParams.WRAP_CONTENT);
34. params.leftMargin =150;
35. params.topMargin = 100;
36.
37. rg.setLayoutParams(params);
38. rl.addView(rg);
39.
40. rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

41. @Override
42. public void onCheckedChanged(RadioGroup group, int checkedId) {
43. RadioButton radioButton = (RadioButton) findViewById(checkedId);
44. Toast.makeText(getApplicationContext(),radioButton.getText(),Toast.LENGTH
_LONG).show();
45. }
46. });
47. }
48. }
Android Custom RadioButton
Rather than default user interface of android RadioButton, we can also implement a
custom radio button. Custom RadioButton makes user interface more attractive.

Example of Custom RadioButton


Let's see an example of custom RadioButton.

activity_main.xml
File: activity_main.xml

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


2. <LinearLayout
3. xmlns:android="http://schemas.android.com/apk/res/android"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. android:paddingBottom="@dimen/activity_vertical_margin"
8. android:paddingLeft="@dimen/activity_horizontal_margin"
9. android:paddingRight="@dimen/activity_horizontal_margin"
10. android:paddingTop="@dimen/activity_vertical_margin"
11. android:orientation="vertical"
12. tools:context="com.example.test.customradiobutton.MainActivity">
13.
14.
15.
16. <TextView
17. android:id="@+id/tv"
18. android:layout_width="fill_parent"
19. android:layout_height="wrap_content"
20. android:layout_marginTop="30dp"
21. android:gravity="center_horizontal"
22. android:textSize="25dp"
23. android:text="Customized Radio Buttons" />
24.
25.
26. <!-- Customized RadioButtons -->
27.
28.
29. <RadioGroup
30. android:layout_width="wrap_content"
31. android:layout_height="wrap_content"
32. android:id="@+id/radioGroup">
33.
34. <RadioButton
35. android:id="@+id/radioMale"
36. android:layout_width="fill_parent"
37. android:layout_height="wrap_content"
38. android:text=" Male"
39. android:layout_marginTop="10dp"
40. android:checked="false"
41. android:button="@drawable/custom_radio_button"
42. android:textSize="20dp" />
43.
44. <RadioButton
45. android:id="@+id/radioFemale"
46. android:layout_width="fill_parent"
47. android:layout_height="wrap_content"
48. android:text=" Female"
49. android:layout_marginTop="20dp"
50. android:checked="false"
51. android:button="@drawable/custom_radio_button"
52. android:textSize="20dp" />
53. </RadioGroup>
54.
55. <Button
56. android:layout_width="wrap_content"
57. android:layout_height="wrap_content"
58. android:text="Show Selected"
59. android:id="@+id/button"
60. android:onClick="onclickbuttonMethod"
61. android:layout_gravity="center_horizontal" />
62.
63. </LinearLayout>
custom_radio_button.xml
Now implement a selector in another file (custom_radio_button.xml) in drawable and
place two different checked and unchecked button images.

File: checkbox.xml

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


2.
3. <selector xmlns:android="http://schemas.android.com/apk/res/android">
4.
5. <item android:state_checked="true" android:drawable="@drawable/
checkedradiobutton" />
6. <item android:state_checked="false" android:drawable="@drawable/
unchekedradiobutton" />
7.
8. </selector>
Activity class
File: MainActivity.java

1. package com.example.test.customradiobutton;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.widget.Button;
7. import android.widget.RadioButton;
8. import android.widget.RadioGroup;
9. import android.widget.Toast;
10.
11. public class MainActivity extends AppCompatActivity {
12. Button button;
13. RadioButton genderradioButton;
14. RadioGroup radioGroup;
15. @Override
16. protected void onCreate(Bundle savedInstanceState) {
17. super.onCreate(savedInstanceState);
18. setContentView(R.layout.activity_main);
19.
20. radioGroup=(RadioGroup)findViewById(R.id.radioGroup);
21. }
22.
23.
24. public void onclickbuttonMethod(View v){
25. int selectedId = radioGroup.getCheckedRadioButtonId();
26. genderradioButton = (RadioButton) findViewById(selectedId);
27. if(selectedId==-1){
28. Toast.makeText(MainActivity.this,"Nothing selected", Toast.LENGTH_SHORT).sh
ow();
29. }
30. else{
31. Toast.makeText(MainActivity.this,genderradioButton.getText(), Toast.LE
NGTH_SHORT).show();
32. }
33.
34. }
35. }

Output
Android AlertDialog Example

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

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

Android AlertDialog is the subclass of Dialog class.

Methods of AlertDialog class


Method Description

public AlertDialog.Builder This method is used to set the title of


setTitle(CharSequence) AlertDialog.

public AlertDialog.Builder This method is used to set the message


setMessage(CharSequence) for AlertDialog.

public AlertDialog.Builder setIcon(int) This method is used to set the icon over
AlertDialog.

Android AlertDialog Example


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

activity_main.xml

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

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


2. <android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.alertdialog.MainActivity">
8.
9. <Button
10. android:layout_width="wrap_content"
11. android:layout_height="wrap_content"
12. android:id="@+id/button"
13. android:text="Close app"
14. app:layout_constraintBottom_toBottomOf="parent"
15. app:layout_constraintLeft_toLeftOf="parent"
16. app:layout_constraintRight_toRightOf="parent"
17. app:layout_constraintTop_toTopOf="parent" />
18.
19. </android.support.constraint.ConstraintLayout>

strings.xml

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

File: strings.xml

1. <resources>
2. <string name="app_name">AlertDialog</string>
3. <string name="dialog_message">Welcome to Alert Dialog</string>
4. <string name="dialog_title">Javatpoint Alert Dialog</string>
5. </resources>

Activity class

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


File: MainActivity.java

1. package example.javatpoint.com.alertdialog;
2.
3. import android.content.DialogInterface;
4. import android.support.v7.app.AppCompatActivity;
5. import android.os.Bundle;
6. import android.view.View;
7. import android.widget.Button;
8. import android.app.AlertDialog;
9. import android.widget.Toast;
10.
11. public class MainActivity extends AppCompatActivity {
12. Button closeButton;
13. AlertDialog.Builder builder;
14. @Override
15. protected void onCreate(Bundle savedInstanceState) {
16. super.onCreate(savedInstanceState);
17. setContentView(R.layout.activity_main);
18.
19. closeButton = (Button) findViewById(R.id.button);
20. builder = new AlertDialog.Builder(this);
21. closeButton.setOnClickListener(new View.OnClickListener() {
22. @Override
23. public void onClick(View v) {
24.
25. //Uncomment the below code to Set the message and title from the
strings.xml file
26. builder.setMessage(R.string.dialog_message) .setTitle(R.string.dialog_title);
27.
28. //Setting message manually and performing action on button click
29. builder.setMessage("Do you want to close this application ?")
30. .setCancelable(false)
31. .setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
32. public void onClick(DialogInterface dialog, int id) {
33. finish();
34. Toast.makeText(getApplicationContext(),"you choose yes action fo
r alertbox",
35. Toast.LENGTH_SHORT).show();
36. }
37. })
38. .setNegativeButton("No", new DialogInterface.OnClickListener() {
39. public void onClick(DialogInterface dialog, int id) {
40. // Action for 'NO' Button
41. dialog.cancel();
42. Toast.makeText(getApplicationContext(),"you choose no action for
alertbox",
43. Toast.LENGTH_SHORT).show();
44. }
45. });
46. //Creating dialog box
47. AlertDialog alert = builder.create();
48. //Setting the title manually
49. alert.setTitle("AlertDialogExample");
50. alert.show();
51. }
52. });
53. }
54. }
Output:
Android Spinner Example

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

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

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

Android Spinner class is the subclass of AsbSpinner class.

Android Spinner Example


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

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

activity_main.xml

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

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


2. <android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.spinner.MainActivity">
8.
9. <Spinner
10. android:id="@+id/spinner"
11. android:layout_width="149dp"
12. android:layout_height="40dp"
13. android:layout_marginBottom="8dp"
14. android:layout_marginEnd="8dp"
15. android:layout_marginStart="8dp"
16. android:layout_marginTop="8dp"
17. app:layout_constraintBottom_toBottomOf="parent"
18. app:layout_constraintEnd_toEndOf="parent"
19. app:layout_constraintHorizontal_bias="0.502"
20. app:layout_constraintStart_toStartOf="parent"
21. app:layout_constraintTop_toTopOf="parent"
22. app:layout_constraintVertical_bias="0.498" />
23.
24. </android.support.constraint.ConstraintLayout>

Activity class

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

File: MainActivity.java

1. package example.javatpoint.com.spinner;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.widget.AdapterView;
7. import android.widget.ArrayAdapter;
8. import android.widget.Spinner;
9. import android.widget.Toast;
10.
11. public class MainActivity extends AppCompatActivity implements
12. AdapterView.OnItemSelectedListener {
13. String[] country = { "India", "USA", "China", "Japan", "Other"};
14.
15. @Override
16. protected void onCreate(Bundle savedInstanceState) {
17. super.onCreate(savedInstanceState);
18. setContentView(R.layout.activity_main);
19. //Getting the instance of Spinner and applying OnItemSelectedListener o
n it
20. Spinner spin = (Spinner) findViewById(R.id.spinner);
21. spin.setOnItemSelectedListener(this);
22.
23. //Creating the ArrayAdapter instance having the country list
24. ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,
country);
25. aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdow
n_item);
26. //Setting the ArrayAdapter data on the Spinner
27. spin.setAdapter(aa);
28.
29. }
30.
31. //Performing action onItemSelected and onNothing selected
32. @Override
33. public void onItemSelected(AdapterView<?> arg0, View arg1, int position,
long id) {
34. Toast.makeText(getApplicationContext(),country[position] , Toast.LENGTH_LONG)
.show();
35. }
36. @Override
37. public void onNothingSelected(AdapterView<?> arg0) {
38. // TODO Auto-generated method stub
39. }
40. }
Output:
Android AutoCompleteTextView
Example

Android AutoCompleteTextView completes the word based on the reserved words,


so no need to write all the characters of the word.

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


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

Android AutoCompleteTextView is the subclass of EditText class. The


MultiAutoCompleteTextView is the subclass of AutoCompleteTextView class.

Android AutoCompleteTextView Example


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

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


activity_main.xml

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

File: activity_main.xml

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


2. <android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.autocompletetextview.MainActivity"
>
8.
9. <TextView
10. android:layout_width="wrap_content"
11. android:layout_height="wrap_content"
12. android:text="What is your favourite programming language?"
13. app:layout_constraintBottom_toBottomOf="parent"
14. app:layout_constraintLeft_toLeftOf="parent"
15. app:layout_constraintRight_toRightOf="parent"
16. app:layout_constraintTop_toTopOf="parent"
17. app:layout_constraintVertical_bias="0.032" />
18.
19. <AutoCompleteTextView
20. android:id="@+id/autoCompleteTextView"
21. android:layout_width="200dp"
22. android:layout_height="wrap_content"
23. android:layout_marginLeft="92dp"
24. android:layout_marginTop="144dp"
25. android:text=""
26. app:layout_constraintStart_toStartOf="parent"
27. app:layout_constraintTop_toTopOf="parent" />
28.
29. </android.support.constraint.ConstraintLayout>
Activity class

Let's write the code of AutoCompleteTextView.

File: MainActivity.java

1. package example.javatpoint.com.autocompletetextview;
2.
3. import android.graphics.Color;
4. import android.support.v7.app.AppCompatActivity;
5. import android.os.Bundle;
6. import android.widget.ArrayAdapter;
7. import android.widget.AutoCompleteTextView;
8.
9. public class MainActivity extends AppCompatActivity {
10. String[] language ={"C","C++","Java",".NET","iPhone","Android","ASP.NET","PHP"};
11. @Override
12. protected void onCreate(Bundle savedInstanceState) {
13. super.onCreate(savedInstanceState);
14. setContentView(R.layout.activity_main);
15. //Creating the instance of ArrayAdapter containing list of language name
s
16. ArrayAdapter<String> adapter = new ArrayAdapter<String>
17. (this,android.R.layout.select_dialog_item,language);
18. //Getting the instance of AutoCompleteTextView
19. AutoCompleteTextView actv = (AutoCompleteTextView)findViewById(R.i
d.autoCompleteTextView);
20. actv.setThreshold(1);//will start working from first character
21. actv.setAdapter(adapter);//setting the adapter data into the AutoComplet
eTextView
22. actv.setTextColor(Color.RED);
23. }
24. }
Output:

Android ListView
Android ListView is a view which contains the group of items and displays in a
scrollable list. ListView is implemented by importing android.widget.ListView class.
ListView is a default scrollable which does not use other scroll view.

ListView uses Adapter classes which add the content from data source (such as string
array, array, database etc) to ListView. Adapter bridges data between
an AdapterViews and other Views (ListView, ScrollView etc).

Example of ListView
Let's implement a simple listview example.

Structure of listview project


activity_main.xml
First we need to drag and drop ListView component from palette to activity_main.xml
file.

File: activity_main.xml

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


2. <android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="listview.example.com.listview.MainActivity">
8.
9. <ListView
10. android:id="@+id/listView"
11. android:layout_width="match_parent"
12. android:layout_height="fill_parent"
13. />
14. </android.support.constraint.ConstraintLayout>

Create an additional mylist.xml file in layout folder which contains view components
displayed in listview.

mylist.xml
File: mylist.xml

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


2.
3. <TextView xmlns:android="http://schemas.android.com/apk/res/android"
4. android:id="@+id/textView"
5. android:layout_width="wrap_content"
6. android:layout_height="wrap_content"
7. android:text="Medium Text"
8. android:textStyle="bold"
9. android:textAppearance="?android:attr/textAppearanceMedium"
10. android:layout_marginLeft="10dp"
11. android:layout_marginTop="5dp"
12. android:padding="2dp"
13. android:textColor="#4d4d4d"
14. />

Now place the list of data in strings.xml file by creating string-array.

strings.xml
File:strings.xml

1. <resources>
2. <string name="app_name">ListView</string>
3. <string-array name="array_technology">
4. <item>Android</item>
5. <item>Java</item>
6. <item>Php</item>
7. <item>Hadoop</item>
8. <item>Sap</item>
9. <item>Python</item>
10. <item>Ajax</item>
11. <item>C++</item>
12. <item>Ruby</item>
13. <item>Rails</item>
14. <item>.Net</item>
15. <item>Perl</item>
16. </string-array>
17. </resources>
Activity class
In java class we need to add adapter to listview using setAdapter() method of
listview.

File: MainActivity.java

1. package listview.example.com.listview;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.widget.AdapterView;
7. import android.widget.ArrayAdapter;
8. import android.widget.ListView;
9. import android.widget.TextView;
10. import android.widget.Toast;
11.
12. public class MainActivity extends AppCompatActivity {
13. ListView listView;
14. TextView textView;
15. String[] listItem;
16. @Override
17. protected void onCreate(Bundle savedInstanceState) {
18. super.onCreate(savedInstanceState);
19. setContentView(R.layout.activity_main);
20.
21. listView=(ListView)findViewById(R.id.listView);
22. textView=(TextView)findViewById(R.id.textView);
23. listItem = getResources().getStringArray(R.array.array_technology);
24. final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
25. android.R.layout.simple_list_item_1, android.R.id.text1, listItem);
26. listView.setAdapter(adapter);
27.
28. listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
29. @Override
30. public void onItemClick(AdapterView<?> adapterView, View view, int positio
n, long l) {
31. // TODO Auto-generated method stub
32. String value=adapter.getItem(position);
33. Toast.makeText(getApplicationContext(),value,Toast.LENGTH_SHORT
).show();
34.
35. }
36. });
37. }
38. }

Output
Android Custom ListView (Adding
Images, sub-title)
After creating simple ListView, android also provides facilities to customize our
ListView.

As the simple ListView, custom ListView also uses Adapter classes which added the
content from data source (such as string array, array, database etc). Adapter bridges
data between an AdapterViews and other Views

Example of Custom ListView


In this custom listview example, we are adding image, text with title and its sub-title.

Structure of custom listview project

activity_main.xml
Create an activity_main.xml file in layout folder.

File: activity_main.xml

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


2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. xmlns:tools="http://schemas.android.com/tools"
4. android:layout_width="match_parent"
5. android:layout_height="match_parent"
6. android:paddingBottom="@dimen/activity_vertical_margin"
7. android:paddingLeft="@dimen/activity_horizontal_margin"
8. android:paddingRight="@dimen/activity_horizontal_margin"
9. android:paddingTop="@dimen/activity_vertical_margin"
10. tools:context="com.example.test.listviewwithimage.MainActivity">
11.
12. <ListView
13. android:id="@+id/list"
14. android:layout_width="match_parent"
15. android:layout_height="wrap_content"
16. android:layout_marginBottom="50dp">
17. </ListView>
18. </RelativeLayout>

Create an additional mylist.xml file in layout folder which contains view components
displayed in listview.

mylist.xml
File: mylist.xml

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


2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:orientation="horizontal" >
6.
7. <ImageView
8. android:id="@+id/icon"
9. android:layout_width="60dp"
10. android:layout_height="60dp"
11. android:padding="5dp" />
12.
13. <LinearLayout android:layout_width="wrap_content"
14. android:layout_height="wrap_content"
15. android:orientation="vertical">
16.
17. <TextView
18. android:id="@+id/title"
19. android:layout_width="wrap_content"
20. android:layout_height="wrap_content"
21. android:text="Medium Text"
22. android:textStyle="bold"
23. android:textAppearance="?android:attr/textAppearanceMedium"
24. android:layout_marginLeft="10dp"
25. android:layout_marginTop="5dp"
26. android:padding="2dp"
27. android:textColor="#4d4d4d" />
28. <TextView
29. android:id="@+id/subtitle"
30. android:layout_width="wrap_content"
31. android:layout_height="wrap_content"
32. android:text="TextView"
33. android:layout_marginLeft="10dp"/>
34. </LinearLayout>
35. </LinearLayout>

Place the all required images in drawable folder.

Activity class
File: MainActivity.java

1. package com.example.test.listviewwithimage;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.widget.AdapterView;
7. import android.widget.ListView;
8. import android.widget.Toast;
9.
10. public class MainActivity extends AppCompatActivity {
11. ListView list;
12.
13. String[] maintitle ={
14. "Title 1","Title 2",
15. "Title 3","Title 4",
16. "Title 5",
17. };
18.
19. String[] subtitle ={
20. "Sub Title 1","Sub Title 2",
21. "Sub Title 3","Sub Title 4",
22. "Sub Title 5",
23. };
24.
25. Integer[] imgid={
26. R.drawable.download_1,R.drawable.download_2,
27. R.drawable.download_3,R.drawable.download_4,
28. R.drawable.download_5,
29. };
30. @Override
31. protected void onCreate(Bundle savedInstanceState) {
32. super.onCreate(savedInstanceState);
33. setContentView(R.layout.activity_main);
34.
35. MyListAdapter adapter=new MyListAdapter(this, maintitle, subtitle,imgid
);
36. list=(ListView)findViewById(R.id.list);
37. list.setAdapter(adapter);
38.
39.
40. list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
41.
42. @Override
43. public void onItemClick(AdapterView<?> parent, View view,int positio
n, long id) {
44. // TODO Auto-generated method stub
45. if(position == 0) {
46. //code specific to first list item
47. Toast.makeText(getApplicationContext(),"Place Your First Option
Code",Toast.LENGTH_SHORT).show();
48. }
49.
50. else if(position == 1) {
51. //code specific to 2nd list item
52. Toast.makeText(getApplicationContext(),"Place Your Second Option Code
",Toast.LENGTH_SHORT).show();
53. }
54.
55. else if(position == 2) {
56.
57. Toast.makeText(getApplicationContext(),"Place Your Third Option
Code",Toast.LENGTH_SHORT).show();
58. }
59. else if(position == 3) {
60.
61. Toast.makeText(getApplicationContext(),"Place Your Forth Option
Code",Toast.LENGTH_SHORT).show();
62. }
63. else if(position == 4) {
64.
65. Toast.makeText(getApplicationContext(),"Place Your Fifth Option
Code",Toast.LENGTH_SHORT).show();
66. }
67.
68. }
69. });
70. }
71. }

Customize Our ListView


Create another java class MyListView.java which extends ArrayAdapter class. This
class customizes our listview.

MyListView.java
1. package com.example.test.listviewwithimage;
2.
3. import android.app.Activity;
4.
5. import android.view.LayoutInflater;
6. import android.view.View;
7. import android.view.ViewGroup;
8. import android.widget.ArrayAdapter;
9. import android.widget.ImageView;
10. import android.widget.TextView;
11.
12. public class MyListAdapter extends ArrayAdapter<String> {
13.
14. private final Activity context;
15. private final String[] maintitle;
16. private final String[] subtitle;
17. private final Integer[] imgid;
18.
19. public MyListAdapter(Activity context, String[] maintitle,String[] subtitle, Int
eger[] imgid) {
20. super(context, R.layout.mylist, maintitle);
21. // TODO Auto-generated constructor stub
22.
23. this.context=context;
24. this.maintitle=maintitle;
25. this.subtitle=subtitle;
26. this.imgid=imgid;
27.
28. }
29.
30. public View getView(int position,View view,ViewGroup parent) {
31. LayoutInflater inflater=context.getLayoutInflater();
32. View rowView=inflater.inflate(R.layout.mylist, null,true);
33.
34. TextView titleText = (TextView) rowView.findViewById(R.id.title);
35. ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
36. TextView subtitleText = (TextView) rowView.findViewById(R.id.subtitle);
37.
38. titleText.setText(maintitle[position]);
39. imageView.setImageResource(imgid[position]);
40. subtitleText.setText(subtitle[position]);
41.
42. return rowView;
43.
44. };
45. }

Output
Android RatingBar Example

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

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

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

Android RatingBar Example


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. <?xml version="1.0" encoding="utf-8"?>


2. <android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.ratingbar.MainActivity">
8.
9. <Button
10. android:layout_width="wrap_content"
11. android:layout_height="wrap_content"
12. android:text="submit"
13. android:id="@+id/button"
14. app:layout_constraintBottom_toBottomOf="parent"
15. app:layout_constraintLeft_toLeftOf="parent"
16. app:layout_constraintRight_toRightOf="parent"
17. app:layout_constraintTop_toTopOf="parent"
18. app:layout_constraintVertical_bias="0.615" />
19.
20. <RatingBar
21. android:id="@+id/ratingBar"
22. android:layout_width="wrap_content"
23. android:layout_height="wrap_content"
24. android:layout_marginLeft="72dp"
25. android:layout_marginTop="60dp"
26. app:layout_constraintStart_toStartOf="parent"
27. app:layout_constraintTop_toTopOf="parent" />
28.
29. </android.support.constraint.ConstraintLayout>

Activity class

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

File: MainActivity.java

1. package example.javatpoint.com.ratingbar;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.widget.Button;
7. import android.widget.RatingBar;
8. import android.widget.Toast;
9.
10. public class MainActivity extends AppCompatActivity {
11. RatingBar ratingbar;
12. Button button;
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. ratingbar=(RatingBar)findViewById(R.id.ratingBar);
21. button=(Button)findViewById(R.id.button);
22. //Performing action on Button Click
23. button.setOnClickListener(new View.OnClickListener(){
24.
25. @Override
26. public void onClick(View arg0) {
27. //Getting the rating and displaying it on the toast
28. String rating=String.valueOf(ratingbar.getRating());
29. Toast.makeText(getApplicationContext(), rating, Toast.LENGTH_LON
G).show();
30. }
31.
32. });
33. }
34. }
Output:
Android WebView Example

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

Android WebView uses webkit engine to display web page.

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

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

Android WebView Example


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

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


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

Let's see the simple code to display HTML web page using web view. In this case,
html file must be located inside the asset directory.
1. WebView mywebview = (WebView) findViewById(R.id.webView1);
2. mywebview.loadUrl("file:///android_asset/myresource.html");

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

1. String data = "<html><body><h1>Hello, Javatpoint!</h1></body></


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

Complete Android WebView Example


Let's see a complete example of Android WebView.

activity_main.xml
File: activity_main.xml

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


2. <android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.webview.MainActivity">
8.
9. <WebView
10. android:layout_width="match_parent"
11. android:layout_height="match_parent"
12. android:id="@+id/webView"
13. app:layout_constraintBottom_toBottomOf="parent"
14. app:layout_constraintLeft_toLeftOf="parent"
15. app:layout_constraintRight_toRightOf="parent"
16. app:layout_constraintTop_toTopOf="parent" />
17.
18. </android.support.constraint.ConstraintLayout>

To add the web page (.html, .jsp) locally in application, they are required to place in
the assets folder. An assets folder is created as: right click on app -> New -> Folder -
> Assets Folder ->main or simply create an assets directory inside main directory.
Activity class
File: MainActivity.java

1. package example.javatpoint.com.webview;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.webkit.WebView;
6.
7. public class MainActivity extends AppCompatActivity {
8.
9. @Override
10. protected void onCreate(Bundle savedInstanceState) {
11. super.onCreate(savedInstanceState);
12. setContentView(R.layout.activity_main);
13. WebView mywebview = (WebView) findViewById(R.id.webView);
14. // mywebview.loadUrl("https://www.javatpoint.com/");
15.
16. /*String data = "<html><body><h1>Hello, Javatpoint!</h1></body></html>";
17. mywebview.loadData(data, "text/html", "UTF-8"); */
18.
19. mywebview.loadUrl("file:///android_asset/myresource.html");
20. }
21. }

Output:

Let's see the output if you load the HTML page.


Let's see the output if you load the javatpoint.com web page.
Android SeekBar Example
Android SeekBar is a kind of ProgressBar with draggable thumb. The end user can
drag the thum left and right to move the progress of song, file download etc.

The SeekBar.OnSeekBarChangeListener interface provides methods to perform even


handling for seek bar.

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

Android SeekBar Example


activity_main.xml

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

File: activity_main.xml

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


2. <android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.seekbar.MainActivity">
8.
9.
10. <SeekBar
11. android:id="@+id/seekBar"
12. android:layout_width="match_parent"
13. android:layout_height="wrap_content"
14. android:layout_marginEnd="8dp"
15. android:layout_marginStart="8dp"
16. android:layout_marginTop="372dp"
17. app:layout_constraintEnd_toEndOf="parent"
18. app:layout_constraintStart_toStartOf="parent"
19. app:layout_constraintTop_toTopOf="parent" />
20. </android.support.constraint.ConstraintLayout>
Activity class

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

File: MainActivity.java

1. package example.javatpoint.com.seekbar;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.widget.SeekBar;
6. import android.widget.Toast;
7.
8. public class MainActivity extends AppCompatActivity {
9. SeekBar seekBar;
10. @Override
11. protected void onCreate(Bundle savedInstanceState) {
12. super.onCreate(savedInstanceState);
13. setContentView(R.layout.activity_main);
14.
15. seekBar=(SeekBar)findViewById(R.id.seekBar);
16. seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

17. @Override
18. public void onProgressChanged(SeekBar seekBar, int progress,
19. boolean fromUser) {
20. Toast.makeText(getApplicationContext(),"seekbar progress: "+progress, Toas
t.LENGTH_SHORT).show();
21. }
22.
23. @Override
24. public void onStartTrackingTouch(SeekBar seekBar) {
25. Toast.makeText(getApplicationContext(),"seekbar touch started!", To
ast.LENGTH_SHORT).show();
26. }
27.
28. @Override
29. public void onStopTrackingTouch(SeekBar seekBar) {
30. Toast.makeText(getApplicationContext(),"seekbar touch stopped!", Toast.LE
NGTH_SHORT).show();
31. }
32. });
33. }
34. }

Output:
Android DatePicker Example

Android DatePicker is a widget to select date. It allows you to select date by day,
month and year. Like DatePicker, android also provides TimePicker to select time.

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

Android DatePicker Example


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

activity_main.xml

File: activity_main.xml

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


2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.datepicker.MainActivity">
8.
9. <TextView
10. android:id="@+id/textView1"
11. android:layout_width="wrap_content"
12. android:layout_height="wrap_content"
13. android:layout_above="@+id/button1"
14. android:layout_alignParentLeft="true"
15. android:layout_alignParentStart="true"
16. android:layout_marginBottom="102dp"
17. android:layout_marginLeft="30dp"
18. android:layout_marginStart="30dp"
19. android:text="" />
20.
21. <Button
22. android:id="@+id/button1"
23. android:layout_width="wrap_content"
24. android:layout_height="wrap_content"
25. android:layout_alignParentBottom="true"
26. android:layout_centerHorizontal="true"
27. android:layout_marginBottom="20dp"
28. android:text="Change Date" />
29.
30. <DatePicker
31. android:id="@+id/datePicker"
32. android:layout_width="wrap_content"
33. android:layout_height="wrap_content"
34. android:layout_above="@+id/textView1"
35. android:layout_centerHorizontal="true"
36. android:layout_marginBottom="36dp" />
37.
38. </RelativeLayout>

Activity class

File: MainActivity.java
1. package example.javatpoint.com.datepicker;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.widget.Button;
7. import android.widget.DatePicker;
8. import android.widget.TextView;
9.
10. public class MainActivity extends AppCompatActivity {
11. DatePicker picker;
12. Button displayDate;
13. TextView textview1;
14. @Override
15. protected void onCreate(Bundle savedInstanceState) {
16. super.onCreate(savedInstanceState);
17. setContentView(R.layout.activity_main);
18.
19. textview1=(TextView)findViewById(R.id.textView1);
20. picker=(DatePicker)findViewById(R.id.datePicker);
21. displayDate=(Button)findViewById(R.id.button1);
22.
23. textview1.setText("Current Date: "+getCurrentDate());
24.
25. displayDate.setOnClickListener(new View.OnClickListener(){
26. @Override
27. public void onClick(View view) {
28.
29. textview1.setText("Change Date: "+getCurrentDate());
30. }
31.
32. });
33.
34. }
35. public String getCurrentDate(){
36. StringBuilder builder=new StringBuilder();;
37. builder.append((picker.getMonth() + 1)+"/");//month is 0 based
38. builder.append(picker.getDayOfMonth()+"/");
39. builder.append(picker.getYear());
40. return builder.toString();
41. }
42. }

Output:
Android TimePicker Example

Android TimePicker widget is used to select date. It allows you to select time by
hour and minute. You cannot select time by seconds.

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

Android TimePicker Example


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

activity_main.xml
File: activity_main.xml

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


2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.timepicker.MainActivity">
8.
9. <TextView
10. android:id="@+id/textView1"
11. android:layout_width="wrap_content"
12. android:layout_height="wrap_content"
13. android:layout_above="@+id/button1"
14. android:layout_alignParentLeft="true"
15. android:layout_alignParentStart="true"
16. android:layout_marginBottom="102dp"
17. android:layout_marginLeft="30dp"
18. android:layout_marginStart="30dp"
19. android:text="" />
20.
21. <Button
22. android:id="@+id/button1"
23. android:layout_width="wrap_content"
24. android:layout_height="wrap_content"
25. android:layout_alignParentBottom="true"
26. android:layout_centerHorizontal="true"
27. android:layout_marginBottom="20dp"
28. android:text="Change Time" />
29.
30. <TimePicker
31. android:id="@+id/timePicker"
32. android:layout_width="wrap_content"
33. android:layout_height="wrap_content"
34. android:layout_above="@+id/textView1"
35. android:layout_centerHorizontal="true"
36. android:layout_marginBottom="36dp" />
37. </RelativeLayout>

Activity class
File: MainActivity.java

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

Output:

Android Analog clock and Digital


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

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

Android AnalogClock is the subclass of View class.

Android DigitalClock is the subclass of TextView class. Since Android API level 17, it
is deprecated. You are recommended to use TextClock Instead.
The AnalogClock was deprecated in API level 23. This widget is no longer supported.
Instead if you want to use AnalogClock in your application you need to hard code. It
does not appear in API level 27 to drag from palette.

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

In android, you need to drag analog and digital clocks from the pallet to display
analog and digital clocks.

activity_main.xml

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

File: activity_main.xml

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


2. <android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.analogdigital.MainActivity">
8.
9. <AnalogClock
10. android:id="@+id/analogClock1"
11. android:layout_width="wrap_content"
12. android:layout_height="wrap_content"
13. android:layout_alignParentTop="true"
14. android:layout_centerHorizontal="true"
15. android:layout_marginLeft="136dp"
16. android:layout_marginTop="296dp"
17. app:layout_constraintStart_toStartOf="parent"
18. app:layout_constraintTop_toTopOf="parent" />
19.
20. <DigitalClock
21. android:id="@+id/digitalClock1"
22. android:layout_width="wrap_content"
23. android:layout_height="wrap_content"
24. android:layout_below="@+id/analogClock1"
25. android:layout_centerHorizontal="true"
26. android:layout_marginLeft="176dp"
27. android:layout_marginTop="84dp"
28. android:text="DigitalClock"
29. app:layout_constraintStart_toStartOf="parent"
30. app:layout_constraintTop_toTopOf="parent" />
31.
32. </android.support.constraint.ConstraintLayout>

Activity class

We have not write any code here.

File: MainActivity.java

1. package example.javatpoint.com.analogdigital;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5.
6. public class MainActivity extends AppCompatActivity {
7.
8. @Override
9. protected void onCreate(Bundle savedInstanceState) {
10. super.onCreate(savedInstanceState);
11. setContentView(R.layout.activity_main);
12. }
13. }
Output:

Android ProgressBar Example

We can display the android progress bar dialog box to display the status of work
being done e.g. downloading file, analyzing status of work etc.
In this example, we are displaying the progress dialog for dummy file download
operation.

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


Android ProgressDialog is the subclass of AlertDialog class.

The ProgressDialog class provides methods to work on progress bar like


setProgress(), setMessage(), setProgressStyle(), setMax(), show() etc. The progress
range of Progress Dialog is 0 to 10000.

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

1. ProgressDialog progressBar = new ProgressDialog(this);


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

Android Progress Bar Example by


ProgressDialog
Let's see a simple example to create progress bar using ProgressDialog class.

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/
android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <Button
8. android:id="@+id/button1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentTop="true"
12. android:layout_centerHorizontal="true"
13. android:layout_marginTop="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 example.javatpoint.com.progressbar;
2.
3. import android.app.ProgressDialog;
4. import android.os.Handler;
5. import android.support.v7.app.AppCompatActivity;
6. import android.os.Bundle;
7. import android.view.View;
8. import android.widget.Button;
9.
10. public class MainActivity extends AppCompatActivity {
11. Button btnStartProgress;
12. ProgressDialog progressBar;
13. private int progressBarStatus = 0;
14. private Handler progressBarHandler = new Handler();
15. private long fileSize = 0;
16. @Override
17. protected void onCreate(Bundle savedInstanceState) {
18. super.onCreate(savedInstanceState);
19. setContentView(R.layout.activity_main);
20. addListenerOnButtonClick();
21. }
22. public void addListenerOnButtonClick() {
23. btnStartProgress = findViewById(R.id.button);
24. btnStartProgress.setOnClickListener(new View.OnClickListener(){
25.
26. @Override
27. public void onClick(View v) {
28. // creating progress bar dialog
29. progressBar = new ProgressDialog(v.getContext());
30. progressBar.setCancelable(true);
31. progressBar.setMessage("File downloading ...");
32. progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
33. progressBar.setProgress(0);
34. progressBar.setMax(100);
35. progressBar.show();
36. //reset progress bar and filesize status
37. progressBarStatus = 0;
38. fileSize = 0;
39.
40. new Thread(new Runnable() {
41. public void run() {
42. while (progressBarStatus < 100) {
43. // performing operation
44. progressBarStatus = doOperation();
45. try {
46. Thread.sleep(1000);
47. } catch (InterruptedException e) {
48. e.printStackTrace();
49. }
50. // Updating the progress bar
51. progressBarHandler.post(new Runnable() {
52. public void run() {
53. progressBar.setProgress(progressBarStatus);
54. }
55. });
56. }
57. // performing operation if file is downloaded,
58. if (progressBarStatus >= 100) {
59. // sleeping for 1 second after operation completed
60. try {
61. Thread.sleep(1000);
62. } catch (InterruptedException e) {
63. e.printStackTrace();
64. }
65. // close the progress bar dialog
66. progressBar.dismiss();
67. }
68. }
69. }).start();
70. }//end of onClick method
71. });
72. }
73. // checking how much file is downloaded and updating the filesize
74. public int doOperation() {
75. //The range of ProgressDialog starts from 0 to 10000
76. while (fileSize <= 10000) {
77. fileSize++;
78. if (fileSize == 1000) {
79. return 10;
80. } else if (fileSize == 2000) {
81. return 20;
82. } else if (fileSize == 3000) {
83. return 30;
84. } else if (fileSize == 4000) {
85. return 40; // you can add more else if
86. }
87. /* else {
88. return 100;
89. }*/
90. }//end of while
91. return 100;
92. }//end of doOperation
93. }
Output:

Android ScrollView (Vertical)


The android.widget.ScrollView class provides the functionality of scroll view.
ScrollView is used to scroll the child elements of palette inside ScrollView. Android
supports vertical scroll view as default scroll view. Vertical ScrollView scrolls elements
vertically.

Android uses HorizontalScrollView for horizontal ScrollView.

Let's implement simple example of vertical ScrollView.

activity_main.xml
Now, drag ScrollView from palette to activity_main.xml file and place some palette
element inside it.

File: activity_main.xml
1. <?xml version="1.0" encoding="utf-8"?>
2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. xmlns:tools="http://schemas.android.com/tools"
4. android:layout_width="match_parent"
5. android:layout_height="match_parent"
6. android:paddingBottom="@dimen/activity_vertical_margin"
7. android:paddingLeft="@dimen/activity_horizontal_margin"
8. android:paddingRight="@dimen/activity_horizontal_margin"
9. android:paddingTop="@dimen/activity_vertical_margin"
10. tools:context="com.example.test.scrollviews.MainActivity">
11.
12.
13. <TextView
14. android:layout_width="wrap_content"
15. android:layout_height="wrap_content"
16. android:textAppearance="?android:attr/textAppearanceMedium"
17. android:text="Vertical ScrollView example"
18. android:id="@+id/textView"
19. android:layout_gravity="center_horizontal"
20. android:layout_centerHorizontal="true"
21. android:layout_alignParentTop="true" />
22.
23.
24. <ScrollView android:layout_marginTop="30dp"
25. android:layout_width="fill_parent"
26. android:layout_height="wrap_content"
27. android:id="@+id/scrollView">
28.
29.
30. <LinearLayout
31. android:layout_width="fill_parent"
32. android:layout_height="fill_parent"
33. android:orientation="vertical" >
34.
35. <Button
36. android:layout_width="fill_parent"
37. android:layout_height="wrap_content"
38. android:text="Button 1" />
39. <Button
40. android:layout_width="fill_parent"
41. android:layout_height="wrap_content"
42. android:text="Button 2" />
43. <Button
44. android:layout_width="fill_parent"
45. android:layout_height="wrap_content"
46. android:text="Button 3" />
47. <Button
48. android:layout_width="fill_parent"
49. android:layout_height="wrap_content"
50. android:text="Button 4" />
51. <Button
52. android:layout_width="fill_parent"
53. android:layout_height="wrap_content"
54. android:text="Button 5" />
55. <Button
56. android:layout_width="fill_parent"
57. android:layout_height="wrap_content"
58. android:text="Button 6" />
59. <Button
60. android:layout_width="fill_parent"
61. android:layout_height="wrap_content"
62. android:text="Button 7" />
63. <Button
64. android:layout_width="fill_parent"
65. android:layout_height="wrap_content"
66. android:text="Button 8" />
67. <Button
68. android:layout_width="fill_parent"
69. android:layout_height="wrap_content"
70. android:text="Button 9" />
71. <Button
72. android:layout_width="fill_parent"
73. android:layout_height="wrap_content"
74. android:text="Button 10" />
75. <Button
76. android:layout_width="fill_parent"
77. android:layout_height="wrap_content"
78. android:text="Button 11" />
79. <Button
80. android:layout_width="fill_parent"
81. android:layout_height="wrap_content"
82. android:text="Button 12" />
83. <Button
84. android:layout_width="fill_parent"
85. android:layout_height="wrap_content"
86. android:text="Button 13" />
87. <Button
88. android:layout_width="fill_parent"
89. android:layout_height="wrap_content"
90. android:text="Button 14" />
91. <Button
92. android:layout_width="fill_parent"
93. android:layout_height="wrap_content"
94. android:text="Button 15" />
95. <Button
96. android:layout_width="fill_parent"
97. android:layout_height="wrap_content"
98. android:text="Button 16" />
99. <Button
100. android:layout_width="fill_parent"
101. android:layout_height="wrap_content"
102. android:text="Button 17" />
103. <Button
104. android:layout_width="fill_parent"
105. android:layout_height="wrap_content"
106. android:text="Button 18" />
107.
108. <Button
109. android:layout_width="fill_parent"
110. android:layout_height="wrap_content"
111. android:text="Button 19" />
112. <Button
113. android:layout_width="fill_parent"
114. android:layout_height="wrap_content"
115. android:text="Button 20" />
116.
117. </LinearLayout>
118.
119. </ScrollView>
120.
121. </RelativeLayout>
Activity class
In activity class, we have not changed any code.

File: MainActivity.java

1. package com.example.test.scrollviews;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5.
6. public class MainActivity extends AppCompatActivity {
7.
8. @Override
9. protected void onCreate(Bundle savedInstanceState) {
10. super.onCreate(savedInstanceState);
11. setContentView(R.layout.activity_main);
12. }
13. }

Output
Android HorizontalScrollView
A HorizontalScrollView is a FrameLayout.
The android.widget.HorizontalScrollView class provides the functionality of
horizontal scroll view. HorizontalScrollView is used to scroll the child elements or
views in a horizontal direction. HorizontalScrollView only supports horizontal
scrolling.

For vertical scroll, android uses ScrollView.

Let's implement simple example of HorizontalScrollView.

activity_main.xml
Now, drag HorizontalScrollView from palette to activity_main.xml file and place some
views or elements inside it.

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


2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. android:layout_width="fill_parent"
4. android:layout_height="fill_parent">
5.
6.
7. <TextView
8. android:layout_width="wrap_content"
9. android:layout_height="wrap_content"
10. android:textAppearance="?android:attr/textAppearanceSmall"
11. android:text="Horizontal ScrollView Example"
12. android:id="@+id/textView"
13. android:layout_alignParentTop="true"
14. android:layout_centerHorizontal="true" />
15.
16.
17. <LinearLayout
18. android:layout_width="match_parent"
19. android:layout_height="match_parent"
20. android:layout_marginTop="25dp">
21. <HorizontalScrollView
22. android:layout_width="match_parent"
23. android:layout_height="60dp"
24. android:id="@+id/horizontalScrollView">
25.
26. <LinearLayout
27. android:layout_width="wrap_content"
28. android:layout_height="wrap_content"
29. android:orientation="horizontal">
30. <Button
31. android:layout_width="wrap_content"
32. android:layout_height="wrap_content"
33. android:text="New Button1"
34. android:id="@+id/button1" />
35. <Button
36. android:layout_width="wrap_content"
37. android:layout_height="wrap_content"
38. android:text="New Button2"
39. android:id="@+id/button2" />
40.
41. <Button
42. android:layout_width="wrap_content"
43. android:layout_height="wrap_content"
44. android:text="New Button3"
45. android:id="@+id/button3" />
46. <Button
47. android:layout_width="wrap_content"
48. android:layout_height="wrap_content"
49. android:text="New Button4"
50. android:id="@+id/button4" />
51. <Button
52. android:layout_width="wrap_content"
53. android:layout_height="wrap_content"
54. android:text="New Button5"
55. android:id="@+id/button5" />
56. <Button
57. android:layout_width="wrap_content"
58. android:layout_height="wrap_content"
59. android:text="New Button6"
60. android:id="@+id/button6" />
61. <Button
62. android:layout_width="wrap_content"
63. android:layout_height="wrap_content"
64. android:text="New Button7"
65. android:id="@+id/button7" />
66. <Button
67. android:layout_width="wrap_content"
68. android:layout_height="wrap_content"
69. android:text="New Button8"
70. android:id="@+id/button8"/>
71. </LinearLayout>
72.
73. </HorizontalScrollView>
74. </LinearLayout>
75. </RelativeLayout>
Activity class
This is auto generated code, we have not written any code here.

File: MainActivity.java

1. package com.example.test.horizantalscrollview;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5.
6. public class MainActivity extends AppCompatActivity {
7.
8. @Override
9. protected void onCreate(Bundle savedInstanceState) {
10. super.onCreate(savedInstanceState);
11. setContentView(R.layout.activity_main);
12. }
13. }
Android Image Switcher
Android image switcher provides an animation over images to transition from one
image to another. In order to use image switcher, we need to
implement ImageSwitcher component in .xml file.

The setFactory() method of ImageSwitcher provide implementation


of ViewFactory interface. ViewFactory interface implements its unimplemented
method and returns an ImageView.

Example of Image Switcher


Let's implement an image switcher.

Create activity_main.xml and content_main.xml file in layout folder.

Place some images in drawable folder which are to be switch.

activity_main.xml
File: activity_main.xml

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


2. <android.support.design.widget.CoordinatorLayout xmlns:android="http://
schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. android:fitsSystemWindows="true"
8. tools:context="com.example.test.imageswitcher.MainActivity">
9.
10. <android.support.design.widget.AppBarLayout
11. android:layout_width="match_parent"
12. android:layout_height="wrap_content"
13. android:theme="@style/AppTheme.AppBarOverlay">
14.
15. <android.support.v7.widget.Toolbar
16. android:id="@+id/toolbar"
17. android:layout_width="match_parent"
18. android:layout_height="?attr/actionBarSize"
19. android:background="?attr/colorPrimary"
20. app:popupTheme="@style/AppTheme.PopupOverlay" />
21.
22. </android.support.design.widget.AppBarLayout>
23. <include layout="@layout/content_main" />
24.
25. </android.support.design.widget.CoordinatorLayout>
content_main.xml
File: content_main.xml

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


2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. android:paddingBottom="@dimen/activity_vertical_margin"
8. android:paddingLeft="@dimen/activity_horizontal_margin"
9. android:paddingRight="@dimen/activity_horizontal_margin"
10. android:paddingTop="@dimen/activity_vertical_margin"
11. app:layout_behavior="@string/appbar_scrolling_view_behavior"
12. tools:context="com.example.test.imageswitcher.MainActivity"
13. tools:showIn="@layout/activity_main">
14.
15. <TextView
16. android:layout_width="wrap_content"
17. android:layout_height="wrap_content"
18. android:text="Image Switcher Example"
19.
20. android:id="@+id/textView"
21. android:layout_alignParentTop="true"
22. android:layout_centerHorizontal="true" />
23.
24. <ImageSwitcher
25. android:id="@+id/imageSwitcher"
26. android:layout_width="match_parent"
27. android:layout_height="250dp"
28. android:layout_marginBottom="28dp"
29. android:layout_marginTop="40dp" />
30.
31. <Button
32. android:layout_width="wrap_content"
33. android:layout_height="wrap_content"
34. android:text="Next"
35. android:id="@+id/button"
36. android:layout_marginBottom="47dp"
37. android:layout_alignParentBottom="true"
38. android:layout_centerHorizontal="true" />
39. </RelativeLayout>
Activity class
File: MainActivity.java

1. package com.example.test.imageswitcher;
2.
3. import android.os.Bundle;
4. import android.support.v7.app.AppCompatActivity;
5. import android.support.v7.widget.Toolbar;
6. import android.view.View;
7. import android.widget.Button;
8. import android.widget.ImageSwitcher;
9. import android.widget.ImageView;
10. import android.widget.ViewSwitcher;
11.
12. import android.app.ActionBar;
13. import android.view.animation.Animation;
14. import android.view.animation.AnimationUtils;
15.
16.
17. public class MainActivity extends AppCompatActivity {
18. ImageSwitcher imageSwitcher;
19. Button nextButton;
20.
21. int imageSwitcherImages[] =
22. {R.drawable.cpp, R.drawable.c_sarp, R.drawable.jsp, R.drawable.mysql, R.drawable.
hadoop};
23.
24. int switcherImageLength = imageSwitcherImages.length;
25. int counter = -1;
26.
27. @Override
28. protected void onCreate(Bundle savedInstanceState) {
29. super.onCreate(savedInstanceState);
30. setContentView(R.layout.activity_main);
31. Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
32. setSupportActionBar(toolbar);
33.
34. imageSwitcher = (ImageSwitcher) findViewById(R.id.imageSwitcher);
35. nextButton = (Button) findViewById(R.id.button);
36.
37. imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
38. @Override
39. public View makeView() {
40. ImageView switcherImageView = new ImageView(getApplicationContext());

41. switcherImageView.setLayoutParams(new ImageSwitcher.LayoutPar


ams(
42. ActionBar.LayoutParams.FILL_PARENT, ActionBar.LayoutParams.FILL_PA
RENT
43. ));
44. switcherImageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
45. switcherImageView.setImageResource(R.drawable.hadoop);
46. //switcherImageView.setMaxHeight(100);
47. return switcherImageView;
48. }
49. });
50.
51. Animation aniOut = AnimationUtils.loadAnimation(this, android.R.anim.sl
ide_out_right);
52. Animation aniIn = AnimationUtils.loadAnimation(this, android.R.anim.slide_in_lef
t);
53.
54. imageSwitcher.setOutAnimation(aniOut);
55. imageSwitcher.setInAnimation(aniIn);
56.
57. nextButton.setOnClickListener(new View.OnClickListener() {
58. @Override
59. public void onClick(View v) {
60. counter++;
61. if (counter == switcherImageLength){
62. counter = 0;
63. imageSwitcher.setImageResource(imageSwitcherImages[counter])
;
64. }
65. else{
66. imageSwitcher.setImageResource(imageSwitcherImages[counter]);
67. }
68. }
69. });
70. }
71.
72. }

Output
Android Image Slider
Android image slider slides one entire screen to another screen. Image slider is
created by ViewPager which is provided by support library. To implement image
slider, you need to inherit ViewPager class which extends PagerAdapter.

Example of Image Slider


Let's see an example of android image slider.

activity_main.xml
In activity_main.xml file, we have wrapped ViewPager inside RelativeLayout.

File: activity_main.xml

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


2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. xmlns:tools="http://schemas.android.com/tools"
4. android:layout_width="fill_parent"
5. android:layout_height="fill_parent"
6. android:paddingBottom="@dimen/activity_vertical_margin"
7. android:paddingLeft="@dimen/activity_horizontal_margin"
8. android:paddingRight="@dimen/activity_horizontal_margin"
9. android:paddingTop="@dimen/activity_vertical_margin"
10. tools:context="com.example.test.imageslider.MainActivity">
11.
12.
13. <android.support.v4.view.ViewPager
14. android:id="@+id/viewPage"
15. android:layout_width="fill_parent"
16. android:layout_height="fill_parent" />
17.
18. </RelativeLayout>
Activity class
File: MainActivity.java
1. package com.example.test.imageslider;
2.
3. import android.support.v4.view.ViewPager;
4. import android.support.v7.app.AppCompatActivity;
5. import android.os.Bundle;
6.
7. public class MainActivity extends AppCompatActivity {
8.
9. @Override
10. protected void onCreate(Bundle savedInstanceState) {
11. super.onCreate(savedInstanceState);
12. setContentView(R.layout.activity_main);
13.
14. ViewPager mViewPager = (ViewPager) findViewById(R.id.viewPage);
15. ImageAdapter adapterView = new ImageAdapter(this);
16. mViewPager.setAdapter(adapterView);
17. }
18. }
ImageAdapter class
Now create ImageAdapter class which extends PagerAdapter for android image
slider.

Place some images in drawable folder which are to be slid.

File: ImageAdapter.java

1. package com.example.test.imageslider;
2.
3. import android.content.Context;
4. import android.support.v4.view.PagerAdapter;
5. import android.support.v4.view.ViewPager;
6. import android.view.View;
7. import android.view.ViewGroup;
8. import android.widget.ImageView;
9.
10. public class ImageAdapter extends PagerAdapter{
11. Context mContext;
12.
13. ImageAdapter(Context context) {
14. this.mContext = context;
15. }
16.
17. @Override
18. public boolean isViewFromObject(View view, Object object) {
19. return view == ((ImageView) object);
20. }
21.
22. private int[] sliderImageId = new int[]{
23. R.drawable.image1, R.drawable.image2, R.drawable.image3,R.drawable.
image4, R.drawable.image5,
24. };
25.
26. @Override
27. public Object instantiateItem(ViewGroup container, int position) {
28. ImageView imageView = new ImageView(mContext);
29. imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
30. imageView.setImageResource(sliderImageId[position]);
31. ((ViewPager) container).addView(imageView, 0);
32. return imageView;
33. }
34.
35. @Override
36. public void destroyItem(ViewGroup container, int position, Object object) {
37. ((ViewPager) container).removeView((ImageView) object);
38. }
39.
40. @Override
41. public int getCount() {
42. return sliderImageId.length;
43. }
44. }

We need to override following methods of PagerAdapter class.


1. isViewFromObject(View, Object): This method checks the view whether it is
associated with key and returned by instantiateItem().
2. instantiateItem(ViewGroup, int): This method creates the page position passed as
an argument.
3. destroyItem(ViewGroup, int, Object): It removes the page from its current position
from container. In this example we simply removed object using removeView().
4. getCount(): It returns the number of available views in ViewPager.

Output
Android ViewStub
A ViewStub is a zero-sized invisible View which is used to load "layout resource" at
runtime. ViewStub is a zero dimension View, so you will not see anything on the
layout pallete.

To make parent resource visible, inflate() method is invoked. To make ViewStub


visible or invisible, setVisibility(int) method is invoked. The View.VISIBLE constant is
used for making ViewStub visible and View.GONE constant is used for invisible.

Example of ViewStub
Let's create an example of ViewStub View that displays and hides an ImageView
(image) created in another layout (my_layout.xml) file.

File: activity.xml

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


2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. xmlns:tools="http://schemas.android.com/tools"
4. android:layout_width="match_parent"
5. android:layout_height="match_parent"
6. android:paddingBottom="@dimen/activity_vertical_margin"
7. android:paddingLeft="@dimen/activity_horizontal_margin"
8. android:paddingRight="@dimen/activity_horizontal_margin"
9. android:paddingTop="@dimen/activity_vertical_margin"
10. tools:context="com.example.test.viewstubexample.MainActivity">
11.
12. <ViewStub
13. android:layout_width="wrap_content"
14. android:layout_height="wrap_content"
15. android:id="@+id/viewStub"
16. android:layout_marginLeft="120dp"
17. android:layout="@layout/my_layout"
18. android:layout_alignParentTop="true" />
19.
20. <Button
21. android:layout_width="wrap_content"
22. android:layout_height="wrap_content"
23. android:text="Show"
24. android:id="@+id/show"
25. android:layout_alignParentBottom="true"
26. android:layout_alignParentLeft="true"
27. android:layout_alignParentStart="true"
28. android:layout_marginLeft="65dp"
29. android:layout_marginStart="65dp" />
30.
31. <Button
32. android:layout_width="wrap_content"
33. android:layout_height="wrap_content"
34. android:text="Hide"
35. android:id="@+id/hide"
36. android:layout_alignParentBottom="true"
37. android:layout_toRightOf="@+id/show"
38. android:layout_toEndOf="@+id/show"
39. android:layout_marginLeft="51dp"
40. android:layout_marginStart="51dp" />
41.
42. </RelativeLayout>

File: my_layout.xml

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


2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent">
5.
6. <ImageView
7. android:layout_width="wrap_content"
8. android:layout_height="wrap_content"
9. android:id="@+id/imageView"
10. android:background="@drawable/image"
11. />
12.
13. </LinearLayout>
File: MainActivity.java

1. package com.example.test.viewstubexample;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.view.ViewStub;
7. import android.widget.Button;
8.
9. public class MainActivity extends AppCompatActivity {
10. ViewStub viewStub;
11. Button show,hide;
12. @Override
13. protected void onCreate(Bundle savedInstanceState) {
14. super.onCreate(savedInstanceState);
15. setContentView(R.layout.activity_main);
16.
17. show=(Button)findViewById(R.id.show);
18. hide=(Button)findViewById(R.id.hide);
19. viewStub=(ViewStub)findViewById(R.id.viewStub);
20. viewStub.inflate();
21.
22. show.setOnClickListener(new View.OnClickListener() {
23. @Override
24. public void onClick(View v) {
25. viewStub.setVisibility(View.VISIBLE);
26. }
27. });
28. hide.setOnClickListener(new View.OnClickListener() {
29. @Override
30. public void onClick(View v) {
31. viewStub.setVisibility(View.GONE);
32. }
33. });
34. }
35. }
Output
Android TabLayout
TabLayout is used to implement horizontal tabs. TabLayout is released by Android
after the deprecation of ActionBar.TabListener (API level 21).

TabLayout is introduced in design support library to implement tabs.

Tabs are created using newTab() method of TabLayout class. The title and icon of
Tabs are set through setText(int) and setIcon(int) methods of TabListener interface
respectively. Tabs of layout are attached over TabLayout using the method
addTab(Tab) method.

1. TabLayout tabLayout = (TabLayout)findViewById(R.id.tabLayout);


2. tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
3. tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
4. tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));

We can also add tab item to TabLayout using TabItem of android design widget.

1. <android.support.design.widget.TabItem
2. android:text="@string/tab_text"/>
Example of TabLayout using ViewPager
Let's create an example of TabLayout using ViewPager and Fragment.

File: activity.xml

Create an activity.xml file with TabLayout and ViewPager view components.

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


2. <android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="tablayout.example.com.tablayout.MainActivity">
8.
9.
10. <android.support.design.widget.TabLayout
11. android:id="@+id/tabLayout"
12. android:layout_width="match_parent"
13. android:layout_height="wrap_content"
14. android:background="#1db995">
15. </android.support.design.widget.TabLayout>
16.
17. <android.support.v4.view.ViewPager
18. android:id="@+id/viewPager"
19. android:layout_width="355dp"
20. android:layout_height="455dp"
21. app:layout_constraintTop_toBottomOf="@+id/tabLayout"
22. tools:layout_editor_absoluteX="8dp" />
23.
24.
25. </android.support.constraint.ConstraintLayout>

File: build.gradle

Now gave the dependency library of TabLayout in build.gradle file.

1. implementation 'com.android.support:design:26.1.0'

File: MainActivity.java

In this file, we implement two additional


listener addOnPageChangeListener(listener) of ViewPager which makes slides the
different fragments of tabs and addOnTabSelectedListener(listener) of TabLayout
which select the current tab on tab selection.

1. package tablayout.example.com.tablayout;
2.
3. import android.support.design.widget.TabLayout;
4. import android.support.v4.view.ViewPager;
5. import android.support.v7.app.AppCompatActivity;
6. import android.os.Bundle;
7.
8. public class MainActivity extends AppCompatActivity {
9. TabLayout tabLayout;
10. ViewPager viewPager;
11. @Override
12. protected void onCreate(Bundle savedInstanceState) {
13. super.onCreate(savedInstanceState);
14. setContentView(R.layout.activity_main);
15.
16. tabLayout=(TabLayout)findViewById(R.id.tabLayout);
17. viewPager=(ViewPager)findViewById(R.id.viewPager);
18.
19. tabLayout.addTab(tabLayout.newTab().setText("Home"));
20. tabLayout.addTab(tabLayout.newTab().setText("Sport"));
21. tabLayout.addTab(tabLayout.newTab().setText("Movie"));
22. tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
23.
24. final MyAdapter adapter = new MyAdapter(this,getSupportFragmentManager(),
tabLayout.getTabCount());
25. viewPager.setAdapter(adapter);
26.
27. viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPage
ChangeListener(tabLayout));
28.
29. tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedList
ener() {
30. @Override
31. public void onTabSelected(TabLayout.Tab tab) {
32. viewPager.setCurrentItem(tab.getPosition());
33. }
34.
35. @Override
36. public void onTabUnselected(TabLayout.Tab tab) {
37.
38. }
39.
40. @Override
41. public void onTabReselected(TabLayout.Tab tab) {
42.
43. }
44. });
45.
46. }
47. }

File: MyAdapter.java

1. package tablayout.example.com.tablayout;
2.
3. import android.content.Context;
4. import android.support.v4.app.Fragment;
5. import android.support.v4.app.FragmentPagerAdapter;
6. import android.support.v4.app.FragmentManager;
7.
8. public class MyAdapter extends FragmentPagerAdapter {
9.
10. private Context myContext;
11. int totalTabs;
12.
13. public MyAdapter(Context context, FragmentManager fm, int totalTabs) {
14. super(fm);
15. myContext = context;
16. this.totalTabs = totalTabs;
17. }
18.
19. // this is for fragment tabs
20. @Override
21. public Fragment getItem(int position) {
22. switch (position) {
23. case 0:
24. HomeFragment homeFragment = new HomeFragment();
25. return homeFragment;
26. case 1:
27. SportFragment sportFragment = new SportFragment();
28. return sportFragment;
29. case 2:
30. MovieFragment movieFragment = new MovieFragment();
31. return movieFragment;
32. default:
33. return null;
34. }
35. }
36. // this counts total number of tabs
37. @Override
38. public int getCount() {
39. return totalTabs;
40. }
41. }

Now create different fragment files for all different tabs.

File: HomeFragment.java

1. package tablayout.example.com.tablayout;
2.
3. import android.os.Bundle;
4. import android.support.v4.app.Fragment;
5. import android.view.LayoutInflater;
6. import android.view.View;
7. import android.view.ViewGroup;
8.
9. public class HomeFragment extends Fragment {
10.
11.
12. public HomeFragment() {
13. // Required empty public constructor
14. }
15.
16. @Override
17. public View onCreateView(LayoutInflater inflater, ViewGroup container,
18. Bundle savedInstanceState) {
19. // Inflate the layout for this fragment
20. return inflater.inflate(R.layout.fragment_home, container, false);
21. }
22.
23. }

File: fragment_home.xml

1. <FrameLayout 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="tablayout.example.com.tablayout.HomeFragment">
6.
7. <!-- TODO: Update blank fragment layout -->
8.
9. <TextView
10. android:layout_width="match_parent"
11. android:layout_height="match_parent"
12. android:gravity="center"
13. android:text="@string/home_fragment" />
14.
15. </FrameLayout>

File: SportFragment.java

1. package tablayout.example.com.tablayout;
2.
3. import android.os.Bundle;
4. import android.support.v4.app.Fragment;
5. import android.view.LayoutInflater;
6. import android.view.View;
7. import android.view.ViewGroup;
8.
9. public class SportFragment extends Fragment {
10.
11.
12. public SportFragment() {
13. // Required empty public constructor
14. }
15.
16. @Override
17. public View onCreateView(LayoutInflater inflater, ViewGroup container,
18. Bundle savedInstanceState) {
19. // Inflate the layout for this fragment
20. return inflater.inflate(R.layout.fragment_sport, container, false);
21. }
22.
23. }

File: fragment_sport.xml

1. <FrameLayout 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="tablayout.example.com.tablayout.SportFragment">
6.
7. <!-- TODO: Update blank fragment layout -->
8. <TextView
9. android:layout_width="match_parent"
10. android:layout_height="match_parent"
11. android:gravity="center"
12. android:text="@string/sport_fragment" />
13.
14. </FrameLayout>

File: MovieFragment.java

1. package tablayout.example.com.tablayout;
2.
3. import android.os.Bundle;
4. import android.support.v4.app.Fragment;
5. import android.view.LayoutInflater;
6. import android.view.View;
7. import android.view.ViewGroup;
8.
9. public class MovieFragment extends Fragment {
10.
11.
12. public MovieFragment() {
13. // Required empty public constructor
14. }
15.
16. @Override
17. public View onCreateView(LayoutInflater inflater, ViewGroup container,
18. Bundle savedInstanceState) {
19. // Inflate the layout for this fragment
20. return inflater.inflate(R.layout.fragment_movie, container, false);
21. }
22.
23. }

File: fragment_movie.xml

1. <FrameLayout 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="tablayout.example.com.tablayout.MovieFragment">
6.
7. <!-- TODO: Update blank fragment layout -->
8. <TextView
9. android:layout_width="match_parent"
10. android:layout_height="match_parent"
11. android:gravity="center"
12. android:text="@string/movie_fragment" />
13.
14. </FrameLayout>

File: strings.xml

1. <resources>
2. <string name="app_name">TabLayout</string>
3.
4. <!-- TODO: Remove or change this placeholder text -->
5. <string name="home_fragment">Home Fragment</string>
6. <string name="sport_fragment">Sport Fragment</string>
7. <string name="movie_fragment">Movie Fragment</string>
8.
9. </resources>

Output
Android TabLayout with FrameLayout
In the previous page, we created a sliding tabs using TabLayout and ViewPager. Here,
we are going to create non sliding tabs using TabLayout and FrameLayout.

Items of TabLayout are implemented by adding TabItem of android support design


widget.

Example of TabLayout using FrameLayout


Let's create an example of TabLayout using FrameLayout and Fragment.

File: activity.xml

Create an activity.xml file with TabLayout and FrameLayout view components.

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


2. <android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="tablayout.example.com.tablayoutwithframelayout.MainActivi
ty">
8.
9.
10. <android.support.design.widget.TabLayout
11. android:id="@+id/tabLayout"
12. android:layout_width="match_parent"
13. android:layout_height="wrap_content"
14. android:background="#7367">
15.
16. <android.support.design.widget.TabItem
17. android:layout_width="wrap_content"
18. android:layout_height="wrap_content"
19. android:text="Home" />
20.
21. <android.support.design.widget.TabItem
22. android:layout_width="wrap_content"
23. android:layout_height="wrap_content"
24. android:text="Java" />
25.
26. <android.support.design.widget.TabItem
27. android:layout_width="wrap_content"
28. android:layout_height="wrap_content"
29. android:text="Android" />
30.
31. <android.support.design.widget.TabItem
32. android:layout_width="wrap_content"
33. android:layout_height="wrap_content"
34. android:text="Php" />
35. </android.support.design.widget.TabLayout>
36.
37. <FrameLayout
38. android:id="@+id/frameLayout"
39. android:layout_width="match_parent"
40. android:layout_height="455dp"
41. app:layout_constraintEnd_toEndOf="parent"
42. app:layout_constraintStart_toStartOf="parent"
43. app:layout_constraintTop_toBottomOf="@+id/tabLayout">
44.
45. </FrameLayout>
46. </android.support.constraint.ConstraintLayout>

File: build.gradle

Now gave the dependency library of TabLayout in build.gradle file.

1. implementation 'com.android.support:design:26.1.0'

File: MainActivity.java

1. package tablayout.example.com.tablayoutwithframelayout;
2.
3. import android.support.design.widget.TabLayout;
4. import android.support.v4.app.Fragment;
5. import android.support.v4.app.FragmentManager;
6. import android.support.v4.app.FragmentTransaction;
7. import android.support.v7.app.AppCompatActivity;
8. import android.os.Bundle;
9. import android.widget.FrameLayout;
10.
11. public class MainActivity extends AppCompatActivity {
12. TabLayout tabLayout;
13. FrameLayout frameLayout;
14. Fragment fragment = null;
15. FragmentManager fragmentManager;
16. FragmentTransaction fragmentTransaction;
17. @Override
18. protected void onCreate(Bundle savedInstanceState) {
19. super.onCreate(savedInstanceState);
20. setContentView(R.layout.activity_main);
21.
22. tabLayout=(TabLayout)findViewById(R.id.tabLayout);
23. frameLayout=(FrameLayout)findViewById(R.id.frameLayout);
24.
25. fragment = new HomeFragment();
26. fragmentManager = getSupportFragmentManager();
27. fragmentTransaction = fragmentManager.beginTransaction();
28. fragmentTransaction.replace(R.id.frameLayout, fragment);
29. fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGM
ENT_OPEN);
30. fragmentTransaction.commit();
31.
32. tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
33. @Override
34. public void onTabSelected(TabLayout.Tab tab) {
35. // Fragment fragment = null;
36. switch (tab.getPosition()) {
37. case 0:
38. fragment = new HomeFragment();
39. break;
40. case 1:
41. fragment = new JavaFragment();
42. break;
43. case 2:
44. fragment = new AndroidFragment();
45. break;
46. case 3:
47. fragment = new PhpFragment();
48. break;
49. }
50. FragmentManager fm = getSupportFragmentManager();
51. FragmentTransaction ft = fm.beginTransaction();
52. ft.replace(R.id.frameLayout, fragment);
53. ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
54. ft.commit();
55. }
56.
57. @Override
58. public void onTabUnselected(TabLayout.Tab tab) {
59.
60. }
61.
62. @Override
63. public void onTabReselected(TabLayout.Tab tab) {
64.
65. }
66. });
67.
68. }
69. }

Now create different fragment files for all different tabs.

File: HomeFragment.java

1. package tablayout.example.com.tablayoutwithframelayout;
2.
3. import android.os.Bundle;
4. import android.support.v4.app.Fragment;
5. import android.view.LayoutInflater;
6. import android.view.View;
7. import android.view.ViewGroup;
8.
9. public class HomeFragment extends Fragment {
10.
11. public HomeFragment() {
12. // Required empty public constructor
13. }
14.
15. @Override
16. public View onCreateView(LayoutInflater inflater, ViewGroup container,
17. Bundle savedInstanceState) {
18. // Inflate the layout for this fragment
19. return inflater.inflate(R.layout.fragment_home, container, false);
20. }
21.
22. }

File: fragment_home.xml

1. <FrameLayout 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="tablayout.example.com.tablayoutwithframelayout.HomeFrag
ment">
6.
7. <!-- TODO: Update blank fragment layout -->
8. <TextView
9. android:layout_width="match_parent"
10. android:layout_height="match_parent"
11. android:gravity="center"
12. android:text="@string/home_fragment" />
13.
14. </FrameLayout>
File: JavaFragment.java

1. package tablayout.example.com.tablayoutwithframelayout;
2.
3. import android.os.Bundle;
4. import android.support.v4.app.Fragment;
5. import android.view.LayoutInflater;
6. import android.view.View;
7. import android.view.ViewGroup;
8.
9. public class JavaFragment extends Fragment {
10.
11. public JavaFragment() {
12. // Required empty public constructor
13. }
14.
15. @Override
16. public View onCreateView(LayoutInflater inflater, ViewGroup container,
17. Bundle savedInstanceState) {
18. // Inflate the layout for this fragment
19. return inflater.inflate(R.layout.fragment_java, container, false);
20. }
21.
22. }

File: fragment_java.xml

1. <FrameLayout 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="tablayout.example.com.tablayoutwithframelayout.JavaFragm
ent">
6.
7. <!-- TODO: Update blank fragment layout -->
8. <TextView
9. android:layout_width="match_parent"
10. android:layout_height="match_parent"
11. android:gravity="center"
12. android:text="@string/java_fragment" />
13.
14. </FrameLayout>

File: AndroidFragment.java

1. package tablayout.example.com.tablayoutwithframelayout;
2.
3. import android.os.Bundle;
4. import android.support.v4.app.Fragment;
5. import android.view.LayoutInflater;
6. import android.view.View;
7. import android.view.ViewGroup;
8.
9. public class AndroidFragment extends Fragment {
10.
11. public AndroidFragment() {
12. // Required empty public constructor
13. }
14.
15. @Override
16. public View onCreateView(LayoutInflater inflater, ViewGroup container,
17. Bundle savedInstanceState) {
18. // Inflate the layout for this fragment
19. return inflater.inflate(R.layout.fragment_android, container, false);
20. }
21.
22. }

File: fragment_android.xml

1. <FrameLayout 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="tablayout.example.com.tablayoutwithframelayout.AndroidFr
agment">
6.
7. <!-- TODO: Update blank fragment layout -->
8. <TextView
9. android:layout_width="match_parent"
10. android:layout_height="match_parent"
11. android:gravity="center"
12. android:text="@string/android_fragment" />
13.
14. </FrameLayout>

File: PhpFragment.java

1. package tablayout.example.com.tablayoutwithframelayout;
2.
3. import android.os.Bundle;
4. import android.support.v4.app.Fragment;
5. import android.view.LayoutInflater;
6. import android.view.View;
7. import android.view.ViewGroup;
8.
9. public class PhpFragment extends Fragment {
10.
11. public PhpFragment() {
12. // Required empty public constructor
13. }
14.
15. @Override
16. public View onCreateView(LayoutInflater inflater, ViewGroup container,
17. Bundle savedInstanceState) {
18. // Inflate the layout for this fragment
19. return inflater.inflate(R.layout.fragment_php, container, false);
20. }
21.
22. }

File: fragment_php.xml
1. <FrameLayout 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="tablayout.example.com.tablayoutwithframelayout.PhpFragm
ent">
6.
7. <!-- TODO: Update blank fragment layout -->
8. <TextView
9. android:layout_width="match_parent"
10. android:layout_height="match_parent"
11. android:gravity="center"
12. android:text="@string/php_fragment" />
13.
14. </FrameLayout>

File: strings.xml

1. <resources>
2. <string name="app_name">TabLayout with FrameLayout</string>
3.
4. <!-- TODO: Remove or change this placeholder text -->
5. <string name="home_fragment">Home fragment</string>
6. <string name="java_fragment">Java fragment</string>
7. <string name="android_fragment">Android fragment</string>
8. <string name="php_fragment">Php fragment</string>
9. </resources>

Output
Android SearchView
Android SearchView provides user interface to search query submitted over search
provider. SearchView widget can be implemented over ToolBar/ActionBar or inside a
layout.

SearchView is by default collapsible and set to be iconified


using setIconifiedByDefault(true) method of SearchView class. For making search field
visible, SearchView uses setIconifiedByDefault(false) method.

Methods of SearchView
1. public boolean onQueryTextSubmit(String query): It searches the query on the
submission of content over SearchView editor. It is case dependent.
2. public boolean onQueryTextChange(String newText): It searches the query at the
time of text change over SearchView editor.

Example of SearchView
Let's see the example of SearchView over layout, searching data in a ListView.

activity_main.xml
Create an activity_main.xml file in layout folder containing ScrollView and ListView.

File: activity_main.xml

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


2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. xmlns:tools="http://schemas.android.com/tools"
4. android:layout_width="match_parent"
5. android:layout_height="match_parent"
6. android:paddingBottom="@dimen/activity_vertical_margin"
7. android:paddingLeft="@dimen/activity_horizontal_margin"
8. android:paddingRight="@dimen/activity_horizontal_margin"
9. android:paddingTop="@dimen/activity_vertical_margin"
10. tools:context="com.example.test.searchview.MainActivity">
11.
12. <ListView
13. android:layout_width="match_parent"
14. android:layout_height="match_parent"
15. android:id="@+id/lv1"
16. android:divider="#ad5"
17. android:dividerHeight="2dp"
18. android:layout_below="@+id/searchView"/>
19.
20. <SearchView
21. android:id="@+id/searchView"
22. android:layout_width="wrap_content"
23. android:layout_height="wrap_content"
24. android:queryHint="Search Here"
25. android:iconifiedByDefault="false"
26. android:layout_alignParentTop="true"
27. />
28.
29. </RelativeLayout>
Activity class
File: MainActivity.java

1. package com.example.test.searchview;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.widget.ArrayAdapter;
6. import android.widget.Filter;
7. import android.widget.ListView;
8. import android.widget.SearchView;
9. import android.widget.Toast;
10.
11. import java.util.ArrayList;
12.
13. public class MainActivity extends AppCompatActivity {
14. SearchView searchView;
15. ListView listView;
16. ArrayList<String> list;
17. ArrayAdapter<String > adapter;
18. @Override
19. protected void onCreate(Bundle savedInstanceState) {
20. super.onCreate(savedInstanceState);
21. setContentView(R.layout.activity_main);
22.
23. searchView = (SearchView) findViewById(R.id.searchView);
24. listView = (ListView) findViewById(R.id.lv1);
25.
26. list = new ArrayList<>();
27. list.add("Apple");
28. list.add("Banana");
29. list.add("Pineapple");
30. list.add("Orange");
31. list.add("Lychee");
32. list.add("Gavava");
33. list.add("Peech");
34. list.add("Melon");
35. list.add("Watermelon");
36. list.add("Papaya");
37.
38. adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,lis
t);
39. listView.setAdapter(adapter);
40.
41. searchView.setOnQueryTextListener(new SearchView.OnQueryTextListen
er() {
42. @Override
43. public boolean onQueryTextSubmit(String query) {
44.
45. if(list.contains(query)){
46. adapter.getFilter().filter(query);
47. }else{
48. Toast.makeText(MainActivity.this, "No Match found",Toast.LENGTH_LONG
).show();
49. }
50. return false;
51. }
52.
53. @Override
54. public boolean onQueryTextChange(String newText) {
55. // adapter.getFilter().filter(newText);
56. return false;
57. }
58. });
59. }
60. }

Output
Android SearchView on ToolBar
As we have already implemented SearchView widget over activity layout, it can also
be implemented over ToolBar/ActionBar. For implementing SearchView over ToolBar,
we need to create menu option and place SearchView widget on it.

Example of SearchView on ToolBar (ActionBar)


Let's us see the example of SearchView over ToolBar and searching data in ListView.

Directory Structure of this Example

activity_main.xml
Create an activity_main.xml file in layout folder containing ListView.

File: activity_main.xml

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


2. <android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="searchview.toolbar.com.searchviewtoolbar.MainActivity">
8.
9. <ListView
10. android:id="@+id/listView"
11. android:layout_width="match_parent"
12. android:layout_height="fill_parent"
13. />
14.
15. </android.support.constraint.ConstraintLayout>
menu.xml
Create a menu.xml file in menu folder and place the following code. This code places
the SearchView widget over ToolBar.

File: menu.xml

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


2. <menu xmlns:app="http://schemas.android.com/apk/res-auto"
3. xmlns:android="http://schemas.android.com/apk/res/android">
4.
5. <item
6. android:id="@+id/app_bar_search"
7. android:icon="@drawable/ic_search_black_24dp"
8. android:title="Search"
9. app:showAsAction="ifRoom|withText"
10. app:actionViewClass="android.widget.SearchView"/>
11. </menu>
Activity class
File: MainActivity.java

1. package searchview.toolbar.com.searchviewtoolbar;
2.
3. import android.support.v4.view.MenuItemCompat;
4. import android.support.v7.app.AppCompatActivity;
5. import android.os.Bundle;
6. import android.view.Menu;
7. import android.view.MenuInflater;
8. import android.view.MenuItem;
9. import android.widget.ArrayAdapter;
10. import android.widget.ListView;
11. import android.widget.SearchView;
12. import android.widget.Toast;
13.
14. import java.util.ArrayList;
15.
16. public class MainActivity extends AppCompatActivity {
17.
18. ListView listView;
19. ArrayList<String> list;
20. ArrayAdapter<String > adapter;
21. @Override
22. protected void onCreate(Bundle savedInstanceState) {
23. super.onCreate(savedInstanceState);
24. setContentView(R.layout.activity_main);
25.
26. listView = (ListView) findViewById(R.id.listView);
27.
28. list = new ArrayList<>();
29. list.add("Apple");
30. list.add("Banana");
31. list.add("Pineapple");
32. list.add("Orange");
33. list.add("Lychee");
34. list.add("Gavava");
35. list.add("Peech");
36. list.add("Melon");
37. list.add("Watermelon");
38. list.add("Papaya");
39.
40. adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,lis
t);
41. listView.setAdapter(adapter);
42. }
43.
44. @Override
45. public boolean onCreateOptionsMenu(Menu menu) {
46. MenuInflater inflater = getMenuInflater();
47. inflater.inflate(R.menu.menu, menu);
48. MenuItem searchViewItem = menu.findItem(R.id.app_bar_search);
49. final SearchView searchView = (SearchView) MenuItemCompat.getAction
View(searchViewItem);
50. searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
51. @Override
52. public boolean onQueryTextSubmit(String query) {
53. searchView.clearFocus();
54. /* if(list.contains(query)){
55. adapter.getFilter().filter(query);
56. }else{
57. Toast.makeText(MainActivity.this, "No Match found",Toast.LENGT
H_LONG).show();
58. }*/
59. return false;
60.
61. }
62.
63. @Override
64. public boolean onQueryTextChange(String newText) {
65. adapter.getFilter().filter(newText);
66. return false;
67. }
68. });
69. return super.onCreateOptionsMenu(menu);
70. }
71. }

Output
Android EditText with TextWatcher
(Searching data from ListView)
Android EditText is a subclass of TextView. EditText is used for entering and
modifying text. While using EditText width, we must specify its input type
in inputType property of EditText which configures the keyboard according to input.

EditText uses TextWatcher interface to watch change made over EditText. For doing
this, EditText calls the addTextChangedListener() method.

Methods of TextWatcher
1. beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3): It is
executed before making any change over EditText.
2. onTextChanged(CharSequence cs, int arg1, int arg2, int arg3): It is executed while
making any change over EditText.
3. afterTextChanged(Editable arg0): It is executed after change made over EditText.
Example of EditText with TextWatcher()
In this example, we will implement EditText with TextWatcher to search data from
ListView.

activity_main.xml
Create an activity_main.xml file in layout folder containing EditText and ListView.

File: activity_main.xml

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


2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. xmlns:tools="http://schemas.android.com/tools"
4. android:layout_width="match_parent"
5. android:layout_height="match_parent"
6. android:paddingBottom="@dimen/activity_vertical_margin"
7. android:paddingLeft="@dimen/activity_horizontal_margin"
8. android:paddingRight="@dimen/activity_horizontal_margin"
9. android:paddingTop="@dimen/activity_vertical_margin"
10. tools:context="com.example.test.searchfromlistview.MainActivity">
11.
12. <EditText
13. android:layout_width="wrap_content"
14. android:layout_height="wrap_content"
15. android:id="@+id/editText"
16. android:inputType="text"
17. android:layout_alignParentTop="true"
18. android:layout_alignParentLeft="true"
19. android:layout_alignParentStart="true"
20. android:layout_alignParentRight="true"
21. android:layout_alignParentEnd="true" />
22.
23. <ListView
24. android:layout_width="wrap_content"
25. android:layout_height="wrap_content"
26. android:id="@+id/listView"
27. android:layout_below="@+id/editText"
28. android:layout_alignParentLeft="true"
29. android:layout_alignParentStart="true" />
30. </RelativeLayout>

Create another file list_item.xml in layout folder which contains data of ListView.

list_item.xm
File: list_item.xml

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


2. <LinearLayout
3. xmlns:android="http://schemas.android.com/apk/res/android"
4. android:orientation="vertical"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent">
7.
8. <TextView android:id="@+id/product_name"
9. android:layout_width="fill_parent"
10. android:layout_height="wrap_content"
11. android:padding="10dip"
12. android:textSize="16dip"
13. android:textStyle="bold"/>
14. </LinearLayout>
Activity class
Activity class

1. package com.example.test.searchfromlistview;
2.
3. import android.os.Bundle;
4. import android.text.Editable;
5. import android.text.TextWatcher;
6. import android.widget.ArrayAdapter;
7. import android.widget.EditText;
8. import android.widget.ListView;
9. import android.support.v7.app.AppCompatActivity;
10. import android.widget.Toast;
11.
12. public class MainActivity extends AppCompatActivity {
13.
14. private ListView lv;
15. private EditText editText;
16. private ArrayAdapter<String> adapter;
17.
18. private String products[] = {"Apple", "Banana","Pinapple", "Orange", "Papaya", "Mel
on",
19. "Grapes", "Water Melon","Lychee", "Guava", "Mango", "Kivi"};
20. @Override
21. protected void onCreate(Bundle savedInstanceState) {
22. super.onCreate(savedInstanceState);
23. setContentView(R.layout.activity_main);
24.
25. lv = (ListView) findViewById(R.id.listView);
26. editText = (EditText) findViewById(R.id.editText);
27. adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.produc
t_name, products);
28. lv.setAdapter(adapter);
29.
30. editText.addTextChangedListener(new TextWatcher() {
31.
32. @Override
33. public void onTextChanged(CharSequence cs, int arg1, int arg2, int ar
g3) {
34. adapter.getFilter().filter(cs);
35. }
36.
37. @Override
38. public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg
3) {
39. Toast.makeText(getApplicationContext(),"before text change",Toast.
LENGTH_LONG).show();
40. }
41.
42. @Override
43. public void afterTextChanged(Editable arg0) {
44. Toast.makeText(getApplicationContext(),"after text change",Toast.LENGTH_L
ONG).show();
45. }
46. });
47. }
48. }

Output
Android Activity Lifecycle

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


The android Activity is the subclass of ContextThemeWrapper class.

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

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

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

Android Activity Lifecycle methods


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

Method Description

onCreate called when activity is first created.

onStart called when activity is becoming visible to the user.

onResume called when activity will start interacting with the user.

onPause called when activity is not visible to the user.


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.

File: activity_main.xml

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


2. <android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.activitylifecycle.MainActivity">
8.
9. <TextView
10. android:layout_width="wrap_content"
11. android:layout_height="wrap_content"
12. android:text="Hello World!"
13. app:layout_constraintBottom_toBottomOf="parent"
14. app:layout_constraintLeft_toLeftOf="parent"
15. app:layout_constraintRight_toRightOf="parent"
16. app:layout_constraintTop_toTopOf="parent" />
17.
18. </android.support.constraint.ConstraintLayout>

Android Activity Lifecycle 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 example.javatpoint.com.activitylifecycle;
2.
3. import android.app.Activity;
4. import android.os.Bundle;
5. import android.util.Log;
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. Log.d("lifecycle","onCreate invoked");
14. }
15. @Override
16. protected void onStart() {
17. super.onStart();
18. Log.d("lifecycle","onStart invoked");
19. }
20. @Override
21. protected void onResume() {
22. super.onResume();
23. Log.d("lifecycle","onResume invoked");
24. }
25. @Override
26. protected void onPause() {
27. super.onPause();
28. Log.d("lifecycle","onPause invoked");
29. }
30. @Override
31. protected void onStop() {
32. super.onStop();
33. Log.d("lifecycle","onStop invoked");
34. }
35. @Override
36. protected void onRestart() {
37. super.onRestart();
38. Log.d("lifecycle","onRestart invoked");
39. }
40. @Override
41. protected void onDestroy() {
42. super.onDestroy();
43. Log.d("lifecycle","onDestroy invoked");
44. }
45. }
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.
The onCreate() and onDestroy() methods are called only once throughout the
activity lifecycle.

Android Intent Tutorial

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

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


etc.

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


the intention to do action.

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

Android intents are mainly used to:

o Start the service


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

Types of Android Intents


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

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

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

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


2. intent.setData(Uri.parse("http://www.javatpoint.com"));
3. startActivity(intent);
2) Explicit Intent
Explicit Intent specifies the component. In such case, intent provides the external
class to be invoked.

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


2. startActivity(i);

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

Android Implicit Intent Example


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

activity_main.xml
File: activity_main.xml

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


2. <android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.implicitintent.MainActivity">
8.
9. <EditText
10. android:id="@+id/editText"
11. android:layout_width="wrap_content"
12. android:layout_height="wrap_content"
13. android:layout_marginEnd="8dp"
14. android:layout_marginStart="8dp"
15. android:layout_marginTop="60dp"
16. android:ems="10"
17. app:layout_constraintEnd_toEndOf="parent"
18. app:layout_constraintHorizontal_bias="0.575"
19. app:layout_constraintStart_toStartOf="parent"
20. app:layout_constraintTop_toTopOf="parent" />
21.
22. <Button
23. android:id="@+id/button"
24. android:layout_width="wrap_content"
25. android:layout_height="wrap_content"
26. android:layout_marginRight="8dp"
27. android:layout_marginLeft="156dp"
28. android:layout_marginTop="172dp"
29. android:text="Visit"
30. app:layout_constraintEnd_toEndOf="parent"
31. app:layout_constraintHorizontal_bias="0.0"
32. app:layout_constraintStart_toStartOf="parent"
33. app:layout_constraintTop_toBottomOf="@+id/editText" />
34. </android.support.constraint.ConstraintLayout>

Activity class
File: MainActivity.java

1. package example.javatpoint.com.implicitintent;
2.
3. import android.content.Intent;
4. import android.net.Uri;
5. import android.support.v7.app.AppCompatActivity;
6. import android.os.Bundle;
7. import android.view.View;
8. import android.widget.Button;
9. import android.widget.EditText;
10.
11. public class MainActivity extends AppCompatActivity {
12.
13. Button button;
14. EditText editText;
15.
16. @Override
17. protected void onCreate(Bundle savedInstanceState) {
18. super.onCreate(savedInstanceState);
19. setContentView(R.layout.activity_main);
20.
21. button = findViewById(R.id.button);
22. editText = findViewById(R.id.editText);
23.
24. button.setOnClickListener(new View.OnClickListener() {
25. @Override
26. public void onClick(View view) {
27. String url=editText.getText().toString();
28. Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse(url));
29. startActivity(intent);
30. }
31. });
32. }
33. }
Output:
Android Explicit Intent Example
Android Explicit intent specifies the component to be invoked from activity. In
other words, we can call another activity in android by explicit intent.

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

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

Android calling one activity from another


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

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


2. <android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.explicitintent.FirstActivity">
8.
9. <TextView
10. android:layout_width="wrap_content"
11. android:layout_height="wrap_content"
12. android:layout_marginEnd="8dp"
13. android:layout_marginStart="8dp"
14. android:layout_marginTop="8dp"
15. android:text="First Activity"
16. app:layout_constraintBottom_toBottomOf="parent"
17. app:layout_constraintEnd_toEndOf="parent"
18. app:layout_constraintHorizontal_bias="0.454"
19. app:layout_constraintLeft_toLeftOf="parent"
20. app:layout_constraintRight_toRightOf="parent"
21. app:layout_constraintStart_toStartOf="parent"
22. app:layout_constraintTop_toTopOf="parent"
23. app:layout_constraintVertical_bias="0.06" />
24.
25. <Button
26. android:id="@+id/button"
27. android:layout_width="wrap_content"
28. android:layout_height="wrap_content"
29. android:layout_marginEnd="8dp"
30. android:layout_marginStart="8dp"
31. android:layout_marginTop="392dp"
32. android:onClick="callSecondActivity"
33. android:text="Call second activity"
34. app:layout_constraintEnd_toEndOf="parent"
35. app:layout_constraintStart_toStartOf="parent"
36. app:layout_constraintTop_toTopOf="parent" />
37.
38. </android.support.constraint.ConstraintLayout>
ActivityOne class
File: MainActivityOne.java

1. package example.javatpoint.com.explicitintent;
2.
3. import android.content.Intent;
4. import android.support.v7.app.AppCompatActivity;
5. import android.os.Bundle;
6. import android.view.View;
7.
8. public class FirstActivity extends AppCompatActivity {
9.
10. @Override
11. protected void onCreate(Bundle savedInstanceState) {
12. super.onCreate(savedInstanceState);
13. setContentView(R.layout.activity_first);
14. }
15. public void callSecondActivity(View view){
16. Intent i = new Intent(getApplicationContext(), SecondActivity.class);
17. i.putExtra("Value1", "Android By Javatpoint");
18. i.putExtra("Value2", "Simple Tutorial");
19. // Set the request code to any code you like, you can identify the
20. // callback via this code
21. startActivity(i);
22. }
23.
24. }
activitytwo_main.xml
File: activitytwo_main.xml

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


2. <android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.explicitintent.SecondActivity">
8.
9. <TextView
10. android:layout_width="wrap_content"
11. android:layout_height="wrap_content"
12. android:layout_marginEnd="8dp"
13. android:layout_marginStart="8dp"
14. android:layout_marginTop="8dp"
15. android:text="Second Activity"
16. app:layout_constraintBottom_toBottomOf="parent"
17. app:layout_constraintEnd_toEndOf="parent"
18. app:layout_constraintHorizontal_bias="0.454"
19. app:layout_constraintLeft_toLeftOf="parent"
20. app:layout_constraintRight_toRightOf="parent"
21. app:layout_constraintStart_toStartOf="parent"
22. app:layout_constraintTop_toTopOf="parent"
23. app:layout_constraintVertical_bias="0.06" />
24.
25. <Button
26. android:id="@+id/button"
27. android:layout_width="wrap_content"
28. android:layout_height="wrap_content"
29. android:layout_marginEnd="8dp"
30. android:layout_marginStart="8dp"
31. android:layout_marginTop="392dp"
32. android:onClick="callFirstActivity"
33. android:text="Call first activity"
34. app:layout_constraintEnd_toEndOf="parent"
35. app:layout_constraintStart_toStartOf="parent"
36. app:layout_constraintTop_toTopOf="parent" />
37. </android.support.constraint.ConstraintLayout>
ActivityTwo class
File: MainActivityTwo.java
1. package example.javatpoint.com.explicitintent;
2.
3. import android.content.Intent;
4. import android.support.v7.app.AppCompatActivity;
5. import android.os.Bundle;
6. import android.view.View;
7. import android.widget.Toast;
8.
9. public class SecondActivity extends AppCompatActivity {
10.
11. @Override
12. protected void onCreate(Bundle savedInstanceState) {
13. super.onCreate(savedInstanceState);
14. setContentView(R.layout.activity_second);
15. Bundle extras = getIntent().getExtras();
16. String value1 = extras.getString("Value1");
17. String value2 = extras.getString("Value2");
18. Toast.makeText(getApplicationContext(),"Values are:\n First value: "+value1+
19. "\n Second Value: "+value2, Toast.LENGTH_LONG).show();
20. }
21. public void callFirstActivity(View view){
22. Intent i = new Intent(getApplicationContext(), FirstActivity.class);
23. startActivity(i);
24. }
25.
26. }
Output:
Android StartActivityForResult
Example
By the help of android startActivityForResult() method, we can get result from
another activity.

By the help of android startActivityForResult() method, we can send information from


one activity to another and vice-versa. The android startActivityForResult method,
requires a result from the second activity (activity to be invoked).

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


automatically when second activity returns result.

Method Signature
There are two variants of startActivityForResult() method.
1. public void startActivityForResult (Intent intent, int requestCode)
2. public void startActivityForResult (Intent intent, int requestCode, Bundle options)

Android StartActivityForResult Example


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

activity_main.xml

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

File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/
android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".MainActivity" >
10. <TextView
11. android:id="@+id/textView1"
12. android:layout_width="wrap_content"
13. android:layout_height="wrap_content"
14. android:layout_alignLeft="@+id/button1"
15. android:layout_alignParentTop="true"
16. android:layout_marginTop="48dp"
17. android:text="Default Message" />
18. <Button
19. android:id="@+id/button1"
20. android:layout_width="wrap_content"
21. android:layout_height="wrap_content"
22. android:layout_below="@+id/textView1"
23. android:layout_centerHorizontal="true"
24. android:layout_marginTop="42dp"
25. android:text="GetMessage" />
26. </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/
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=".SecondActivity" >
10. <EditText
11. android:id="@+id/editText1"
12. android:layout_width="wrap_content"
13. android:layout_height="wrap_content"
14. android:layout_alignParentTop="true"
15. android:layout_marginTop="61dp"
16. android:layout_toRightOf="@+id/textView1"
17. android:ems="10" />
18. <TextView
19. android:id="@+id/textView1"
20. android:layout_width="wrap_content"
21. android:layout_height="wrap_content"
22. android:layout_alignBaseline="@+id/editText1"
23. android:layout_alignBottom="@+id/editText1"
24. android:layout_alignParentLeft="true"
25. android:text="Enter Message:" />
26. <Button
27. android:id="@+id/button1"
28. android:layout_width="wrap_content"
29. android:layout_height="wrap_content"
30. android:layout_below="@+id/editText1"
31. android:layout_centerHorizontal="true"
32. android:layout_marginTop="34dp"
33. android:text="Submit" />
34. </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. import android.os.Bundle;
3. import android.app.Activity;
4. import android.content.Intent;
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. public class MainActivity extends Activity {
11. TextView textView1;
12. Button button1;
13. @Override
14. protected void onCreate(Bundle savedInstanceState) {
15. super.onCreate(savedInstanceState);
16. setContentView(R.layout.activity_main);
17. textView1=(TextView)findViewById(R.id.textView1);
18. button1=(Button)findViewById(R.id.button1);
19. button1.setOnClickListener(new OnClickListener() {
20. @Override
21. public void onClick(View arg0) {
22. Intent intent=new Intent(MainActivity.this,SecondActivity.class);
23. startActivityForResult(intent, 2);// Activity is started with requestCod
e2
24. }
25. });
26. }
27. // Call Back method to get the Message form other Activity
28. @Override
29. protected void onActivityResult(int requestCode, int resultCode, Intent d
ata)
30. {
31. super.onActivityResult(requestCode, resultCode, data);
32. // check if the request code is same as what is passed here it is 2
33. if(requestCode==2)
34. {
35. String message=data.getStringExtra("MESSAGE");
36. textView1.setText(message);
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.main, menu);
43. return true;
44. }
45. }
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. import android.os.Bundle;
3. import android.app.Activity;
4. import android.content.Intent;
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.TextView;
11. public class SecondActivity 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_second);
18. editText1=(EditText)findViewById(R.id.editText1);
19. button1=(Button)findViewById(R.id.button1);
20. button1.setOnClickListener(new OnClickListener() {
21. @Override
22. public void onClick(View arg0) {
23. String message=editText1.getText().toString();
24. Intent intent=new Intent();
25. intent.putExtra("MESSAGE",message);
26. setResult(2,intent);
27. finish();//finishing activity
28. }
29. });
30. }
31. @Override
32. public boolean onCreateOptionsMenu(Menu menu) {
33. // Inflate the menu; this adds items to the action bar if it is present.
34. getMenuInflater().inflate(R.menu.second, menu);
35. return true;
36. }
37. }

download this android example


Output:

Android Share App Data


(ACTION_SEND)
Android uses ACTION_SEND event of android.content.Intent class to send data
from one activity to another and from current activity to outside the application.
Intent class needs to specify the data and its type which is to be share.
Most commonly, ACTION_SEND action sends URL of build-in Browser app. While
sharing the data, Intent call createChooser() method which takes Intent object and
specify the title of the chooser dialog. Intent.createChooser() method allows to
display the chooser.

Example of ACTION_SEND
In this example, we are going to share plain text which is a URL of browser.

activity_main.xml

File: activity_main.xml

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


2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. xmlns:tools="http://schemas.android.com/tools"
4. android:layout_width="match_parent"
5. android:layout_height="match_parent"
6. android:paddingBottom="@dimen/activity_vertical_margin"
7. android:paddingLeft="@dimen/activity_horizontal_margin"
8. android:paddingRight="@dimen/activity_horizontal_margin"
9. android:paddingTop="@dimen/activity_vertical_margin"
10. tools:context="com.example.test.shareapp.MainActivity">
11.
12. <TextView
13. android:layout_width="wrap_content"
14. android:layout_height="wrap_content"
15. android:text="Hello World!"
16. android:id="@+id/textView" />
17.
18. <Button
19. android:layout_width="wrap_content"
20. android:layout_height="wrap_content"
21. android:text="Share App"
22. android:id="@+id/button"
23. android:layout_marginBottom="95dp"
24. android:layout_alignParentBottom="true"
25. android:layout_centerHorizontal="true" />
26.
27. </RelativeLayout>
Activity class
File: MainActivity.java

1. package com.example.test.shareapp;
2.
3. import android.content.Intent;
4. import android.support.v7.app.AppCompatActivity;
5. import android.os.Bundle;
6. import android.view.View;
7. import android.widget.Button;
8.
9. public class MainActivity extends AppCompatActivity {
10. Button sharebutton;
11. @Override
12. protected void onCreate(Bundle savedInstanceState) {
13. super.onCreate(savedInstanceState);
14. setContentView(R.layout.activity_main);
15.
16. sharebutton=(Button)findViewById(R.id.button);
17. sharebutton.setOnClickListener(new View.OnClickListener() {
18. @Override
19. public void onClick(View v) {
20. Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
21. shareIntent.setType("text/plain");
22. shareIntent.putExtra(Intent.EXTRA_SUBJECT,"Insert Subject here");
23. String app_url = " https://play.google.com/store/apps/details?
id=my.example.javatpoint";
24. shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,app_url);
25. startActivity(Intent.createChooser(shareIntent, "Share via"));
26. }
27. });
28. }
29. }

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

Android fragment lifecycle is affected by activity lifecycle because fragments are


included in activity.

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

The FragmentManager class is responsible to make interaction between fragment


objects.

Android Fragment Lifecycle


The lifecycle of android fragment is like the activity lifecycle. There are 12 lifecycle
methods for fragment.
Android Fragment Lifecycle Methods

No. Method Description

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


with activity.

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

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


ViewGroup, Bundle)

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


onCreate() method.

5) onViewStateRestored(Bundle) It provides information to the fragment


that all the saved state of fragment view
hierarchy has been restored.

6) onStart() makes the fragment visible.

7) onResume() makes the fragment interactive.

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


interactive.

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

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

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


fragment state.

12) onDetach() It is called immediately prior to the


fragment no longer being associated with
its activity.
Android Fragment Example
Let's have a look at the simple example of android fragment.

activity_main.xml
File: activity_main.xml

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


2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="fill_parent"
6. android:layout_height="fill_parent"
7. tools:context="example.javatpoint.com.fragmentexample.MainActivity">
8.
9. <fragment
10. android:id="@+id/fragment1"
11. android:name="example.javatpoint.com.fragmentexample.Fragment1"
12. android:layout_width="0px"
13. android:layout_height="match_parent"
14. android:layout_weight="1"
15. />
16.
17. <fragment
18. android:id="@+id/fragment2"
19. android:name="example.javatpoint.com.fragmentexample.Fragment2"
20. android:layout_width="0px"
21. android:layout_height="match_parent"
22. android:layout_weight="1"
23. />
24.
25. </LinearLayout>
File: fragment_fragment1.xml

1. <FrameLayout 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:background="#F5F5DC"
6. tools:context="example.javatpoint.com.fragmentexample.Fragment1">
7.
8. <!-- TODO: Update blank fragment layout -->
9. <TextView
10. android:layout_width="match_parent"
11. android:layout_height="match_parent"
12. android:text="@string/hello_blank_fragment" />
13.
14. </FrameLayout>
File: fragment_fragment2.xml

1. <FrameLayout 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:background="#F0FFFF"
6. tools:context="example.javatpoint.com.fragmentexample.Fragment2">
7.
8. <!-- TODO: Update blank fragment layout -->
9. <TextView
10. android:layout_width="match_parent"
11. android:layout_height="match_parent"
12. android:text="@string/hello_blank_fragment" />
13.
14. </FrameLayout>

MainActivity class
File: MainActivity.java

1. package example.javatpoint.com.fragmentexample;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5.
6. public class MainActivity extends AppCompatActivity {
7.
8. @Override
9. protected void onCreate(Bundle savedInstanceState) {
10. super.onCreate(savedInstanceState);
11. setContentView(R.layout.activity_main);
12. }
13. }

File: Fragment1.java

1. package example.javatpoint.com.fragmentexample;
2. import android.os.Bundle;
3. import android.support.v4.app.Fragment;
4. import android.view.LayoutInflater;
5. import android.view.View;
6. import android.view.ViewGroup;
7.
8. public class Fragment1 extends Fragment {
9.
10. @Override
11. public void onCreate(Bundle savedInstanceState) {
12. super.onCreate(savedInstanceState);
13. }
14.
15. @Override
16. public View onCreateView(LayoutInflater inflater, ViewGroup container,
17. Bundle savedInstanceState) {
18. // Inflate the layout for this fragment
19. return inflater.inflate(R.layout.fragment_fragment1, container, false);
20. }
21. }

File: Fragment2.java

1. package example.javatpoint.com.fragmentexample;
2.
3. import android.os.Bundle;
4. import android.support.v4.app.Fragment;
5. import android.view.LayoutInflater;
6. import android.view.View;
7. import android.view.ViewGroup;
8.
9. public class Fragment2 extends Fragment {
10.
11. @Override
12. public void onCreate(Bundle savedInstanceState) {
13. super.onCreate(savedInstanceState);
14. }
15.
16. @Override
17. public View onCreateView(LayoutInflater inflater, ViewGroup container,
18. Bundle savedInstanceState) {
19. // Inflate the layout for this fragment
20. return inflater.inflate(R.layout.fragment_fragment2, container, false);
21. }
22.
23. }
Output:

Android Option Menu Example


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

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

Here, we are inflating the menu by calling the inflate() method


of MenuInflater class. To perform event handling on menu items, you need to
override onOptionsItemSelected() method of Activity class.

Android Option Menu Example


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

We have only one textview in this file.

File: activity_main.xml

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


2. <android.support.design.widget.CoordinatorLayout xmlns:android="http://
schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.optionmenu.MainActivity">
8.
9. <android.support.design.widget.AppBarLayout
10. android:layout_width="match_parent"
11. android:layout_height="wrap_content"
12. android:theme="@style/AppTheme.AppBarOverlay">
13.
14. <android.support.v7.widget.Toolbar
15. android:id="@+id/toolbar"
16. android:layout_width="match_parent"
17. android:layout_height="?attr/actionBarSize"
18. android:background="?attr/colorPrimary"
19. app:popupTheme="@style/AppTheme.PopupOverlay" />
20.
21. </android.support.design.widget.AppBarLayout>
22.
23. <include layout="@layout/content_main" />
24.
25. </android.support.design.widget.CoordinatorLayout>
File: context_main.xml

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


2. <android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. app:layout_behavior="@string/appbar_scrolling_view_behavior"
8. tools:context="example.javatpoint.com.optionmenu.MainActivity"
9. tools:showIn="@layout/activity_main">
10.
11. <TextView
12. android:layout_width="wrap_content"
13. android:layout_height="wrap_content"
14. android:text="Hello World!"
15. app:layout_constraintBottom_toBottomOf="parent"
16. app:layout_constraintLeft_toLeftOf="parent"
17. app:layout_constraintRight_toRightOf="parent"
18. app:layout_constraintTop_toTopOf="parent" />
19.
20. </android.support.constraint.ConstraintLayout>
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:android="http://schemas.android.com/apk/res/android"
2. xmlns:app="http://schemas.android.com/apk/res-auto"
3. xmlns:tools="http://schemas.android.com/tools"
4. tools:context="example.javatpoint.com.optionmenu.MainActivity">
5.
6. <item android:id="@+id/item1"
7. android:title="Item 1"/>
8. <item android:id="@+id/item2"
9. android:title="Item 2"/>
10. <item android:id="@+id/item3"
11. android:title="Item 3"
12. app:showAsAction="withText"/>
13. </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 example.javatpoint.com.optionmenu;
2.
3. import android.os.Bundle;
4. import android.support.v7.app.AppCompatActivity;
5. import android.support.v7.widget.Toolbar;
6. import android.view.Menu;
7. import android.view.MenuItem;
8. import android.widget.Toast;
9.
10. public class MainActivity extends AppCompatActivity {
11.
12. @Override
13. protected void onCreate(Bundle savedInstanceState) {
14. super.onCreate(savedInstanceState);
15. setContentView(R.layout.activity_main);
16. Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
17. setSupportActionBar(toolbar);
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.menu_main, menu);
24. return true;
25. }
26.
27. @Override
28. public boolean onOptionsItemSelected(MenuItem item) {
29. int id = item.getItemId();
30. switch (id){
31. case R.id.item1:
32. Toast.makeText(getApplicationContext(),"Item 1 Selected",Toast.LENGTH_LO
NG).show();
33. return true;
34. case R.id.item2:
35. Toast.makeText(getApplicationContext(),"Item 2 Selected",Toast.LEN
GTH_LONG).show();
36. return true;
37. case R.id.item3:
38. Toast.makeText(getApplicationContext(),"Item 3 Selected",Toast.LENGTH_LO
NG).show();
39. return true;
40. default:
41. return super.onOptionsItemSelected(item);
42. }
43. }
44. }

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:android="http://schemas.android.com/apk/res/android"
2. xmlns:app="http://schemas.android.com/apk/res-auto"
3. xmlns:tools="http://schemas.android.com/tools"
4. tools:context="example.javatpoint.com.optionmenu.MainActivity">
5.
6. <item android:id="@+id/item1"
7. android:title="Item 1"
8. app:showAsAction="always"
9. android:icon="@android:drawable/btn_star"/>
10. <item android:id="@+id/item2"
11. android:title="Item 2"
12. app:showAsAction="ifRoom"
13. android:icon="@android:drawable/btn_plus"/>
14. <item android:id="@+id/item3"
15. android:title="Item 3"
16. app:showAsAction="withText"
17. android:icon="@android:drawable/btn_plus"/>
18. </menu>

Android Context Menu Example


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

It affects the selected content while doing action on it.

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. <?xml version="1.0" encoding="utf-8"?>


2. <android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.contextmenu.MainActivity">
8.
9. <ListView
10. android:layout_width="368dp"
11. android:layout_height="495dp"
12. android:id="@+id/listView"
13. android:layout_marginEnd="8dp"
14. android:layout_marginStart="8dp"
15. android:layout_marginTop="8dp"
16. app:layout_constraintEnd_toEndOf="parent"
17. app:layout_constraintHorizontal_bias="0.0"
18. app:layout_constraintStart_toStartOf="parent"
19. app:layout_constraintTop_toTopOf="parent" />
20. </android.support.constraint.ConstraintLayout>

main_menu.xml

Create a separate menu_main.xml file in menu directory for menu items.

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


2. <menu xmlns:android="http://schemas.android.com/apk/res/android">
3. <item android:id="@+id/call"
4. android:title="Call" />
5. <item android:id="@+id/sms"
6. android:title="SMS" />
7. </menu>
Activity class

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

File: MainActivity.java

1. package example.javatpoint.com.contextmenu;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.ContextMenu;
6. import android.view.MenuInflater;
7. import android.view.MenuItem;
8. import android.view.View;
9. import android.widget.ArrayAdapter;
10. import android.widget.ListView;
11. import android.widget.Toast;
12.
13. public class MainActivity extends AppCompatActivity {
14. ListView listView;
15. String contacts[]={"Ajay","Sachin","Sumit","Tarun","Yogesh"};
16. @Override
17. protected void onCreate(Bundle savedInstanceState) {
18. super.onCreate(savedInstanceState);
19. setContentView(R.layout.activity_main);
20. listView=(ListView)findViewById(R.id.listView);
21. ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.
R.layout.simple_list_item_1,contacts);
22. listView.setAdapter(adapter);
23. // Register the ListView for Context menu
24. registerForContextMenu(listView);
25. }
26. @Override
27. public void onCreateContextMenu(ContextMenu menu, View v, ContextMe
nu.ContextMenuInfo menuInfo)
28. {
29. super.onCreateContextMenu(menu, v, menuInfo);
30. MenuInflater inflater = getMenuInflater();
31. inflater.inflate(R.menu.menu_main, menu);
32. menu.setHeaderTitle("Select The Action");
33. }
34. @Override
35. public boolean onContextItemSelected(MenuItem item){
36. if(item.getItemId()==R.id.call){
37. Toast.makeText(getApplicationContext(),"calling code",Toast.LENGTH_L
ONG).show();
38. }
39. else if(item.getItemId()==R.id.sms){
40. Toast.makeText(getApplicationContext(),"sending sms code",Toast.LENGTH_LO
NG).show();
41. }else{
42. return false;
43. }
44. return true;
45. }
46. }
Output:

Output after long press on the listview.


Output after clicking on the context menu.
Android Popup Menu Example
Android Popup Menu displays the menu below the anchor text if space is available
otherwise above the anchor text. It disappears if you click outside the popup menu.

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

Android Popup Menu Example


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

activity_main.xml

It contains only one button.

File: activity_main.xml

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


2. <android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.popupmenu.MainActivity">
8.
9. <Button
10. android:layout_width="wrap_content"
11. android:layout_height="wrap_content"
12. android:id="@+id/button"
13. android:text="Click"
14. app:layout_constraintBottom_toBottomOf="parent"
15. app:layout_constraintLeft_toLeftOf="parent"
16. app:layout_constraintRight_toRightOf="parent"
17. app:layout_constraintTop_toTopOf="parent" />
18.
19. </android.support.constraint.ConstraintLayout>
popup_menu.xml

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

File: poupup_menu.xml

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


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

It displays the popup menu on button click.

File: MainActivity.java

1. package example.javatpoint.com.popupmenu;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.MenuItem;
6. import android.view.View;
7. import android.widget.Button;
8. import android.widget.PopupMenu;
9. import android.widget.Toast;
10.
11. public class MainActivity extends AppCompatActivity {
12. Button button;
13.
14. @Override
15. protected void onCreate(Bundle savedInstanceState) {
16. super.onCreate(savedInstanceState);
17. setContentView(R.layout.activity_main);
18.
19. button = (Button) findViewById(R.id.button);
20. button.setOnClickListener(new View.OnClickListener() {
21.
22. @Override
23. public void onClick(View v) {
24. //Creating the instance of PopupMenu
25. PopupMenu popup = new PopupMenu(MainActivity.this, button);
26. //Inflating the Popup using xml file
27. popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMe
nu());
28.
29. //registering popup with OnMenuItemClickListener
30. popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickList
ener() {
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

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


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

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


Moreover, service can be bounded by a component to perform interactivity and inter
process communication (IPC).

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

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

Life Cycle of Android Service


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

1. Started
2. Bound

1) Started Service

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

2) Bound Service

A service is bound when another component (e.g. client) calls bindService() method.
The 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. <?xml version="1.0" encoding="utf-8"?>


2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.androidservice.MainActivity">
8.
9.
10. <Button
11. android:id="@+id/buttonStart"
12. android:layout_width="wrap_content"
13. android:layout_height="wrap_content"
14. android:layout_alignParentTop="true"
15. android:layout_centerHorizontal="true"
16. android:layout_marginTop="74dp"
17. android:text="Start Service" />
18.
19. <Button
20. android:id="@+id/buttonStop"
21. android:layout_width="wrap_content"
22. android:layout_height="wrap_content"
23. android:layout_centerHorizontal="true"
24. android:layout_centerVertical="true"
25. android:text="Stop Service" />
26.
27. <Button
28. android:id="@+id/buttonNext"
29. android:layout_width="wrap_content"
30. android:layout_height="wrap_content"
31. android:layout_alignParentBottom="true"
32. android:layout_centerHorizontal="true"
33. android:layout_marginBottom="63dp"
34. android:text="Next Page" />
35. </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. <?xml version="1.0" encoding="utf-8"?>


2. <android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.androidservice.NextPage">
8.
9. <TextView
10. android:id="@+id/textView"
11. android:layout_width="wrap_content"
12. android:layout_height="wrap_content"
13. android:layout_marginEnd="8dp"
14. android:layout_marginStart="8dp"
15. android:layout_marginTop="200dp"
16. android:text="Next Page"
17. app:layout_constraintEnd_toEndOf="parent"
18. app:layout_constraintStart_toStartOf="parent"
19. app:layout_constraintTop_toTopOf="parent" />
20. </android.support.constraint.ConstraintLayout>

Service class

Now create the service implemenation class by inheriting the Service class and
overridding its callback methods.

File: MyService.java

1. package example.javatpoint.com.androidservice;
2.
3. import android.app.Service;
4. import android.content.Intent;
5. import android.media.MediaPlayer;
6. import android.os.IBinder;
7. import android.support.annotation.Nullable;
8. import android.widget.Toast;
9.
10. public class MyService extends Service {
11. MediaPlayer myPlayer;
12. @Nullable
13. @Override
14. public IBinder onBind(Intent intent) {
15. return null;
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. @Override
25. public void onStart(Intent intent, int startid) {
26. Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
27. myPlayer.start();
28. }
29. @Override
30. public void onDestroy() {
31. Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
32. myPlayer.stop();
33. }
34. }

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 example.javatpoint.com.androidservice;
2.
3. import android.content.Intent;
4. import android.support.v7.app.AppCompatActivity;
5. import android.os.Bundle;
6. import android.view.View;
7. import android.widget.Button;
8.
9. public class MainActivity extends AppCompatActivity implements View.OnCl
ickListener{
10. Button buttonStart, buttonStop,buttonNext;
11. @Override
12. protected void onCreate(Bundle savedInstanceState) {
13. super.onCreate(savedInstanceState);
14. setContentView(R.layout.activity_main);
15.
16. buttonStart = findViewById(R.id.buttonStart);
17. buttonStop = findViewById(R.id.buttonStop);
18. buttonNext = findViewById(R.id.buttonNext);
19.
20. buttonStart.setOnClickListener(this);
21. buttonStop.setOnClickListener(this);
22. buttonNext.setOnClickListener(this);
23.
24.
25. }
26. public void onClick(View src) {
27. switch (src.getId()) {
28. case R.id.buttonStart:
29.
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 example.javatpoint.com.androidservice;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5.
6. public class NextPage extends AppCompatActivity {
7.
8. @Override
9. protected void onCreate(Bundle savedInstanceState) {
10. super.onCreate(savedInstanceState);
11. setContentView(R.layout.activity_next);
12. }
13. }

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:android="http://schemas.android.com/apk/res/android"
3. package="example.javatpoint.com.androidservice">
4.
5. <application
6. android:allowBackup="true"
7. android:icon="@mipmap/ic_launcher"
8. android:label="@string/app_name"
9. android:roundIcon="@mipmap/ic_launcher_round"
10. android:supportsRtl="true"
11. android:theme="@style/AppTheme">
12. <activity android:name=".MainActivity">
13. <intent-filter>
14. <action android:name="android.intent.action.MAIN" />
15.
16. <category android:name="android.intent.category.LAUNCHER" />
17. </intent-filter>
18. </activity>
19. <activity android:name=".NextPage"></activity>
20. <service
21. android:name=".MyService"
22. android:enabled="true" />
23. </application>
24.
25. </manifest>
Output:
Android AlarmManager
Android AlarmManager allows you to access system alarm.

By the help of Android AlarmManager in android, you can schedule your


application to run at a specific time in the future. It works whether your phone is
running or not.

The Android AlarmManager holds a CPU wake lock that provides guarantee not to
sleep the phone until broadcast is handled.

Android AlarmManager Example


Let's see a simple AlarmManager example that runs after a specific time provided by
user.
activity_main.xml

You need to drag only a edittext and a button as given below.

File: activity_main.xml

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


2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.alarmmanager.MainActivity">
8.
9. <Button
10. android:id="@+id/button"
11. android:layout_width="wrap_content"
12. android:layout_height="wrap_content"
13. android:text="Start"
14. android:layout_alignParentBottom="true"
15. android:layout_centerHorizontal="true"
16. android:layout_marginBottom="103dp" />
17.
18. <EditText
19. android:id="@+id/time"
20. android:layout_width="wrap_content"
21. android:layout_height="wrap_content"
22. android:layout_alignParentTop="true"
23. android:layout_centerHorizontal="true"
24. android:layout_marginTop="22dp"
25. android:ems="10" />
26. </RelativeLayout>

Activity class

The activity class starts the alarm service when user clicks on the button.

File: MainActivity.java
1. package example.javatpoint.com.alarmmanager;
2.
3. import android.app.AlarmManager;
4. import android.app.PendingIntent;
5. import android.content.Intent;
6. import android.support.v7.app.AppCompatActivity;
7. import android.os.Bundle;
8. import android.view.View;
9. import android.widget.Button;
10. import android.widget.EditText;
11. import android.widget.Toast;
12.
13. public class MainActivity extends AppCompatActivity {
14. Button start;
15. @Override
16. protected void onCreate(Bundle savedInstanceState) {
17. super.onCreate(savedInstanceState);
18. setContentView(R.layout.activity_main);
19. start= findViewById(R.id.button);
20.
21. start.setOnClickListener(new View.OnClickListener() {
22. @Override
23. public void onClick(View view) {
24. startAlert();
25. }
26. });
27. }
28.
29. public void startAlert(){
30. EditText text = findViewById(R.id.time);
31. int i = Integer.parseInt(text.getText().toString());
32. Intent intent = new Intent(this, MyBroadcastReceiver.class);
33. PendingIntent pendingIntent = PendingIntent.getBroadcast(
34. this.getApplicationContext(), 234324243, intent, 0);
35. AlarmManager alarmManager = (AlarmManager) getSystemService(ALAR
M_SERVICE);
36. alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
37. + (i * 1000), pendingIntent);
38. Toast.makeText(this, "Alarm set in " + i + " seconds",Toast.LENGTH_LONG).show()
;
39. }
40. }

Let's create BroadcastReceiver class that starts alarm.

File: MyBroadcastReceiver.java

1. package example.javatpoint.com.alarmmanager;
2.
3. import android.content.BroadcastReceiver;
4. import android.content.Context;
5. import android.content.Intent;
6. import android.media.MediaPlayer;
7. import android.widget.Toast;
8.
9. public class MyBroadcastReceiver extends BroadcastReceiver {
10. MediaPlayer mp;
11. @Override
12. public void onReceive(Context context, Intent intent) {
13. mp=MediaPlayer.create(context, R.raw.alarm);
14. mp.start();
15. Toast.makeText(context, "Alarm....", Toast.LENGTH_LONG).show();
16. }
17. }

File: AndroidManifest.xml

You need to provide a receiver entry in AndroidManifest.xml file.

1. <receiver android:name="MyBroadcastReceiver" >


2. </receiver>

Let's see the full code of AndroidManifest.xml file.

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


2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3. package="example.javatpoint.com.alarmmanager">
4.
5. <application
6. android:allowBackup="true"
7. android:icon="@mipmap/ic_launcher"
8. android:label="@string/app_name"
9. android:roundIcon="@mipmap/ic_launcher_round"
10. android:supportsRtl="true"
11. android:theme="@style/AppTheme">
12. <activity android:name=".MainActivity">
13. <intent-filter>
14. <action android:name="android.intent.action.MAIN" />
15.
16. <category android:name="android.intent.category.LAUNCHER" />
17. </intent-filter>
18. </activity>
19. <receiver android:name="MyBroadcastReceiver" >
20. </receiver>
21. </application>
22.
23. </manifest>
Output:
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

public void setDataSource(String path) sets the data source (file path or http
url) to use.

public void prepare() prepares the player for playback


synchronously.

public void start() it starts or resumes the playback.

public void stop() it stops the playback.

public void pause() it pauses the playback.

public boolean isPlaying() checks if media player is playing.

public void seekTo(int millis) seeks to specified time in


miliseconds.

public void setLooping(boolean looping) sets the player for looping or non-
looping.

public boolean isLooping() checks if the player is looping or


non-looping.

public void selectTrack(int index) it selects a track for the specified


index.

public int getCurrentPosition() returns the current playback position.

public int getDuration() returns duration of the file.

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/
android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".MainActivity" >
10.
11. <TextView
12. android:id="@+id/textView1"
13. android:layout_width="wrap_content"
14. android:layout_height="wrap_content"
15. android:layout_alignParentTop="true"
16. android:layout_marginTop="30dp"
17. android:text="Audio Controller" />
18.
19. <Button
20. android:id="@+id/button1"
21. style="?android:attr/buttonStyleSmall"
22. android:layout_width="wrap_content"
23. android:layout_height="wrap_content"
24. android:layout_alignLeft="@+id/textView1"
25. android:layout_below="@+id/textView1"
26. android:layout_marginTop="48dp"
27. android:text="start" />
28.
29. <Button
30. android:id="@+id/button2"
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. sdcar
d) /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 playback.

public void suspend() suspends the playback.

public void resume() resumes the playback.

public void seekTo(int millis) seeks to specified time in


miliseconds.

activity_main.xml

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

File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/
android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
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/
android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".MainActivity" >
10.
11. <Button
12. android:id="@+id/button1"
13. android:layout_width="wrap_content"
14. android:layout_height="wrap_content"
15. android:layout_alignParentLeft="true"
16. android:layout_alignParentTop="true"
17. android:layout_marginLeft="68dp"
18. android:layout_marginTop="50dp"
19. android:text="Start Recording"
20. android:onClick="startRecording"
21. />
22.
23. <Button
24. android:id="@+id/button2"
25. android:layout_width="wrap_content"
26. android:layout_height="wrap_content"
27. android:layout_alignLeft="@+id/button1"
28. android:layout_below="@+id/button1"
29. android:layout_marginTop="64dp"
30. android:text="Stop Recording"
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
library.
60. addRecordingToMediaLibrary();
61. }
62.
63. protected void addRecordingToMediaLibrary() {
64. //creating content values of size 4
65. ContentValues values = new ContentValues(4);
66. long current = System.currentTimeMillis();
67. values.put(MediaStore.Audio.Media.TITLE, "audio" + audiofile.getName())
;
68. values.put(MediaStore.Audio.Media.DATE_ADDED, (int) (current / 1000));
69. values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/3gpp");
70. values.put(MediaStore.Audio.Media.DATA, audiofile.getAbsolutePath());
71.
72. //creating content resolver and storing it in the external content uri
73. ContentResolver contentResolver = getContentResolver();
74. Uri base = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
75. Uri newUri = contentResolver.insert(base, values);
76.
77. //sending broadcast message to scan the media file so that it can be av
ailable
78. sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, newUri)
);
79. Toast.makeText(this, "Added File " + newUri, Toast.LENGTH_LONG).show(
);
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


o TextToSpeech(Context context, TextToSpeech.OnInitListener)

Methods of TextToSpeech class

The commonly used methods of TextToSpeech class are as follows:

Method Description

int speak (String text, int converts the text into speech. Queue Mode may be
queueMode, QUEUE_ADD or QUEUE_FLUSH. Request parameters can
HashMap params) be null, KEY_PARAM_STREAM, 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 loc) it sets the locale specific language for the speech.

void shutdown() it releases the resource set by TextToSpeech Engine.

int stop() it interrupts the current utterance (whether played or


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/
android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <EditText
8. android:id="@+id/editText1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentLeft="true"
12. android:layout_alignParentTop="true"
13. android:layout_marginLeft="77dp"
14. android:layout_marginTop="42dp"
15. android:ems="10" >
16.
17. <requestFocus />
18. </EditText>
19.
20. <Button
21. android:id="@+id/button1"
22. android:layout_width="wrap_content"
23. android:layout_height="wrap_content"
24. android:layout_alignLeft="@+id/editText1"
25. android:layout_below="@+id/editText1"
26. android:layout_marginLeft="59dp"
27. android:layout_marginTop="39dp"
28. android:text="Speak" />
29.
30. <TextView
31. android:id="@+id/textView1"
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. }

download this android example

You need to run it on the Real Device (e.g. Mobile) to test the application.

Next: TextToSpeech example with speed and pitch option

Android TextToSpeech Example


TextToSpeech class is responsible to convert text into speech. It provides a lot of
methods to control the speech such as setSpeedRate(), setPitch() etc.

In this example, we are going to see the android texttospeech example with speed
and pitch option.

activity_main.xml

Drag 2 textviews, 1 edittext, 1 spinner and 1 button for the layout. Now the
activity_main.xml file will look like this:

File: activity_main.xml
1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/
android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <EditText
8. android:id="@+id/editText1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignBaseline="@+id/textView1"
12. android:layout_alignBottom="@+id/textView1"
13. android:layout_alignParentRight="true"
14. android:layout_marginRight="58dp"
15. android:ems="10" >
16.
17. <requestFocus />
18. </EditText>
19.
20. <Button
21. android:id="@+id/button1"
22. android:layout_width="wrap_content"
23. android:layout_height="wrap_content"
24. android:layout_below="@+id/editText1"
25. android:layout_centerHorizontal="true"
26. android:layout_marginTop="28dp"
27. android:text="Speak" />
28.
29. <TextView
30. android:id="@+id/textView2"
31. android:layout_width="wrap_content"
32. android:layout_height="wrap_content"
33. android:layout_below="@+id/button1"
34. android:layout_marginTop="62dp"
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>(this,andr
oid.R.layout.simple_spinner_item, lables);
121.
122. // Drop down layout style - list view with radio button
123. dataAdapter.setDropDownViewResource(android.R.layout.simple_spi
nner_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 po
sition,
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/
android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".MainActivity" >
10.
11. <TextView
12. android:id="@+id/textView1"
13. android:layout_width="wrap_content"
14. android:layout_height="wrap_content"
15. android:layout_alignParentLeft="true"
16. android:layout_alignParentTop="true"
17. android:layout_marginLeft="38dp"
18. android:layout_marginTop="30dp"
19. android:text="Phone Details:" />
20.
21. </RelativeLayout>
Activity class

Now, write the code to display the information about the telephony services.

File: MainActivity.java

1. package com.javatpoint.telephonymanager;
2.
3. import android.os.Bundle;
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.TELEPH
ONY_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:

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/
android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <Button
8. android:id="@+id/button1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentTop="true"
12. android:layout_centerHorizontal="true"
13. android:layout_marginTop="118dp"
14. android:text="Call" />
15.
16. <EditText
17. android:id="@+id/editText1"
18. android:layout_width="wrap_content"
19. android:layout_height="wrap_content"
20. android:layout_alignParentTop="true"
21. android:layout_centerHorizontal="true"
22. android:layout_marginTop="25dp"
23. android:ems="10" />
24.
25. </RelativeLayout>

Write the permission code in Android-Manifest.xml file

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 sen
d message
6. SmsManager sms=SmsManager.getDefault();
7. sms.sendTextMessage("8802177690", null, "hello javatpoint", pi,null);

Example of sending sms in android


activity_main.xml

Drag the 2 edittexts, 2 textviews and 1 button from the pallete, now the
activity_main.xml file will like this:

File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/
android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <EditText
8. android:id="@+id/editText1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentRight="true"
12. android:layout_alignParentTop="true"
13. android:layout_marginRight="20dp"
14. android:ems="10" />
15.
16. <EditText
17. android:id="@+id/editText2"
18. android:layout_width="wrap_content"
19. android:layout_height="wrap_content"
20. android:layout_alignLeft="@+id/editText1"
21. android:layout_below="@+id/editText1"
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.class)
;
38. PendingIntent pi=PendingIntent.getActivity(getApplicationContext(), 0, inte
nt,0);
39.
40. //Get the SmsManager instance and call the sendTextMessage method to s
end message
41. SmsManager sms=SmsManager.getDefault();
42. sms.sendTextMessage(no, null, msg, pi,null);
43.
44. Toast.makeText(getApplicationContext(), "Message Sent successfully!",
45. Toast.LENGTH_LONG).show();
46. }
47. });
48. }
49.
50. @Override
51. public boolean onCreateOptionsMenu(Menu menu) {
52. // Inflate the menu; this adds items to the action bar if it is present.
53. getMenuInflater().inflate(R.menu.activity_main, menu);
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:
Android Bluetooth Tutorial
Bluetooth is a way to exchange data with other devices wirelessly. Android provides
Bluetooth API to perform several tasks such as:

o scan bluetooth devices


o connect and transfer data from and to other devices
o manage multiple connections etc.

Android Bluetooth API


The android.bluetooth package provides a lot of interfaces classes to work with
bluetooth such as:

o BluetoothAdapter
o BluetoothDevice
o BluetoothSocket
o BluetoothServerSocket
o BluetoothClass
o BluetoothProfile
o BluetoothProfile.ServiceListener
o BluetoothHeadset
o BluetoothA2dp
o BluetoothHealth
o BluetoothHealthCallback
o BluetoothHealthAppConfiguration

android-preferences-example

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:

o String ACTION_REQUEST_ENABLE
o String ACTION_REQUEST_DISCOVERABLE
o String ACTION_DISCOVERY_STARTED
o String ACTION_DISCOVERY_FINISHED

Methods of BluetoothAdapter class

Commonly used methods of BluetoothAdapter class are as follows:

o static synchronized BluetoothAdapter getDefaultAdapter() returns the instance of


BluetoothAdapter.
o boolean enable() enables the bluetooth adapter if it is disabled.
o boolean isEnabled() returns true if the bluetooth adapter is enabled.
o boolean disable() disables the bluetooth adapter if it is enabled.
o String getName() returns the name of the bluetooth adapter.
o boolean setName(String name) changes the bluetooth name.
o int getState() returns the current state of the local bluetooth adapter.
o Set<BluetoothDevice> getBondedDevices() returns a set of paired (bonded)
BluetoothDevice objects.
o boolean startDiscovery() starts the discovery process.

Android Bluetooth Example: enable, disable and make


discovrable bluetooth programmatically
You need to write few lines of code only, to enable or disable the bluetooth.

activity_main.xml

Drag one textview and three buttons from the pallete, now the activity_main.xml file
will like this:
File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/
android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <TextView android:text=""
8. android:id="@+id/out"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content">
11. </TextView>
12. <Button
13. android:id="@+id/button1"
14. android:layout_width="wrap_content"
15. android:layout_height="wrap_content"
16. android:layout_alignParentLeft="true"
17. android:layout_alignParentTop="true"
18. android:layout_marginLeft="30dp"
19. android:layout_marginTop="49dp"
20. android:text="TURN_ON" />
21.
22. <Button
23. android:id="@+id/button2"
24. android:layout_width="wrap_content"
25. android:layout_height="wrap_content"
26. android:layout_alignLeft="@+id/button1"
27. android:layout_below="@+id/button1"
28. android:layout_marginTop="27dp"
29. android:text="DISCOVERABLE" />
30.
31. <Button
32. android:id="@+id/button3"
33. android:layout_width="wrap_content"
34. android:layout_height="wrap_content"
35. android:layout_alignLeft="@+id/button2"
36. android:layout_below="@+id/button2"
37. android:layout_marginTop="28dp"
38. android:text="TURN_OFF" />
39.
40. </RelativeLayout>

Provide Permission

You need to provide following permissions in AndroidManifest.xml file.

1. <uses-permission android:name="android.permission.BLUETOOTH" />


2. <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

The full code of AndroidManifest.xml file is given below.

File: AndroidManifest.xml

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


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

Activity class

Let's write the code to enable, disable and make bluetooth discoverable.

File: MainActivity.java

1. package com.example.bluetooth;
2. import android.os.Bundle;
3. import android.app.Activity;
4. import android.view.Menu;
5. import android.app.Activity;
6. import android.bluetooth.BluetoothAdapter;
7. import android.content.Context;
8. import android.content.Intent;
9. import android.os.Bundle;
10. import android.util.Log;
11. import android.view.View;
12. import android.widget.Button;
13. import android.widget.TextView;
14. import android.widget.Toast;
15.
16. public class MainActivity extends Activity {
17. private static final int REQUEST_ENABLE_BT = 0;
18. private static final int REQUEST_DISCOVERABLE_BT = 0;
19. @Override
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_REQUEST_EN
ABLE);
35. startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
36. }
37. }
38. });
39. button2.setOnClickListener(new View.OnClickListener() {
40. @Override
41. public void onClick(View arg0) {
42. if (!mBluetoothAdapter.isDiscovering()) {
43. //out.append("MAKING YOUR DEVICE DISCOVERABLE");
44. Toast.makeText(getApplicationContext(), "MAKING YOUR DEVICE DISCOV
ERABLE",
45. Toast.LENGTH_LONG);
46.
47. Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQ
UEST_DISCOVERABLE);
48. startActivityForResult(enableBtIntent, REQUEST_DISCOVERABLE_BT);
49.
50. }
51. }
52. });
53. button3.setOnClickListener(new View.OnClickListener() {
54. @Override
55. public void onClick(View arg0) {
56. mBluetoothAdapter.disable();
57. //out.append("TURN_OFF BLUETOOTH");
58. Toast.makeText(getApplicationContext(), "TURNING_OFF BLUETOOTH", Toast.L
ENGTH_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
containing list of all paired or bounded bluetooth devices.

In this example, we are checking if the bluetooth is turned off, if yes then turn it on
and list all the paired devices.

activity_main.xml

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

File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/
android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <TextView
8. android:id="@+id/textView1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentLeft="true"
12. android:layout_alignParentTop="true"
13. android:layout_marginLeft="18dp"
14. android:layout_marginTop="61dp"
15. android:text="Showing Paired Devices:" />
16.
17. </RelativeLayout>

Provide Permission

You need to provide following permissions in AndroidManifest.xml file.

1. <uses-permission android:name="android.permission.BLUETOOTH" />


2. <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

The full code of AndroidManifest.xml file is given below.

File: AndroidManifest.xml

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


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

Activity class

Let's write the code to provide the list of paired (bounded) bluetooth devices.

File: MainActivity.java

1. package com.example.bluetoothshowpaired;
2.
3. import android.os.Bundle;
4. import android.app.Activity;
5. import android.view.Menu;
6. import java.util.Set;
7. import android.bluetooth.BluetoothAdapter;
8. import android.bluetooth.BluetoothDevice;
9. import android.content.Intent;
10. import android.widget.TextView;
11.
12. public class MainActivity extends Activity {
13. TextView textview1;
14. private static final int REQUEST_ENABLE_BT = 1;
15. BluetoothAdapter btAdapter;
16.
17. /** Called when the activity is first created. */
18. @Override
19. public void onCreate(Bundle savedInstanceState) {
20. super.onCreate(savedInstanceState);
21. setContentView(R.layout.activity_main);
22.
23. textview1 = (TextView) findViewById(R.id.textView1);
24.
25. // Getting the Bluetooth adapter
26. btAdapter = BluetoothAdapter.getDefaultAdapter();
27. textview1.append("\nAdapter: " + btAdapter);
28.
29. CheckBluetoothState();
30. }
31.
32. /* It is called when an activity completes.*/
33. @Override
34. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
35. super.onActivityResult(requestCode, resultCode, data);
36. if (requestCode == REQUEST_ENABLE_BT) {
37. CheckBluetoothState();
38. }
39. }
40.
41. @Override
42. protected void onDestroy() {
43. super.onDestroy();
44. }
45.
46. private void CheckBluetoothState() {
47. // Checks for the Bluetooth support and then makes sure it is turned on
48. // If it isn't turned on, request to turn it on
49. // List paired devices
50. if(btAdapter==null) {
51. textview1.append("\nBluetooth NOT supported. Aborting.");
52. return;
53. } else {
54. if (btAdapter.isEnabled()) {
55. textview1.append("\nBluetooth is enabled...");
56.
57. // Listing paired devices
58. textview1.append("\nPaired Devices are:");
59. Set<BluetoothDevice> devices = btAdapter.getBondedDevices();
60. for (BluetoothDevice device : devices) {
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_REQUE
ST_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/
android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <Button
8. android:id="@+id/button1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentLeft="true"
12. android:layout_alignParentTop="true"
13. android:layout_marginLeft="76dp"
14. android:layout_marginTop="67dp"
15. android:text="Enable Wifi" />
16.
17. <Button
18. android:id="@+id/button2"
19. android:layout_width="wrap_content"
20. android:layout_height="wrap_content"
21. android:layout_alignLeft="@+id/button1"
22. android:layout_below="@+id/button1"
23. android:layout_marginTop="44dp"
24. android:text="Disable Wifi" />
25.
26. </RelativeLayout>

Activity class
File: MainActivity.java

1. package com.example.wifi;
2.
3. import android.net.wifi.WifiManager;
4. import android.os.Bundle;
5. import android.app.Activity;
6. import android.content.Context;
7. import android.view.Menu;
8. import android.view.View;
9. import android.view.View.OnClickListener;
10. import android.widget.Button;
11.
12. public class MainActivity extends Activity {
13. Button enableButton,disableButton;
14. @Override
15. protected void onCreate(Bundle savedInstanceState) {
16. super.onCreate(savedInstanceState);
17. setContentView(R.layout.activity_main);
18.
19. enableButton=(Button)findViewById(R.id.button1);
20. disableButton=(Button)findViewById(R.id.button2);
21.
22. enableButton.setOnClickListener(new OnClickListener(){
23. public void onClick(View v){
24. WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE)
;
25. wifi.setWifiEnabled(true);
26. }
27. });
28. disableButton.setOnClickListener(new OnClickListener(){
29. public void onClick(View v){
30. WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE)
;
31. wifi.setWifiEnabled(false);
32. }
33. });
34. }
35.
36. @Override
37. public boolean onCreateOptionsMenu(Menu menu) {
38. // Inflate the menu; this adds items to the action bar if it is present.
39. getMenuInflater().inflate(R.menu.activity_main, menu);
40. return true;
41. }
42.
43. }
Add Permission in AndroidManifest.xml

You need to add following permissions in AndroidManifest.xml file.

1. <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /
>
2. <uses-permission android:name="android.permission.INTERNET" />
3. <uses-permission android:nam
e="android.permission.CHANGE_WIFI_STATE"/>

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/
android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <Button
8. android:id="@+id/button1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentBottom="true"
12. android:layout_centerHorizontal="true"
13. android:text="Take a Photo" >
14. </Button>
15.
16. <ImageView
17. android:id="@+id/imageView1"
18. android:layout_width="fill_parent"
19. android:layout_height="fill_parent"
20. android:layout_above="@+id/button1"
21. android:layout_alignParentTop="true"
22. android:src="@drawable/ic_launcher" >
23. </ImageView>
24. </RelativeLayout>

Activity class

Let's write the code to capture image using camera and displaying it on the image
view.

File: MainActivity.java
1. package com.example.simplecamera;
2.
3. import android.app.Activity;
4. import android.content.Intent;
5. import android.graphics.Bitmap;
6. import android.os.Bundle;
7. import android.view.Menu;
8. import android.view.View;
9. import android.widget.Button;
10. import android.widget.ImageView;
11.
12. public class MainActivity extends Activity {
13. private static final int CAMERA_REQUEST = 1888;
14. ImageView imageView;
15. public void onCreate(Bundle savedInstanceState) {
16.
17. super.onCreate(savedInstanceState);
18. setContentView(R.layout.activity_main);
19.
20. imageView = (ImageView) this.findViewById(R.id.imageView1);
21. Button photoButton = (Button) this.findViewById(R.id.button1);
22.
23. photoButton.setOnClickListener(new View.OnClickListener() {
24.
25. @Override
26. public void onClick(View v) {
27. Intent cameraIntent = new Intent(android.provider.MediaStore.ACTIO
N_IMAGE_CAPTURE);
28. startActivityForResult(cameraIntent, CAMERA_REQUEST);
29. }
30. });
31. }
32.
33. protected void onActivityResult(int requestCode, int resultCode, Intent da
ta) {
34. if (requestCode == CAMERA_REQUEST) {
35. Bitmap photo = (Bitmap) data.getExtras().get("data");
36. imageView.setImageBitmap(photo);
37. }
38. }
39.
40. @Override
41. public boolean onCreateOptionsMenu(Menu menu) {
42. // Inflate the menu; this adds items to the action bar if it is present.
43. getMenuInflater().inflate(R.menu.activity_main, menu);
44. return true;
45. }
46.
47. }

download this android example

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 :

o to get sensor instance,


o to access and list sensors,
o to register and unregister sensor listeners etc.

You can get the instance of SensorManager by calling the method


getSystemService() and passing the SENSOR_SERVICE constant in it.

1. SensorManager sm = (SensorManager)getSystemService(SENSOR_SERVICE);
2) Sensor class

The android.hardware.Sensor class provides methods to get information of the


sensor such as sensor name, sensor type, sensor resolution, sensor type etc.

3) SensorEvent class

Its instance is created by the system. It provides information about the sensor.

4) SensorEventListener interface

It provides two call back methods to get information when sensor values (x,y and z)
change or sensor accuracy changes.

Public and abstract methods Description

void onAccuracyChanged(Sensor sensor, int it is called when sensor accuracy is


accuracy) changed.

void onSensorChanged(SensorEvent event) it is called when sensor values are


changed.

Android simple sensor app example


Let's see the two sensor examples.
1. A sensor example that prints x, y and z axis values. Here, we are going to see that.
2. A sensor example that changes the background color when device is shuffled. Click
for changing background color of activity sensor example

activity_main.xml

There is only one textview in this file.

File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/
android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <TextView
8. android:id="@+id/textView1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentLeft="true"
12. android:layout_alignParentTop="true"
13. android:layout_marginLeft="92dp"
14. android:layout_marginTop="114dp"
15. android:text="TextView" />
16.
17. </RelativeLayout>

Activity class

Let's write the code that prints values of x axis, y axis and z axis.

File: MainActivity.java

1. package com.example.sensorsimple;
2. import android.app.Activity;
3. import android.os.Bundle;
4. import android.widget.TextView;
5. import android.widget.Toast;
6. import android.hardware.SensorManager;
7. import android.hardware.SensorEventListener;
8. import android.hardware.SensorEvent;
9. import android.hardware.Sensor;
10. import java.util.List;
11. public class MainActivity extends Activity {
12. SensorManager sm = null;
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_N
ORMAL);
37. }else{
38. Toast.makeText(getBaseContext(), "Error: No Accelerometer.", Toast.LENGTH_L
ONG).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:

Android Simple Graphics Example


The android.graphics.Canvas can be used to draw graphics in android. It provides
methods to draw oval, rectangle, picture, text, line etc.

The android.graphics.Paint class is used with canvas to draw objects. It holds the
information of color and style.
In this example, we are going to display 2D graphics in android.

activity_main.xml
File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/
android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".MainActivity" >
10.
11. <TextView
12. android:layout_width="wrap_content"
13. android:layout_height="wrap_content"
14. android:text="@string/hello_world" />
15.
16. </RelativeLayout>
Activity class
File: MainActivity.java

1. package com.example.simplegraphics;
2.
3. import android.os.Bundle;
4. import android.app.Activity;
5. import android.view.Menu;
6. import android.content.Context;
7. import android.graphics.Canvas;
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. }
Output:
Android Animation Example
Android provides a large number of classes and interface for the animation
development. Most of the classes and interfaces are given
in android.animation package.

Android Animation enables you to change the object property and behavior at run
time. There are various ways to do animation in android.

The AnimationDrawable class provides methods to start and end the animation.
Even, you can use time based animation.

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

activity_main.xml

You need to have a view only.

File: activity_main.xml

1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/
android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".MainActivity" >
10.
11. <View
12. />
13.
14. </RelativeLayout>
File: logo.xml

Have a image view only.

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


2. <ImageView xmlns:android="http://schemas.android.com/apk/res/android"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:id="@+id/anm"
6. >
7.
8. </ImageView>

MainActivity class
File: MainActivity.java

1. package com.javatpoint.animation;
2.
3. import android.os.Bundle;
4. import android.app.Activity;
5. import android.graphics.drawable.AnimationDrawable;
6. import android.widget.ImageView;
7.
8. public class MainActivity extends Activity {
9.
10. ImageView anm;
11. public void onCreate(Bundle savedInstanceState) {
12. super.onCreate(savedInstanceState);
13. setContentView(R.layout.logo);
14. anm = (ImageView)findViewById(R.id.anm);
15.
16. anm.setBackgroundResource(R.drawable.animation);
17. // the frame-by-frame animation defined as a xml file within the drawabl
e folder
18.
19. /*
20. * NOTE: It's not possible to start the animation during the onCreate.
21. */
22. }
23. public void onWindowFocusChanged (boolean hasFocus) {
24. super.onWindowFocusChanged(hasFocus);
25. AnimationDrawable frameAnimation =
26. (AnimationDrawable) anm.getBackground();
27. if(hasFocus) {
28. frameAnimation.start();
29. } else {
30. frameAnimation.stop();
31. }
32. }
33.
34. }

You need to create animation.xml file inside res/drawable-hdpi directory.

You need to have many images. Here, we are using 14 images and all the 14 images
are located inside res/drawable-mdpi directory.

File: animation.xml

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


2. <animation-list xmlns:android="http://schemas.android.com/apk/res/android"
3. android:oneshot="false">
4.
5. <item android:drawable="@drawable/frame0" android:duration="120" />
6. <item android:drawable="@drawable/frame1" android:duration="120" />
7. <item android:drawable="@drawable/frame2" android:duration="120" />
8. <item android:drawable="@drawable/frame3" android:duration="120" />
9. <item android:drawable="@drawable/frame4" android:duration="120" />
10. <item android:drawable="@drawable/frame5" android:duration="120" />
11. <item android:drawable="@drawable/frame6" android:duration="120" />
12. <item android:drawable="@drawable/frame7" android:duration="120" />
13. <item android:drawable="@drawable/frame8" android:duration="120" />
14. <item android:drawable="@drawable/frame9" android:duration="120" />
15. <item android:drawable="@drawable/frame10" android:duration="120" />

16. <item android:drawable="@drawable/frame11" android:duration="120" />


17. <item android:drawable="@drawable/frame12" android:duration="120" />

18. <item android:drawable="@drawable/frame13" android:duration="120" />


19. <item android:drawable="@drawable/frame14" android:duration="120" />
20. <item android:drawable="@drawable/frame14" android:duration="120" />
21. <item android:drawable="@drawable/frame13" android:duration="120" />

22. <item android:drawable="@drawable/frame12" android:duration="120" />


23. <item android:drawable="@drawable/frame11" android:duration="120" />

24. <item android:drawable="@drawable/frame10" android:duration="120" />


25. <item android:drawable="@drawable/frame9" android:duration="120" />
26. <item android:drawable="@drawable/frame8" android:duration="120" />
27. <item android:drawable="@drawable/frame7" android:duration="120" />
28. <item android:drawable="@drawable/frame6" android:duration="120" />
29. <item android:drawable="@drawable/frame5" android:duration="120" />
30. <item android:drawable="@drawable/frame4" android:duration="120" />
31. <item android:drawable="@drawable/frame3" android:duration="120" />
32. <item android:drawable="@drawable/frame2" android:duration="120" />
33. <item android:drawable="@drawable/frame1" android:duration="120" />
34. <item android:drawable="@drawable/frame0" android:duration="120" />
35.
36. </animation-list>

download this android example


Output:
Android Web Service Tutorial
Creating web service application in android is not a difficult task. We can easily create
a restful web service application in android to authenticate or save information into
the external database such as oracle, mysql, postgre sql, sql server using other
application developed in java, .net, php etc languages. That is what we are going to
do.

Android Restful Web Service Tutorial


Before developing web services application, you must have basic knowledge of SOAP
and Restful web services. That is why, we are going to discuss basic points about web
services such as what is web service and brief information about SOAP and Restful
web services.

What is Web Service?


A web service is a standard for exchanging information between different types of
applications irrespective of language and platform. For example, an android
application can interact with java or .net application using web services.

Android Restful Web Service Example


File: activity_main.xml

1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/
android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".MainActivity" >
10.
11. <EditText
12. android:id="@+id/editText1"
13. android:layout_width="wrap_content"
14. android:layout_height="wrap_content"
15. android:layout_alignParentTop="true"
16. android:layout_centerHorizontal="true"
17. android:hint="Username"
18. android:ems="10" >
19.
20. <requestFocus />
21. </EditText>
22.
23. <EditText
24. android:id="@+id/editText2"
25. android:layout_width="wrap_content"
26. android:layout_height="wrap_content"
27. android:layout_alignLeft="@+id/editText1"
28. android:layout_below="@+id/editText1"
29. android:layout_marginTop="67dp"
30. android:ems="10"
31. android:hint="Password"
32. android:inputType="textPassword" />
33.
34. <Button
35. android:id="@+id/button2"
36. android:layout_width="wrap_content"
37. android:layout_height="wrap_content"
38. android:layout_alignParentBottom="true"
39. android:layout_marginBottom="24dp"
40. android:layout_toRightOf="@+id/button1"
41. android:text="New User" />
42.
43. <ProgressBar
44. android:id="@+id/progressBar1"
45. style="?android:attr/progressBarStyleLarge"
46. android:layout_width="wrap_content"
47. android:layout_height="wrap_content"
48. android:layout_alignLeft="@+id/button1"
49. android:layout_below="@+id/editText2"
50. android:layout_marginTop="22dp" />
51.
52. <Button
53. android:id="@+id/button1"
54. android:layout_width="wrap_content"
55. android:layout_height="wrap_content"
56. android:layout_alignLeft="@+id/editText2"
57. android:layout_below="@+id/progressBar1"
58. android:layout_marginLeft="22dp"
59. android:text="Login" />
60.
61. </RelativeLayout>

File: activity_register_user.xml

1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/
android"
2. android:layout_width="fill_parent"
3. android:layout_height="fill_parent" >
4.
5. <EditText
6. android:id="@+id/editText1"
7. android:layout_width="wrap_content"
8. android:layout_height="wrap_content"
9. android:layout_alignParentTop="true"
10. android:layout_centerHorizontal="true"
11. android:layout_marginTop="15dp"
12. android:ems="10"
13. android:hint="Enter UserName" />
14.
15. <EditText
16. android:id="@+id/editText2"
17. android:layout_width="wrap_content"
18. android:layout_height="wrap_content"
19. android:layout_alignLeft="@+id/editText1"
20. android:layout_below="@+id/editText1"
21. android:layout_marginTop="50dp"
22. android:ems="10"
23. android:hint="Enter Password"
24. android:inputType="textPassword" />
25.
26. <Button
27. android:id="@+id/button1"
28. android:layout_width="wrap_content"
29. android:layout_height="wrap_content"
30. android:layout_alignParentBottom="true"
31. android:layout_centerHorizontal="true"
32. android:text="Resister" />
33.
34. <ProgressBar
35. android:id="@+id/progressBar1"
36. style="?android:attr/progressBarStyleLarge"
37. android:layout_width="wrap_content"
38. android:layout_height="wrap_content"
39. android:layout_alignLeft="@+id/button1"
40. android:layout_below="@+id/editText2"
41. android:layout_marginTop="87dp" />
42.
43. </RelativeLayout>

MainActivity class
File: MainActivity.java

1. package com.example.newrestapi;
2.
3. import java.io.BufferedReader;
4. import java.io.InputStream;
5. import java.io.InputStreamReader;
6. import java.util.ArrayList;
7. import java.util.List;
8. import org.apache.http.HttpEntity;
9. import org.apache.http.HttpResponse;
10. import org.apache.http.NameValuePair;
11. import org.apache.http.client.HttpClient;
12. import org.apache.http.client.entity.UrlEncodedFormEntity;
13. import org.apache.http.client.methods.HttpPost;
14. import org.apache.http.impl.client.DefaultHttpClient;
15. import org.apache.http.message.BasicNameValuePair;
16. import android.os.AsyncTask;
17. import android.os.Bundle;
18. import android.app.Activity;
19. import android.content.Intent;
20. import android.view.View;
21. import android.view.View.OnClickListener;
22. import android.widget.Button;
23. import android.widget.EditText;
24. import android.widget.ProgressBar;
25. import android.widget.Toast;
26.
27. public class MainActivity extends Activity {
28. EditText password,userName;
29. Button login,resister;
30. ProgressBar progressBar;
31.
32.
33.
34. protected void onCreate(Bundle savedInstanceState) {
35. super.onCreate(savedInstanceState);
36. setContentView(R.layout.activity_main);
37. password=(EditText) findViewById(R.id.editText2);
38. userName=(EditText) findViewById(R.id.editText1);
39. login=(Button) findViewById(R.id.button1);
40. resister=(Button) findViewById(R.id.button2);
41.
42. //progess_msz.setVisibility(View.GONE);
43. progressBar=(ProgressBar) findViewById(R.id.progressBar1);
44. progressBar.setVisibility(View.GONE);
45.
46.
47. resister.setOnClickListener(new OnClickListener() {
48.
49. @Override
50. public void onClick(View arg0) {
51. // TODO Auto-generated method stub
52. Intent intent=new Intent(MainActivity.this,ResisterUser.class);
53. startActivity(intent);
54. }
55. });
56. login.setOnClickListener(new OnClickListener() {
57.
58. public void onClick(View v) {
59. progressBar.setVisibility(View.VISIBLE);
60.
61. String s1=userName.getText().toString();
62. String s2=password.getText().toString();
63. new ExecuteTask().execute(s1,s2);
64.
65. }
66. });
67.
68.
69. }
70.
71. class ExecuteTask extends AsyncTask<String, Integer, String>
72. {
73.
74. @Override
75. protected String doInBackground(String... params) {
76.
77. String res=PostData(params);
78.
79. return res;
80. }
81.
82. @Override
83. protected void onPostExecute(String result) {
84. progressBar.setVisibility(View.GONE);
85. //progess_msz.setVisibility(View.GONE);
86. Toast.makeText(getApplicationContext(), result, 3000).show();
87. }
88.
89. }
90.
91. public String PostData(String[] valuse) {
92. String s="";
93. try
94. {
95. HttpClient httpClient=new DefaultHttpClient();
96. HttpPost httpPost=new HttpPost("http://10.0.0.8:7777/HttpPostServlet/servlet/
Login");
97.
98. List<NameValuePair> list=new ArrayList<NameValuePair>();
99. list.add(new BasicNameValuePair("name", valuse[0]));
100. list.add(new BasicNameValuePair("pass",valuse[1]));
101. httpPost.setEntity(new UrlEncodedFormEntity(list));
102. HttpResponse httpResponse= httpClient.execute(httpPost);
103.
104. HttpEntity httpEntity=httpResponse.getEntity();
105. s= readResponse(httpResponse);
106.
107. }
108. catch(Exception exception) {}
109. return s;
110.
111.
112. }
113. public String readResponse(HttpResponse res) {
114. InputStream is=null;
115. String return_text="";
116. try {
117. is=res.getEntity().getContent();
118. BufferedReader bufferedReader=new BufferedReader(new InputStrea
mReader(is));
119. String line="";
120. StringBuffer sb=new StringBuffer();
121. while ((line=bufferedReader.readLine())!=null)
122. {
123. sb.append(line);
124. }
125. return_text=sb.toString();
126. } catch (Exception e)
127. {
128.
129. }
130. return return_text;
131.
132. }
133.
134. }

RegisterUser class
File: RegisterUser.java

1. package com.example.newrestapi;
2.
3. import java.util.ArrayList;
4. import java.util.List;
5. import org.apache.http.NameValuePair;
6. import org.apache.http.client.HttpClient;
7. import org.apache.http.client.entity.UrlEncodedFormEntity;
8. import org.apache.http.client.methods.HttpPost;
9. import org.apache.http.impl.client.DefaultHttpClient;
10. import org.apache.http.message.BasicNameValuePair;
11. import android.os.AsyncTask;
12. import android.os.Bundle;
13. import android.app.Activity;
14. import android.view.View;
15. import android.view.View.OnClickListener;
16. import android.widget.Button;
17. import android.widget.EditText;
18. import android.widget.ProgressBar;
19.
20. public class ResisterUser extends Activity {
21. EditText userName,passwprd;
22. Button resister,login;
23. ProgressBar progressBar;
24. protected void onCreate(Bundle savedInstanceState) {
25. super.onCreate(savedInstanceState);
26. setContentView(R.layout.activity_resister_user);
27. userName=(EditText) findViewById(R.id.editText1);;
28. passwprd=(EditText) findViewById(R.id.editText2);
29. resister=(Button) findViewById(R.id.button1);
30.
31. progressBar=(ProgressBar) findViewById(R.id.progressBar1);
32. progressBar.setVisibility(View.GONE);
33.
34. resister.setOnClickListener(new OnClickListener() {
35.
36. @Override
37. public void onClick(View v) {
38.
39. progressBar.setVisibility(View.VISIBLE);
40.
41. String s1=userName.getText().toString();
42. String s2=passwprd.getText().toString();
43. new ExecuteTask().execute(s1,s2);
44. }
45. });
46.
47.
48.
49.
50. }
51.
52. class ExecuteTask extends AsyncTask<String, Integer, String>
53. {
54.
55. @Override
56. protected String doInBackground(String... params) {
57.
58. PostData(params);
59. return null;
60. }
61.
62. @Override
63. protected void onPostExecute(String result) {
64. progressBar.setVisibility(View.GONE);
65. }
66.
67. }
68.
69.
70.
71. public void PostData(String[] valuse) {
72. try
73. {
74. HttpClient httpClient=new DefaultHttpClient();
75. HttpPost httpPost=new HttpPost(
76. "http://10.0.0.8:7777/HttpPostServlet/servlet/httpPostServlet");
77. List<NameValuePair> list=new ArrayList<NameValuePair>();
78. list.add(new BasicNameValuePair("name", valuse[0]));
79. list.add(new BasicNameValuePair("pass",valuse[1]));
80. httpPost.setEntity(new UrlEncodedFormEntity(list));
81. httpClient.execute(httpPost);
82. }
83. catch(Exception e)
84. {
85. System.out.println(e);
86. }
87.
88. }
89.
90. }

File: AndroidManifest.xml
You need to provide INTERNET permission in AndroidManifest.xml file.

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


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

download this android example


Output:
Java Servlet Login and Register example
using oracle database
Create table javatpoint_user in the oracle database having three columns id, name
and password. Id must be primary key and generated through SEQUENCE.

1. CREATE TABLE "JAVATPOINT_USER"


2. ( "ID" NUMBER,
3. "NAME" VARCHAR2(4000),
4. "PASSWORD" VARCHAR2(4000),
5. CONSTRAINT "JAVATPOINT_USER_PK" PRIMARY KEY ("ID") ENABLE
6. )
7. /

New create two servlet classes to login and register user.

Login Servlet class


File: Login.java

1. package server;
2.
3. import java.io.IOException;
4. import java.io.ObjectOutputStream;
5. import java.sql.Connection;
6. import java.sql.DriverManager;
7. import java.sql.PreparedStatement;
8. import java.sql.ResultSet;
9. import javax.servlet.ServletException;
10. import javax.servlet.http.HttpServlet;
11. import javax.servlet.http.HttpServletRequest;
12. import javax.servlet.http.HttpServletResponse;
13.
14. public class Login extends HttpServlet {
15.
16.
17. public void doGet(HttpServletRequest request, HttpServletResponse respo
nse)
18. throws ServletException, IOException {
19. response.setContentType("text/html");
20.
21. ObjectOutputStream out=new ObjectOutputStream(response.getOutp
utStream());
22.
23. String n=request.getParameter("name");
24. String p=request.getParameter("pass");
25. System.out.println(n);
26. System.out.println(p);
27.
28. if(validate(n, p)){
29. out.writeObject("success");
30.
31. }
32. else{
33. out.writeObject("Sorry username or password error");
34.
35. }
36.
37. out.close();
38. }
39.
40.
41. public static boolean validate(String name,String pass){
42. boolean status=false;
43. try{
44. Class.forName("oracle.jdbc.driver.OracleDriver");
45. Connection con=DriverManager.getConnection(
46. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
47.
48. PreparedStatement ps=con.prepareStatement(
49. "select * from javatpoint_user where name=? and password=?");
50. ps.setString(1,name);
51. ps.setString(2,pass);
52.
53. ResultSet rs=ps.executeQuery();
54. status=rs.next();
55.
56. }catch(Exception e){System.out.println(e);}
57. return status;
58. }
59. public void doPost(HttpServletRequest request,HttpServletResponse respo
nse)
60. throws ServletException, IOException {
61. doGet(request, response);
62.
63. }
64. }
httpPostServlet Servlet class
File: httpPostServlet.java

1. package server;
2.
3. import java.io.IOException;
4. import java.sql.Connection;
5. import java.sql.DriverManager;
6. import java.sql.PreparedStatement;
7. import javax.servlet.ServletException;
8. import javax.servlet.http.HttpServlet;
9. import javax.servlet.http.HttpServletRequest;
10. import javax.servlet.http.HttpServletResponse;
11.
12.
13. public class httpPostServlet extends HttpServlet {
14.
15.
16. public void doGet(HttpServletRequest request,HttpServletResponse response)
17. throws ServletException, IOException {
18. response.setContentType("text/html");
19. String recived_data="";
20.
21.
22. String s1=request.getParameter("name");
23. String s2=request.getParameter("pass");
24. System.out.println(s1);
25. System.out.println(s2);
26.
27. try
28. {
29. Class.forName("oracle.jdbc.driver.OracleDriver");
30. Connection con=DriverManager.getConnection(
31. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
32. PreparedStatement ps=con.prepareStatement(
33. "insert into javatpoint_user(name,password) values(?,?)");
34. ps.setString(1, s1);
35. ps.setString(2,s2);
36. ps.executeUpdate();
37. con.close();
38. }
39. catch (Exception e) {
40. e.printStackTrace();
41. }
42.
43. }
44. public void doPost(HttpServletRequest request,HttpServletResponse response)
45. throws ServletException, IOException {
46. doGet(request, response);
47. }
48.
49. }
index.jsp
1. <form action="servlet/Login">
2. Name:<input type="text" name="name"/><br/>
3. Password:<input type="password" name="pass"/><br/>
4. <input type="submit" value="login"/>
5. </form>

Android Google Map


Android provides facility to integrate Google map in our application. Google map
displays your current location, navigate location direction, search location etc. We
can also customize Google map according to our requirement.
Types of Google Maps
There are four different types of Google maps, as well as an optional to no map at all.
Each of them gives different view on map. These maps are as follow:

1. Normal: This type of map displays typical road map, natural features like river and
some features build by humans.
2. Hybrid: This type of map displays satellite photograph data with typical road maps. It
also displays road and feature labels.
3. Satellite: Satellite type displays satellite photograph data, but doesn't display road
and feature labels.
4. Terrain: This type displays photographic data. This includes colors, contour lines and
labels and perspective shading.
5. None: This type displays an empty grid with no tiles loaded.

Syntax of different types of map

1. googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
2. googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
3. googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
4. googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
Methods of Google map
Google map API provides several methods that help to customize Google map.
These methods are as following:

Methods Description

addCircle(CircleOptions options) This method add circle to map.

addPolygon(PolygonOptions options) This method add polygon to map.

addTileOverlay(TileOverlayOptions options) This method add tile overlay to the


map.

animateCamera(CameraUpdate update) This method moves the map


according to the update with an
animation.

clear() This method removes everything from


the map.

getMyLocation() This method returns the currently


displayed user location.

moveCamera(CameraUpdate update) This method reposition the camera


according to the instructions defined
in the update.

setTrafficEnabled(boolean enabled) This method set the traffic layer on or


off.

snapshot(GoogleMap.SnapshotReadyCallback This method takes a snapshot of the


callback) map.

stopAnimation() This method stops the camera


animation if there is any progress.

Example of Google Map


Let's create an example of Google map integrating within our app. For doing this we
select Google Maps Activity.
Copy the URL from google_map_api.xml file to generate Google map key.

Paste the copied URL at the browser. It will open the following page.
Click on Create API key to generate API key.

After clicking on Create API key, it will generate our API key displaying the following
screen.
Copy this generated API key in our google_map_api.xml file

activity_maps.xml
1. <fragment xmlns:android="http://schemas.android.com/apk/res/android"
2. xmlns:map="http://schemas.android.com/apk/res-auto"
3. xmlns:tools="http://schemas.android.com/tools"
4. android:id="@+id/map"
5. android:name="com.google.android.gms.maps.SupportMapFragment"
6. android:layout_width="match_parent"
7. android:layout_height="match_parent"
8. tools:context="example.com.mapexample.MapsActivity" />
MapsActivity.java
To get the GoogleMap object in our MapsActivity.java class we need to implement
the OnMapReadyCallback interface and override the onMapReady() callback method.
1. package example.com.mapexample;
2.
3. import android.support.v4.app.FragmentActivity;
4. import android.os.Bundle;
5. import com.google.android.gms.maps.CameraUpdateFactory;
6. import com.google.android.gms.maps.GoogleMap;
7. import com.google.android.gms.maps.OnMapReadyCallback;
8. import com.google.android.gms.maps.SupportMapFragment;
9. import com.google.android.gms.maps.model.LatLng;
10. import com.google.android.gms.maps.model.MarkerOptions;
11.
12. public class MapsActivity extends FragmentActivity implements OnMapReadyCallba
ck{
13.
14. private GoogleMap mMap;
15.
16. @Override
17. protected void onCreate(Bundle savedInstanceState) {
18. super.onCreate(savedInstanceState);
19. setContentView(R.layout.activity_maps);
20. // Obtain the SupportMapFragment and get notified when the map is ready to b
e used.
21. SupportMapFragment mapFragment = (SupportMapFragment) getSupp
ortFragmentManager()
22. .findFragmentById(R.id.map);
23. mapFragment.getMapAsync(this);
24.
25. }
26.
27. @Override
28. public void onMapReady(GoogleMap googleMap) {
29. mMap = googleMap;
30.
31. // Add a marker in Sydney and move the camera
32. LatLng sydney = new LatLng(-34, 151);
33. mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in
Sydney"));
34. mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
35.
36. }
37. }
Required Permission
Add the following user-permission in AndroidManifest.xml file.

1. <uses-permission android:nam
e="android.permission.ACCESS_FINE_LOCATION" />
2. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"
/>
3. <uses-permission android:name="android.permission.INTERNET" />
AndroidManifest.xml
1. <?xml version="1.0" encoding="utf-8"?>
2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3. package="example.com.mapexample">
4. <!--
5. The ACCESS_COARSE/FINE_LOCATION permissions are not required to u
se
6. Google Maps Android API v2, but you must specify either coarse or fine
7. location permissions for the 'MyLocation' functionality.
8. -->
9. <uses-permission android:nam
e="android.permission.ACCESS_FINE_LOCATION" />
10. <uses-permission android:nam
e="android.permission.ACCESS_COARSE_LOCATION" />
11. <uses-permission android:name="android.permission.INTERNET" />
12.
13. <application
14. android:allowBackup="true"
15. android:icon="@mipmap/ic_launcher"
16. android:label="@string/app_name"
17. android:roundIcon="@mipmap/ic_launcher_round"
18. android:supportsRtl="true"
19. android:theme="@style/AppTheme">
20.
21. <meta-data
22. android:name="com.google.android.geo.API_KEY"
23. android:value="@string/google_maps_key" />
24.
25. <activity
26. android:name=".MapsActivity"
27. android:label="@string/title_activity_maps">
28. <intent-filter>
29. <action android:name="android.intent.action.MAIN" />
30.
31. <category android:name="android.intent.category.LAUNCHER" />
32. </intent-filter>
33. </activity>
34. </application>
35.
36. </manifest>
build.gradel
Add the following dependencies in build.gradel file.

1. dependencies {
2. implementation fileTree(dir: 'libs', include: ['*.jar'])
3. implementation 'com.android.support:appcompat-v7:26.1.0'
4. implementation 'com.google.android.gms:play-services-maps:11.8.0'
5. testImplementation 'junit:junit:4.12'
6. androidTestImplementation 'com.android.support.test:runner:1.0.1'
7. androidTestImplementation 'com.android.support.test.espresso:espresso-
core:3.0.1'
8. }

Output
Android Google Map Displaying
Current Location
In the previous tutorial of Android Google Map, we simply displayed the default
coordinates (location) set by the MapsActivity.java class file.

Now in this tutorial we will display and place marker at the user current location. For
doing this we need to generate Google Map API key. The process of generating
Google Map API is described in tutorial Android Google Map.

To display the user current location we need to implements some interfaces and
there callbacks methods.

Callback methods in Google Map

1. OnMapRreadyCallback: This callback interface invokes when it instance is set on


MapFragment object. The onMapReady(GoogleMap) method of
OnMapReadyCallback interface is called when the map is ready to used. In the
onMapReady(GoogleMap) method we can add markers, listeners and other
attributes.
2. LocationListener: This interface is used to receive notification when the device
location has changed. The abstract method of LocationListener
onLocationChanged(Location) is called when the location has changed.
3. GoogleApiClient.ConnectionCallbacks: This interface provide callbacks methods
onConnected(Bundle) and onConnectionSuspended(int) which are called when the
device is to connected and disconnected.
4. GoogleApiClient.OnConnectionFailedListener: This interface provide callbacks
method onConnectionFailed(ConnectionResult) which is called when there was an
error in connecting the device to the service.

The setMyLocationEnabled() method of GoogleMap is used to enable location


layer, which allows device to interact with current location.

Example of Google Map Displaying Current


Location
Let's see an example of Google Map which displays the current location of device.

activity_maps.xml
Add a SupportMapFragment in fragment in activity_maps.xml file.

1. <fragment xmlns:android="http://schemas.android.com/apk/res/android"
2. xmlns:map="http://schemas.android.com/apk/res-auto"
3. xmlns:tools="http://schemas.android.com/tools"
4. android:id="@+id/map"
5. android:name="com.google.android.gms.maps.SupportMapFragment"
6. android:layout_width="match_parent"
7. android:layout_height="match_parent"
8. tools:context="example.com.mapexample.MapsActivity" />
build.gradel
Add the following dependencies in build.gradel file.

1. dependencies {
2. implementation fileTree(dir: 'libs', include: ['*.jar'])
3. implementation 'com.android.support:appcompat-v7:26.1.0'
4. implementation 'com.google.android.gms:play-services-maps:11.8.0'
5. compile 'com.google.android.gms:play-services-location:11.8.0'
6. testImplementation 'junit:junit:4.12'
7. androidTestImplementation 'com.android.support.test:runner:1.0.1'
8. androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

9.
10. }
MapsActivity.java
Add the following code in MapsActivity.java file.

1. package example.com.mapexample;
2.
3.
4. import android.os.Build;
5. import android.support.v4.app.FragmentActivity;
6. import android.os.Bundle;
7.
8. import com.google.android.gms.common.api.GoogleApiClient;
9. import com.google.android.gms.maps.CameraUpdateFactory;
10. import com.google.android.gms.maps.GoogleMap;
11. import com.google.android.gms.maps.OnMapReadyCallback;
12. import com.google.android.gms.maps.SupportMapFragment;
13. import com.google.android.gms.maps.model.BitmapDescriptorFactory;
14. import com.google.android.gms.maps.model.LatLng;
15. import com.google.android.gms.maps.model.Marker;
16. import com.google.android.gms.maps.model.MarkerOptions;
17. import com.google.android.gms.location.LocationServices;
18.
19. import android.location.Location;
20. import android.Manifest;
21. import android.content.pm.PackageManager;
22. import android.support.v4.content.ContextCompat;
23. import com.google.android.gms.common.ConnectionResult;
24. import com.google.android.gms.location.LocationListener;
25. import com.google.android.gms.location.LocationRequest;
26.
27.
28. public class MapsActivity extends FragmentActivity implements OnMapReadyCallba
ck,
29. LocationListener,GoogleApiClient.ConnectionCallbacks,
30. GoogleApiClient.OnConnectionFailedListener{
31.
32. private GoogleMap mMap;
33. Location mLastLocation;
34. Marker mCurrLocationMarker;
35. GoogleApiClient mGoogleApiClient;
36. LocationRequest mLocationRequest;
37.
38. @Override
39. protected void onCreate(Bundle savedInstanceState) {
40. super.onCreate(savedInstanceState);
41. setContentView(R.layout.activity_maps);
42. // Obtain the SupportMapFragment and get notified when the map is ready to b
e used.
43. SupportMapFragment mapFragment = (SupportMapFragment) getSupp
ortFragmentManager()
44. .findFragmentById(R.id.map);
45. mapFragment.getMapAsync(this);
46.
47. }
48.
49. @Override
50. public void onMapReady(GoogleMap googleMap) {
51. mMap = googleMap;
52.
53. if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
54. if (ContextCompat.checkSelfPermission(this,
55. Manifest.permission.ACCESS_FINE_LOCATION)
56. == PackageManager.PERMISSION_GRANTED) {
57. buildGoogleApiClient();
58. mMap.setMyLocationEnabled(true);
59. }
60. }
61. else {
62. buildGoogleApiClient();
63. mMap.setMyLocationEnabled(true);
64. }
65.
66. }
67. protected synchronized void buildGoogleApiClient() {
68. mGoogleApiClient = new GoogleApiClient.Builder(this)
69. .addConnectionCallbacks(this)
70. .addOnConnectionFailedListener(this)
71. .addApi(LocationServices.API).build();
72. mGoogleApiClient.connect();
73. }
74.
75. @Override
76. public void onConnected(Bundle bundle) {
77.
78. mLocationRequest = new LocationRequest();
79. mLocationRequest.setInterval(1000);
80. mLocationRequest.setFastestInterval(1000);
81. mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_PO
WER_ACCURACY);
82. if (ContextCompat.checkSelfPermission(this,
83. Manifest.permission.ACCESS_FINE_LOCATION)
84. == PackageManager.PERMISSION_GRANTED) {
85. LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleA
piClient, mLocationRequest, this);
86. }
87.
88. }
89.
90. @Override
91. public void onConnectionSuspended(int i) {
92.
93. }
94.
95. @Override
96. public void onLocationChanged(Location location) {
97.
98. mLastLocation = location;
99. if (mCurrLocationMarker != null) {
100. mCurrLocationMarker.remove();
101. }
102. //Place current location marker
103. LatLng latLng = new LatLng(location.getLatitude(), location.getLon
gitude());
104. MarkerOptions markerOptions = new MarkerOptions();
105. markerOptions.position(latLng);
106. markerOptions.title("Current Position");
107. markerOptions.icon(BitmapDescriptorFactory.defaultMarker(Bitma
pDescriptorFactory.HUE_GREEN));
108. mCurrLocationMarker = mMap.addMarker(markerOptions);
109.
110. //move map camera
111. mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
112. mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
113.
114. //stop location updates
115. if (mGoogleApiClient != null) {
116. LocationServices.FusedLocationApi.removeLocationUpdates(mGoogle
ApiClient, this);
117. }
118.
119. }
120.
121. @Override
122. public void onConnectionFailed(ConnectionResult connectionResult) {
123.
124. }
125.
126. }
Request Runtime Permission
Android device having Android 6.0 (Marshmallow) or later are required some
permission at runtime to access device functionality.

In the above MapsActivity.java file we added a runtime


permission Manifest.permission.ACCESS_FINE_LOCATION which request to access
device location. The runtime permission is checked
using checkSelfPermission() method and
return PackageManager.PERMISSION_GRANTED or PackageManager.PERMISSION_DE
NIED. If permission granted than app proceeds for operation.

Required Permission in AndroidManifest.xml


Add the following user-permission in AndroidManifest.xml file.

1. <uses-permission android:nam
e="android.permission.ACCESS_FINE_LOCATION" />
2. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"
/>
3. <uses-permission android:name="android.permission.INTERNET" />
AndroidManifest.xml
1. <?xml version="1.0" encoding="utf-8"?>
2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3. package="example.com.mapexample">
4. <!--
5. The ACCESS_COARSE/FINE_LOCATION permissions are not required to u
se
6. Google Maps Android API v2, but you must specify either coarse or fine
7. location permissions for the 'MyLocation' functionality.
8. -->
9. <uses-permission android:nam
e="android.permission.ACCESS_FINE_LOCATION" />
10. <uses-permission android:nam
e="android.permission.ACCESS_COARSE_LOCATION" />
11. <uses-permission android:name="android.permission.INTERNET" />
12.
13.
14. <application
15. android:allowBackup="true"
16. android:icon="@mipmap/ic_launcher"
17. android:label="@string/app_name"
18. android:roundIcon="@mipmap/ic_launcher_round"
19. android:supportsRtl="true"
20. android:theme="@style/AppTheme">
21. <!--
22. The API key for Google Maps-based APIs is defined as a string resource.
23. (See the file "res/values/google_maps_api.xml").
24. Note that the API key is linked to the encryption key used to sign the APK.
25. You need a different API key for each encryption key, including the rel
ease key that is used to
26. sign the APK for publishing.
27. You can define the keys for the debug and release targets in src/
debug/ and src/release/.
28. -->
29. <meta-data
30. android:name="com.google.android.geo.API_KEY"
31. android:value="@string/google_maps_key" />
32.
33. <activity
34. android:name=".MapsActivity"
35. android:label="@string/title_activity_maps">
36. <intent-filter>
37. <action android:name="android.intent.action.MAIN" />
38.
39. <category android:name="android.intent.category.LAUNCHER" />
40. </intent-filter>
41. </activity>
42. </application>
43.
44. </manifest>

Output
Android Google Map Search Location
using Geocoder
In the previous tutorial of Android Google Map and Android Google Map Displaying
Current Location we described about display basic Google Map and current location
respectively.

Now in this tutorial we will implement location search functionality in Google Map.

Searching location in Google Map API is done through Geocoder class. Geocoder
class is used to handle geocoding and reverse geocoding.

Geocoding is a process in which street address is converted into a coordinate


(latitude,longitude). Reverse geocoding is a process in which a coordinate
(latitude,longitude) is converted into an address.

Methods of Geocoder class


1. List<Address> getFromLocation(double latitude, double longitude, int
maxResults): This method returns an array of Address which specifies the
surrounding latitude and longitude.
2. List<Address> getFromLocationName(String location, int results, double
leftLatitude, double leftLongitude, double rightLatitude, double
rightLongitude): This method returns an array of Address which describes the given
location such as place, an address, etc.
3. List<Address> getFromLocationName(String location, int results): This method
returns an array of Address which describes te given location such as place, an
address, etc.
4. static boolean isPresent(): This method returns true if the methods
getFromLocation() and getFromLocationName() are implemented.

Let's see the code which convert location name into coordinate.

1. List<Address> addressList = geocoder.getFromLocationName(location, 1);


2. Address address = addressList.get(0);
3. LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
Example of Android Google Map API Searching
Location
Let's see an example of Google Map which search input location.

activity_maps.xml
Add a fragment (SupportMapFragment), EditText and Button in activity_maps.xml file.

1. <fragment xmlns:android="http://schemas.android.com/apk/res/android"
2. xmlns:map="http://schemas.android.com/apk/res-auto"
3. xmlns:tools="http://schemas.android.com/tools"
4. android:id="@+id/map"
5. android:name="com.google.android.gms.maps.SupportMapFragment"
6. android:layout_width="match_parent"
7. android:layout_height="match_parent"
8. tools:context="example.com.mapexample.MapsActivity">
9. <LinearLayout
10. android:layout_width="match_parent"
11. android:layout_height="wrap_content"
12. android:orientation="horizontal">
13.
14. <EditText
15. android:layout_width="248dp"
16. android:layout_height="wrap_content"
17. android:id="@+id/editText"
18. android:layout_weight="0.5"
19. android:inputType="textPersonName"
20. android:hint="Search Location" />
21.
22. <Button
23. android:layout_width="wrap_content"
24. android:layout_height="wrap_content"
25. android:layout_weight="0.5"
26. android:onClick="searchLocation"
27. android:text="Search" />
28.
29. </LinearLayout>
30.
31. </fragment>
build.gradel
Add the following dependencies in build.gradel file.

1. dependencies {
2. implementation fileTree(dir: 'libs', include: ['*.jar'])
3. implementation 'com.android.support:appcompat-v7:26.1.0'
4. implementation 'com.google.android.gms:play-services-maps:11.8.0'
5. compile 'com.google.android.gms:play-services-location:11.8.0'
6. testImplementation 'junit:junit:4.12'
7. androidTestImplementation 'com.android.support.test:runner:1.0.1'
8. androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

9.
10. }
MapsActivity.java
Add the following code in MapsActivity.java file.

1. package example.com.mapexample;
2.
3. import android.location.Address;
4. import android.location.Geocoder;
5. import android.os.Build;
6. import android.support.v4.app.FragmentActivity;
7. import android.os.Bundle;
8.
9. import com.google.android.gms.common.api.GoogleApiClient;
10. import com.google.android.gms.maps.CameraUpdateFactory;
11. import com.google.android.gms.maps.GoogleMap;
12. import com.google.android.gms.maps.OnMapReadyCallback;
13. import com.google.android.gms.maps.SupportMapFragment;
14. import com.google.android.gms.maps.model.BitmapDescriptorFactory;
15. import com.google.android.gms.maps.model.LatLng;
16. import com.google.android.gms.maps.model.Marker;
17. import com.google.android.gms.maps.model.MarkerOptions;
18. import com.google.android.gms.location.LocationServices;
19.
20. import android.location.Location;
21. import android.Manifest;
22. import android.content.pm.PackageManager;
23. import android.support.v4.content.ContextCompat;
24. import android.view.View;
25. import android.widget.EditText;
26. import android.widget.Toast;
27.
28. import com.google.android.gms.common.ConnectionResult;
29. import com.google.android.gms.location.LocationListener;
30. import com.google.android.gms.location.LocationRequest;
31.
32. import java.io.IOException;
33. import java.util.List;
34.
35.
36. public class MapsActivity extends FragmentActivity implements OnMapReadyCallba
ck,
37. LocationListener,GoogleApiClient.ConnectionCallbacks,
38. GoogleApiClient.OnConnectionFailedListener{
39.
40. private GoogleMap mMap;
41. Location mLastLocation;
42. Marker mCurrLocationMarker;
43. GoogleApiClient mGoogleApiClient;
44. LocationRequest mLocationRequest;
45.
46. @Override
47. protected void onCreate(Bundle savedInstanceState) {
48. super.onCreate(savedInstanceState);
49. setContentView(R.layout.activity_maps);
50. // Obtain the SupportMapFragment and get notified when the map is ready to b
e used.
51. SupportMapFragment mapFragment = (SupportMapFragment) getSupp
ortFragmentManager()
52. .findFragmentById(R.id.map);
53. mapFragment.getMapAsync(this);
54.
55. }
56.
57. @Override
58. public void onMapReady(GoogleMap googleMap) {
59. mMap = googleMap;
60.
61. if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
62. if (ContextCompat.checkSelfPermission(this,
63. Manifest.permission.ACCESS_FINE_LOCATION)
64. == PackageManager.PERMISSION_GRANTED) {
65. buildGoogleApiClient();
66. mMap.setMyLocationEnabled(true);
67. }
68. }
69. else {
70. buildGoogleApiClient();
71. mMap.setMyLocationEnabled(true);
72. }
73.
74. }
75. protected synchronized void buildGoogleApiClient() {
76. mGoogleApiClient = new GoogleApiClient.Builder(this)
77. .addConnectionCallbacks(this)
78. .addOnConnectionFailedListener(this)
79. .addApi(LocationServices.API).build();
80. mGoogleApiClient.connect();
81. }
82.
83. @Override
84. public void onConnected(Bundle bundle) {
85.
86. mLocationRequest = new LocationRequest();
87. mLocationRequest.setInterval(1000);
88. mLocationRequest.setFastestInterval(1000);
89. mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_PO
WER_ACCURACY);
90. if (ContextCompat.checkSelfPermission(this,
91. Manifest.permission.ACCESS_FINE_LOCATION)
92. == PackageManager.PERMISSION_GRANTED) {
93. LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleA
piClient, mLocationRequest, this);
94. }
95.
96. }
97.
98. @Override
99. public void onConnectionSuspended(int i) {
100.
101. }
102.
103. @Override
104. public void onLocationChanged(Location location) {
105.
106. mLastLocation = location;
107. if (mCurrLocationMarker != null) {
108. mCurrLocationMarker.remove();
109. }
110. //Place current location marker
111. LatLng latLng = new LatLng(location.getLatitude(), location.getLon
gitude());
112. MarkerOptions markerOptions = new MarkerOptions();
113. markerOptions.position(latLng);
114. markerOptions.title("Current Position");
115. markerOptions.icon(BitmapDescriptorFactory.defaultMarker(Bitma
pDescriptorFactory.HUE_GREEN));
116. mCurrLocationMarker = mMap.addMarker(markerOptions);
117.
118. //move map camera
119. mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
120. mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
121.
122. //stop location updates
123. if (mGoogleApiClient != null) {
124. LocationServices.FusedLocationApi.removeLocationUpdates(mGoogle
ApiClient, this);
125. }
126.
127. }
128.
129. @Override
130. public void onConnectionFailed(ConnectionResult connectionResult) {
131.
132. }
133.
134. public void searchLocation(View view) {
135. EditText locationSearch = (EditText) findViewById(R.id.editText);
136. String location = locationSearch.getText().toString();
137. List<Address> addressList = null;
138.
139. if (location != null || !location.equals("")) {
140. Geocoder geocoder = new Geocoder(this);
141. try {
142. addressList = geocoder.getFromLocationName(location, 1);
143.
144. } catch (IOException e) {
145. e.printStackTrace();
146. }
147. Address address = addressList.get(0);
148. LatLng latLng = new LatLng(address.getLatitude(), address.getLongitu
de());
149. mMap.addMarker(new MarkerOptions().position(latLng).title(loc
ation));
150. mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
151. Toast.makeText(getApplicationContext(),address.getLatitude()+"
"+address.getLongitude(),Toast.LENGTH_LONG).show();
152. }
153. }
154.
155. }
Required Permission in AndroidManifest.xml
Add the following user-permission in AndroidManifest.xml file.

1. <uses-permission android:nam
e="android.permission.ACCESS_FINE_LOCATION" />
2. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"
/>
3. <uses-permission android:name="android.permission.INTERNET" />
AndroidManifest.xml
1. <?xml version="1.0" encoding="utf-8"?>
2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3. package="example.com.mapexample">
4. <!--
5. The ACCESS_COARSE/FINE_LOCATION permissions are not required to u
se
6. Google Maps Android API v2, but you must specify either coarse or fine
7. location permissions for the 'MyLocation' functionality.
8. -->
9. <uses-permission android:nam
e="android.permission.ACCESS_FINE_LOCATION" />
10. <uses-permission android:nam
e="android.permission.ACCESS_COARSE_LOCATION" />
11. <uses-permission android:name="android.permission.INTERNET" />
12.
13. <application
14. android:allowBackup="true"
15. android:icon="@mipmap/ic_launcher"
16. android:label="@string/app_name"
17. android:roundIcon="@mipmap/ic_launcher_round"
18. android:supportsRtl="true"
19. android:theme="@style/AppTheme">
20. <!--
21. The API key for Google Maps-based APIs is defined as a string resourc
e.
22. (See the file "res/values/google_maps_api.xml").
23. Note that the API key is linked to the encryption key used to sign the
APK.
24. You need a different API key for each encryption key, including the release ke
y that is used to
25. sign the APK for publishing.
26. You can define the keys for the debug and release targets in src/debug/ and s
rc/release/.
27. -->
28. <meta-data
29. android:name="com.google.android.geo.API_KEY"
30. android:value="@string/google_maps_key" />
31.
32. <activity
33. android:name=".MapsActivity"
34. android:label="@string/title_activity_maps">
35. <intent-filter>
36. <action android:name="android.intent.action.MAIN" />
37.
38. <category android:name="android.intent.category.LAUNCHER" />
39. </intent-filter>
40. </activity>
41. </application>
42.
43. </manifest>

Output
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

SQLiteOpenHelper(Context context, String name, creates an object for creating,


SQLiteDatabase.CursorFactory factory, int version) opening and managing the
database.

SQLiteOpenHelper(Context context, String name, creates an object for creating,


SQLiteDatabase.CursorFactory factory, int version, opening and managing the
DatabaseErrorHandler errorHandler) database. It specifies the error
handler.

Methods of SQLiteOpenHelper class

There are many methods in SQLiteOpenHelper class. Some of them are as follows:

Method Description

public abstract void onCreate(SQLiteDatabase db) called only once when 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.

long insert(String table, String inserts a record on the database. The table
nullColumnHack, ContentValues specifies the table name, nullColumnHack doesn't
values) allow completely null values. If second argument is
null, android will store null values if values are
empty. The third argument specifies the values to
be stored.

int update(String table, updates a row.


ContentValues values, String
whereClause, String[] whereArgs)

Cursor query(String table, returns a cursor over the resultset.


String[] columns, String
selection, String[] selectionArgs,
String groupBy, String having,
String orderBy)

Example of android SQLite database


Let's see the simple example of android sqlite database.

File: Contact.java

1. package example.javatpoint.com.sqlitetutorial;
2.
3. public class Contact {
4. int _id;
5. String _name;
6. String _phone_number;
7. public Contact(){ }
8. public Contact(int id, String name, String _phone_number){
9. this._id = id;
10. this._name = name;
11. this._phone_number = _phone_number;
12. }
13.
14. public Contact(String name, String _phone_number){
15. this._name = name;
16. this._phone_number = _phone_number;
17. }
18. public int getID(){
19. return this._id;
20. }
21.
22. public void setID(int id){
23. this._id = id;
24. }
25.
26. public String getName(){
27. return this._name;
28. }
29.
30. public void setName(String name){
31. this._name = name;
32. }
33.
34. public String getPhoneNumber(){
35. return this._phone_number;
36. }
37.
38. public void setPhoneNumber(String phone_number){
39. this._phone_number = phone_number;
40. }
41. }
File: DatabaseHandler.java
Now, let's create the database handler class that extends SQLiteOpenHelper class
and provides the implementation of its methods.

1. package example.javatpoint.com.sqlitetutorial;
2.
3. import android.content.ContentValues;
4. import android.content.Context;
5. import android.database.Cursor;
6. import android.database.sqlite.SQLiteDatabase;
7. import android.database.sqlite.SQLiteOpenHelper;
8. import java.util.ArrayList;
9. import java.util.List;
10.
11.
12. public class DatabaseHandler extends SQLiteOpenHelper {
13. private static final int DATABASE_VERSION = 1;
14. private static final String DATABASE_NAME = "contactsManager";
15. private static final String TABLE_CONTACTS = "contacts";
16. private static final String KEY_ID = "id";
17. private static final String KEY_NAME = "name";
18. private static final String KEY_PH_NO = "phone_number";
19.
20. public DatabaseHandler(Context context) {
21. super(context, DATABASE_NAME, null, DATABASE_VERSION);
22. //3rd argument to be passed is CursorFactory instance
23. }
24.
25. // Creating Tables
26. @Override
27. public void onCreate(SQLiteDatabase db) {
28. String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
29. + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
30. + KEY_PH_NO + " TEXT" + ")";
31. db.execSQL(CREATE_CONTACTS_TABLE);
32. }
33.
34. // Upgrading database
35. @Override
36. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
37. // Drop older table if existed
38. db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
39.
40. // Create tables again
41. onCreate(db);
42. }
43.
44. // code to add the new contact
45. void addContact(Contact contact) {
46. SQLiteDatabase db = this.getWritableDatabase();
47.
48. ContentValues values = new ContentValues();
49. values.put(KEY_NAME, contact.getName()); // Contact Name
50. values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
51.
52. // Inserting Row
53. db.insert(TABLE_CONTACTS, null, values);
54. //2nd argument is String containing nullColumnHack
55. db.close(); // Closing database connection
56. }
57.
58. // code to get the single contact
59. Contact getContact(int id) {
60. SQLiteDatabase db = this.getReadableDatabase();
61.
62. Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
63. KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
64. new String[] { String.valueOf(id) }, null, null, null, null);
65. if (cursor != null)
66. cursor.moveToFirst();
67.
68. Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
69. cursor.getString(1), cursor.getString(2));
70. // return contact
71. return contact;
72. }
73.
74. // code to get all contacts in a list view
75. public List<Contact> getAllContacts() {
76. List<Contact> contactList = new ArrayList<Contact>();
77. // Select All Query
78. String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
79.
80. SQLiteDatabase db = this.getWritableDatabase();
81. Cursor cursor = db.rawQuery(selectQuery, null);
82.
83. // looping through all rows and adding to list
84. if (cursor.moveToFirst()) {
85. do {
86. Contact contact = new Contact();
87. contact.setID(Integer.parseInt(cursor.getString(0)));
88. contact.setName(cursor.getString(1));
89. contact.setPhoneNumber(cursor.getString(2));
90. // Adding contact to list
91. contactList.add(contact);
92. } while (cursor.moveToNext());
93. }
94.
95. // return contact list
96. return contactList;
97. }
98.
99. // code to update the single contact
100. public int updateContact(Contact contact) {
101. SQLiteDatabase db = this.getWritableDatabase();
102.
103. ContentValues values = new ContentValues();
104. values.put(KEY_NAME, contact.getName());
105. values.put(KEY_PH_NO, contact.getPhoneNumber());
106.
107. // updating row
108. return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
109. new String[] { String.valueOf(contact.getID()) });
110. }
111.
112. // Deleting single contact
113. public void deleteContact(Contact contact) {
114. SQLiteDatabase db = this.getWritableDatabase();
115. db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
116. new String[] { String.valueOf(contact.getID()) });
117. db.close();
118. }
119.
120. // Getting contacts Count
121. public int getContactsCount() {
122. String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
123. SQLiteDatabase db = this.getReadableDatabase();
124. Cursor cursor = db.rawQuery(countQuery, null);
125. cursor.close();
126.
127. // return count
128. return cursor.getCount();
129. }
130.
131. }
File: MainActivity.java

1. package example.javatpoint.com.sqlitetutorial;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.util.Log;
6. import java.util.List;
7.
8. public class MainActivity extends AppCompatActivity {
9.
10. @Override
11. protected void onCreate(Bundle savedInstanceState) {
12. super.onCreate(savedInstanceState);
13. setContentView(R.layout.activity_main);
14. DatabaseHandler db = new DatabaseHandler(this);
15.
16. // Inserting Contacts
17. Log.d("Insert: ", "Inserting ..");
18. db.addContact(new Contact("Ravi", "9100000000"));
19. db.addContact(new Contact("Srinivas", "9199999999"));
20. db.addContact(new Contact("Tommy", "9522222222"));
21. db.addContact(new Contact("Karthik", "9533333333"));
22.
23. // Reading all contacts
24. Log.d("Reading: ", "Reading all contacts..");
25. List<Contact> contacts = db.getAllContacts();
26.
27. for (Contact cn : contacts) {
28. String log = "Id: " + cn.getID() + " ,Name: " + cn.getName() + " ,Phone: " +
29. cn.getPhoneNumber();
30. // Writing Contacts to log
31. Log.d("Name: ", log);
32. }
33. }
34. }
Output:

How to view the data stored in sqlite in android


studio?
Follow the following steps to view the database and its data stored in android sqlite:

o Open File Explorer.


o Go to data directory inside data directory.
o Search for your application package name.
o Inside your application package go to databases where you will found your database
(contactsManager).
o Save your database (contactsManager) anywhere you like.
o Download any SqLite browser plugins or tool (in my case DB Browser for SQLite).
o Launch DB Browser for SQLite and open your database (contactsManager).
o Go to Browse Data -> select your table (contacts) you will see the data stored.
Android Sqlite Example (with
Spinner)
In this example, we are adding a label on button click and displaying all the added
labels on the spinner. As you have seen in the previous
example, SQLiteOpenHelper class need to be extended for performing operations
on the sqlite.
We have overridden the onCreate() and onUpgrade() method of SQLiteOpenHelper
class in the DatabaseHandler class that provides additional methods to insert and
display the labels or data.

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. <?xml version="1.0" encoding="utf-8"?>


2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.sqlitespinner.MainActivity">
8.
9.
10. <EditText
11. android:id="@+id/input_label"
12. android:layout_width="wrap_content"
13. android:layout_height="wrap_content"
14. android:layout_alignParentTop="true"
15. android:layout_centerHorizontal="true"
16. android:layout_marginTop="46dp"
17. android:hint="Add item"
18. android:ems="10" />
19.
20. <Button
21. android:id="@+id/btn_add"
22. android:layout_width="wrap_content"
23. android:layout_height="wrap_content"
24. android:layout_below="@+id/input_label"
25. android:layout_centerHorizontal="true"
26. android:layout_marginTop="67dp"
27. android:text="Add item" />
28.
29. <Spinner
30. android:id="@+id/spinner"
31. android:layout_width="match_parent"
32. android:layout_height="wrap_content"
33. android:layout_alignParentLeft="true"
34. android:layout_alignParentStart="true"
35. android:layout_below="@+id/btn_add"
36. android:layout_marginTop="70dp" />
37. </RelativeLayout>

Activity class
File: MainActivity.java

1. package example.javatpoint.com.sqlitespinner;
2.
3. import android.content.Context;
4. import android.support.v7.app.AppCompatActivity;
5. import android.os.Bundle;
6. import android.view.View;
7. import android.view.inputmethod.InputMethodManager;
8. import android.widget.AdapterView;
9. import android.widget.ArrayAdapter;
10. import android.widget.Button;
11. import android.widget.EditText;
12. import android.widget.Spinner;
13. import android.widget.Toast;
14. import java.util.List;
15.
16. public class MainActivity extends AppCompatActivity implements AdapterView.OnIt
emSelectedListener {
17. Spinner spinner;
18. Button btnAdd;
19. EditText inputLabel;
20. @Override
21. protected void onCreate(Bundle savedInstanceState) {
22. super.onCreate(savedInstanceState);
23. setContentView(R.layout.activity_main);
24. spinner = findViewById(R.id.spinner);
25. btnAdd = findViewById(R.id.btn_add);
26. inputLabel = findViewById(R.id.input_label);
27.
28. spinner.setOnItemSelectedListener(this);
29.
30. // Loading spinner data from database
31. loadSpinnerData();
32.
33. btnAdd.setOnClickListener(new View.OnClickListener() {
34.
35. @Override
36. public void onClick(View arg0) {
37. String label = inputLabel.getText().toString();
38.
39. if (label.trim().length() > 0) {
40. DatabaseHandler db = new DatabaseHandler(getApplicationContext());
41. db.insertLabel(label);
42.
43. // making input filed text to blank
44. inputLabel.setText("");
45.
46. // Hiding the keyboard
47. InputMethodManager imm = (InputMethodManager)
48. getSystemService(Context.INPUT_METHOD_SERVICE);
49. imm.hideSoftInputFromWindow(inputLabel.getWindowToken(), 0)
;
50. // loading spinner with newly added data
51. loadSpinnerData();
52. } else {
53. Toast.makeText(getApplicationContext(), "Please enter label name
",
54. Toast.LENGTH_SHORT).show();
55. }
56.
57. }
58. });
59. }
60.
61. /**
62. * Function to load the spinner data from SQLite database
63. * */
64. private void loadSpinnerData() {
65. DatabaseHandler db = new DatabaseHandler(getApplicationContext());
66. List<String> labels = db.getAllLabels();
67.
68. // Creating adapter for spinner
69. ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,an
droid.R.layout.simple_spinner_item, labels);
70.
71. // Drop down layout style - list view with radio button
72. dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropd
own_item);
73.
74. // attaching data adapter to spinner
75. spinner.setAdapter(dataAdapter);
76. }
77.
78. @Override
79. public void onItemSelected(AdapterView<?> parent, View view, int positio
n,
80. long id) {
81. // On selecting a spinner item
82. String label = parent.getItemAtPosition(position).toString();
83.
84. // Showing selected spinner item
85. Toast.makeText(parent.getContext(), "You selected: " + label,
86. Toast.LENGTH_LONG).show();
87.
88. }
89.
90. @Override
91. public void onNothingSelected(AdapterView<?> arg0) {
92. // TODO Auto-generated method stub
93.
94. }
95. }
DatabaseHandler class
File: DatabaseHandler.java

1. package example.javatpoint.com.sqlitespinner;
2.
3. import android.content.ContentValues;
4. import android.content.Context;
5. import android.database.Cursor;
6. import android.database.sqlite.SQLiteDatabase;
7. import android.database.sqlite.SQLiteOpenHelper;
8. import java.util.ArrayList;
9. import java.util.List;
10.
11. public class DatabaseHandler extends SQLiteOpenHelper {
12. private static final int DATABASE_VERSION = 1;
13. private static final String DATABASE_NAME = "spinnerExample";
14. private static final String TABLE_NAME = "labels";
15. private static final String COLUMN_ID = "id";
16. private static final String COLUMN_NAME = "name";
17.
18. public DatabaseHandler(Context context) {
19. super(context, DATABASE_NAME, null, DATABASE_VERSION);
20. }
21.
22. // Creating Tables
23. @Override
24. public void onCreate(SQLiteDatabase db) {
25. // Category table create query
26. String CREATE_ITEM_TABLE = "CREATE TABLE " + TABLE_NAME + "("
27. + COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_NAME + " T
EXT)";
28. db.execSQL(CREATE_ITEM_TABLE);
29. }
30.
31. // Upgrading database
32. @Override
33. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
34. // Drop older table if existed
35. db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
36.
37. // Create tables again
38. onCreate(db);
39. }
40.
41. /**
42. * Inserting new lable into lables table
43. * */
44. public void insertLabel(String label){
45. SQLiteDatabase db = this.getWritableDatabase();
46.
47. ContentValues values = new ContentValues();
48. values.put(COLUMN_NAME, label);//column name, column value
49.
50. // Inserting Row
51. db.insert(TABLE_NAME, null, values);//tableName, nullColumnHack, Cote
ntValues
52. db.close(); // Closing database connection
53. }
54.
55. /**
56. * Getting all labels
57. * returns list of labels
58. * */
59. public List<String> getAllLabels(){
60. List<String> list = new ArrayList<String>();
61.
62. // Select All Query
63. String selectQuery = "SELECT * FROM " + TABLE_NAME;
64.
65. SQLiteDatabase db = this.getReadableDatabase();
66. Cursor cursor = db.rawQuery(selectQuery, null);//
selectQuery,selectedArguments
67.
68. // looping through all rows and adding to list
69. if (cursor.moveToFirst()) {
70. do {
71. list.add(cursor.getString(1));//adding 2nd column data
72. } while (cursor.moveToNext());
73. }
74. // closing connection
75. cursor.close();
76. db.close();
77. // returning lables
78. return list;
79. }
80. }

download this android example


Output:

You might also like