MAD PPTs

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

MOBILE APPLICATION DEVELOPMENT

(Common to CSE, CSE-AI, AIML, CSE-IOT)


Course Code 21A050422
By
Ch.Venkateswarlu
UNIT I (9 Hrs)
Introduction to Android: The Android 4.1 jelly Bean SDK, Understanding the Android
Software Stack, installing the Android SDK, Creating Android Virtual Devices, Creating the
First Android Project, Using the Text view Control, Using the Android Emulator, The Android
Debug Bridge(ADB), Launching Android Applications on a Handset.

UNIT II (9 Hrs)
Basic Widgets: Understanding the Role of Android Application Components, Overview of
the Android Project Files, Understanding Activities, Role of the Android Manifest File,
Creating the User Interface, Commonly Used Layouts and Controls, Event Handling,
Displaying Messages Through Toast, Creating and Starting an Activity, Using the Edit Text
Control, Choosing Options with Checkbox, Choosing Mutually Exclusive Items Using Radio
Buttons.

UNIT III (9 Hrs)


Building Blocks for Android Application Design: Introduction to Layouts, Linear Layout,
Relative Layout, Absolute Layout, Using Image View, Frame Layout, Table Layout, Grid
Layout, Adapting to Screen orientation.
Utilizing Resources and Media: Resources, Creating Values Resources, Using Drawable
Resources, Switching States with Toggle Buttons, Creating an Images Switcher Application,
Scrolling Through Scroll View, playing Audio, Playing Video, Displaying Progress with
Progress Bar, Using Assets.
UNIT IV (9 Hrs)
Using Selection widgets and Debugging: Using List View, Using the Spinner control, Using
the GridView Control, Creating an Image Gallery Using the ViewPager Control, Using the
Debugging Tool: Dalvik Debug Monitor Service(DDMS), Debugging Application, Using the
Debug Perspective.
Displaying And Fetching Information Using Dialogs and Fragments: What Are Dialogs?,
Selecting the Date and Time in One Application, Fragments, Creating Fragments with java
Code, Creating Special Fragments.

UNIT V (9 Hrs)
Building Menus and Storing Data: Creating Interface Menus and Action Bars, Menus and
Their Types, Creating Menus Through XML, Creating Menus Through Coding, Applying a
Context Menu to a List View, Using the Action Bar, Replacing a Menu with the Action Bar,
Creating a Tabbed Action Bar, Creating a Drop-Down List Action Bar.

Using Databases: Using the SQLite Open Helper class, Accessing Databases with the ADB,
Creating a Data Entry Form.

Communicating with SMS and Emails: Understanding Broadcast Receivers, Using the
Notification System, Sending SMS Messages with Java Code, Receiving SMS Messages,
Sending Email, Working With Telephony Manager.
TEXTBOOKS:
1. Android Programming , B.M Harwani, Pearson Education, 2013

REFERENCE BOOKS:
1. Android application Development for Java Programmers , James C Sheusi, Cengage
Learning
2. Android In Action , W. Frank Ableson, Robi Sen, Chris King, C. Enrique Ortiz., Dreamtech.
3. Professional Android 4 applications development , Reto Meier, Wiley India, 2012.
4. Beginning Android 4 applications development , Wei Meng Lee, Wiley India,2013
5. Beginning Android Development: Create Your Own Android , PawPrints Learning
Technologies, Apps Today, 2014.
6. Android Programming: Pushing the Limits , Erik Hellman, John Wiley and sons ltd, 2014.
7. Introduction to Android Application Development , Joseph Annuzzi, Jr, Lauren Darcey,
Addison-Wesley, 4th Edition.
INTRODUCTION TO ANDROID
What is Android?
•Android is an open source and Linux-based Operating System for mobile
devices such as smart phones and tablet computers.
•Android was developed by the Open Handset Alliance, led by Google, and
other companies.
•Android offers a unified approach to application development for mobile
devices which means developers need only develop for Android, and their
applications should be able to run on different devices powered by
Android.
•The first beta version of the Android Software Development Kit (SDK) was
released by Google in 2007 where as the first commercial version, Android
1.0, was released in September 2008.
•On June 27, 2012, at the Google I/O conference, Google announced the
next Android version, 4.1 Jelly Bean. Jelly Bean is an incremental update,
with the primary aim of improving the user interface, both in terms of
functionality and performance.
Why Android ?
Features of Android
S.NO FEATURE DESCRIPTION
1 Beautiful UI Android OS basic screen provides a beautiful and intuitive user
interface.
2 Connectivity GSM/EDGE, IDEN, CDMA, EV-DO, UMTS, Bluetooth, Wi-Fi, LTE,
NFC and WiMAX.
3 Storage SQLite, a lightweight relational database, is used for data
storage purposes.
4 Media H.263, H.264, MPEG-4 SP, AMR, AMR-WB, AAC, HE-AAC, AAC
support 5.1, MP3, MIDI, Ogg Vorbis, WAV, JPEG, PNG, GIF, and BMP.
5 Messaging SMS and MMS
6 Web Based on the open-source WebKit layout engine, coupled with
browser Chrome's V8 JavaScript engine supporting HTML5 and CSS3.
7 Faster Speech recognition is now faster and doesnot require any
Speech network to convert voice to text.i.e users can dictate to the
Recognition system without an internet.
8 Wi-Fi Direct A technology that lets apps discover and pair directly, over a
high-bandwidth peer-to-peer connection.
S.NO Feature Description
9 Improved The Jelly Bean Camera app includes a new review mode of
Camera app the captured photos. Users can swipe in from the right of the
screen to quickly view the captured photos. Also, users can
pinch to switch to a new film strip view, where they can swipe
to delete photos.
10
Supports new Jelly Bean includes support for several languages including
languages Arabic, Hebrew, Hindi, and Thai. It also supports bidirectional
text.

11
Improved Jelly Bean is equipped with a question and answer search
Google Voice method that helps in solving users' queries similar to Apple's
search popular Siri.

12
Supports This feature supports developers in the sense that the
antipiracy applications are encrypted with a device-specific key making
it difficult to copy and upload them to the Internet.
Android Applications
• Android applications are usually developed in the Java
language using the Android Software Development Kit.
• Once developed, Android applications can be packaged
easily and sold out either through a store such
as Google Play, SlideME, Opera Mobile
Store, Mobango, F-droid and the Amazon Appstore.
• Android powers hundreds of millions of mobile devices
in more than 190 countries around the world. It's the
largest installed base of any mobile platform and
growing fast. Every day more than 1 million new
Android devices are activated worldwide.
• Categories of Android applications
• There are many android applications in the
market. The top categories are −
History of Android
• The code names of android ranges from A to Q currently, such as
• Aestro
• Blender
• Cupcake
• Donut
• Eclair
• Froyo
• Gingerbread
• Honeycomb
• Ice Cream Sandwitch
• Jelly Bean
• KitKat
• Lollipop
• Marshmallow
• Nougat
• Oreo
• Pie
• Andriod Q
Code Name Version Number Release Date API Level
Cup cake 1.5 April 27, 2009 3
Donut 1.6 Sept 15, 2009 4
Éclair 2.0 - 2.1 Oct 26, 2009 5-7
Froyo 2.2 - 2.2.3 May 20, 2010 8
Ginger bread 2.3 - 2.3.7 Dec 6, 2010 9 - 10
Honey comb 3.0 - 3.2.6 Feb 22, 2011 11 - 13
Ice cream Sandwich 4.0 - 4.0.4 Oct 18, 2011 14 - 15
Jelly bean 4.1 - 4.3.1 July 9, 2012 16 - 18
Kitkat 4.4 - 4.4.4 Oct 31, 2013 19 - 20
Lollipop 5.0 - 5.1.1 Nov 12, 2014 21 - 22
Marsh mallow 6.0 - 6.0.1 Oct 5, 2015 23
Nougat 7.0 - 7.1.2 Aug 22, 2016 24 - 25

Oreo 8.0 - 8.1 Aug 21, 2017 26 - 27


What is API level?
• API Level is an integer value that uniquely
identifies the framework API revision offered
by a version of the Android platform.
Platform Version API Level VERSION_CODE
Android 6.0 23 MARSHMALLOW
Android 5.1 22 LOLLIPOP_MR1
Android 5.0 21 LOLLIPOP
Android 4.4W 20 KITKAT_WATCH
Android 4.4 19 KITKAT
Android 4.3 18 JELLY_BEAN_MR2
Android 4.2, 4.2.2 17 JELLY_BEAN_MR1
Android 4.1, 4.1.1 16 JELLY_BEAN
Android 4.3 18 JELLY_BEAN_MR2
Platform Version API Level VERSION_CODE
Android 4.2, 4.2.2 17 JELLY_BEAN_MR1
Android 4.1, 4.1.1 16 JELLY_BEAN
Android 4.0.3, 4.0.4 15 ICE_CREAM_SANDWICH_MR1
Android 4.0, 4.0.1, 14 ICE_CREAM_SANDWICH
4.0.2
Android 3.2 13 HONEYCOMB_MR2
Android 3.1.x 12 HONEYCOMB_MR1
Android 3.0.x 11 HONEYCOMB
Android 2.3.4 10 GINGERBREAD_MR1
Android 2.3.3
Android 2.3.2 9 GINGERBREAD
Android 2.3.1
Android 2.3
Android 2.2.x 8 FROYO
• You will be glad to know that you can start your Android application
development on either of the following opera ng systems −
• Microsoft Windows XP or later version.
• Mac OS X 10.5.8 or later version with Intel chip.
• Linux including GNU C Library 2.7 or later.
• Second point is that all the required tools to develop Android
applications are freely available and can be downloaded from the
Web. Following is the list of software's you will need before you
start your Android application programming.
• Java JDK5 or later version
• Android Studio
• Here last two components are optional and if you are working on
Windows machine then these components make your life easy
while doing Java based application development.
Android IDEs

• here are so many sophisticated Technologies


are available to develop android applications,
the familiar technologies, which are
predominantly using tools as follows
• Android Studio
• Eclipse IDE(Deprecated)
Android - Architecture
(Android Software Stack)
• Android operating system is a stack of software
components which is roughly divided into five
sections and four main layers as shown below in the
architecture diagram.
Term Description

View Views are user interface (UI) controls that collectively make up the Screen of
application. TextView, Buttons and edit text controls are all individually
known as views. Views are placed in containers known as layouts.

ViewGroup ViewGroups are extensions of the view class that can contain multiple Child
views. Examples of ViewGroup include LinearLayout, AbsoluteLayout,
TableLayout, RelativeLayout, FrameLayout and ScrollView.

Activity Android applications must have at least one activity. Activity represents
single screen in an application and consists of one or more views. If more
than one activity in the application, they work independently. Activities in
android are usually started with an intent.

Intent Intent is a message-passing mechanism telling the android application when


user is asking it to do. It represents the action to execute in response to the
event, along with the data on which to perform the action.
Android - Hello World Example
The file imports the desired class files and also inherits the Activity class.

The onCreate () method is invoked when the Activity is started. It calls the
onCreate () method of the super class (the Activity class) for initializing an activity.

In statement #1, the parameter Bundle savedlnstanceState refers to a bundle used to
pass information between different activities.
Statement #2 is essential for activity initialization. If you don't write this statement
into the Java file, you get a runtime exception.
Statement #3 defines the screen (user interface) of the activity
HelloworldAppActivity.
Basically, the user interface defined in the layout file activity_hello_world_app.xml is
set as the content of an activity file.

The parameter R.layout.activity_hello_world_app in the setContent () method refers


to the activity_hello_world_app.xml file of the project's res/layout folder.

The character R in the parameter refers to the auto-generated R. java class file

Statement #4 defines the onCreateoptionsMenu() method that is meant for dealing


with menus.
Assign text to the Text View in two ways:
1. Direct assignment to the Text View control as defined in the layout file activity_hello_
world_app.xml
2. Indirectly through the java Activity files Hello World App Activity.java.

Assigning the Text Directly in the layout File:

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true“/>
Assigning Text through the Activity File:
1. Remove the text from XML definition-
android: text=” ”
2. Assign an ID to the Text View control-
android:id=”@+id/message”
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/message"
/>

After assign ID to TextView control, it will be accessible in Activity file.

import android.widget.TextView;
public class HelloWorldAppActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello_world_app);
TextView mesg = (TextView) findViewById(R.id.message);
mesg.setText("HelloWorld !");
}
Applying Dimensions to Controls:
Dimensions are commonly used to specify the size and other properties for the controls and
layouts. The following units of measurements are used:
px (pixels)—Corresponds to the actual pixels on the screen.
in (inches)—Based on the actual size of the screen.
mm (millimetres)—Based on actual size of the screen.
pts (points)—Points are a fixed dimension—1/72 of an inch.
dip or dp (device-independent pixels)—Based on the physical density of the screen.
sp (scale independent pixels)—Similar to the dp unit, but also depends on the user’s font size
settings. Hence this unit is preferred while specifying font sizes.

Aligning Content with the Gravity Attribte:


The gravity attribute is used for aligning the content within a control or it’s container. To align
text of the TextView control to the center, you set the value of its android:gravity attribute to
center. Some of the valid values for the android:gravity attribute are shown in below
Top
Bottom
Left
Right
center_horizontal
center_veritcal
fill_horizontal
fill_veritcal
Center
setGravity()
Commonly Used Attributes:
List of attributes commonly applied to configure the controls are shown below.
Attributes Java Method
android:width setWidth()
android:height setHeight()
android:text setText()
android:textColor setTextColor()
android:textSize setTextSize()
android:ellipsize setEllipSize() Valid options are none, start, middle, end and marquee.
android:singleLine setTransformationMethod()
android:background setBackgroundResource()
android:textStyle setTypeface()
android:typeface setTypeface()

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/message"
android:typeface="serif"
android:textColor="#0f0"
android:textSize="25dp"
android:textStyle="italic"
android:gravity="center_horizontal" />
Using the Android Emulator:
The Android emulator is used for testing and debugging applications before they are loaded
onto a real handset. The Android emulator is integrated into Eclipse through the ADT plug-in.
Limitations of the Android Emulator:
The android emulator is useful to test android applications for compatibility with devices of
different configurations. It is a piece of software and not an actual device has several limitations:
1. Emulators no doubt help in knowing how an application may operate within a given
environment, but they still don’t provide the actual environment like memory, CPU or other
physical limitations to application.
2. Emulators just simulate certain handset behaviour. Features such as GPS, Sensors, Battery,
Power settings and network connectivity can be easily simulated on a computer.
3. SMS messages are also simulated and do not use a real network.
4. Phone calls cannot be placed or received but are simulated.
5. No support for device attached headphones is available.
6. Peripherals such as camera/video capture are not fully functional.
7. No USB or Bluetooth support is available.
Eclipse IDE provides three perspectives to work
The Java Perspective :-
It’s the default perspective in Eclipse where you spend most of the time. It shows the panes
where you can write code and navigate around the project.
The Debug perspective :-
It enables application debugging. You can set breakpoints, step through the code, view LogCat
logging information, threads and so on.
The Dalvik Debug Monitor Service (DDMS) perspective :-
It enables you to monitor and manipulate emulator and device status. It also provides screen
capture and simulates incoming phone calls, SMS sending and GPS coordinates.

The Android Debug Bridge (ADB):


The android debug bridge (ADB) is a client-server program that is part of the android SDK. It is
used to communicate with, control and manage the android device and emulator.
It consists of three components:
CLIENT --Runs on a computer machine. It can be invoked from the command prompt using
the adb command.
DAEMON --Runs as a background process in either an emulator instances or in device itself.
SERVER --Runs in a computer machine in the background. It manages the communication
between the client and the daemon.
When you install the android SDK, the Android Debug Bridge is also automatically installed along
with it. When ADB is activating, you can issue adb commands to interact with one or more
emulator instances.
Using the shell command, you can perform several tasks such as listing existing applications,
deleting applications, and querying or modifying SQLite database on device.

To access ADB through windows, open the command prompt and navigate to the folder where
adb.exe is located by using the cd command.

By default, adb.exe is installed in C:\program files(x86)\Android-sdk\platform-tools. After


finding adb, you can issue the following commands to interact with the device or emulator:
adb devices --- Displays the list of devices attached to the computer currently on your
computer, emulator-5554.
adb push --- Copies files from your computer to the device /emulator.
Syntax :- adb push source destination
Where source to the file along with its path that you want to copy, an
destination refers to the device or emulator where you want to copy the file.
adb pull --- Copies files from the device/emulator to your computer.
Syntax:- adb pull source(destination)
adb shell --- Display the shell prompt where can issue Unix commands. You can see the
names of different files and folders of the emulator after issue ls a command.

You can use the commands to list, rename, and delete applications from the emulator For
example, to delete the file song 1.mp3 that you pushed into the emulator, you issue the rm
command. To leave Shell; Press Ctrl+d.
adb install --- Install an application from your computer to the device/emulator.
Syntax:- adb install appname.apk

This Code C:\program Files(x860\Android\android-sdk\platform-tools>adb install D:\ androidun


leashed\loginApp.apk.
Installs the application package file loginApp.apk into the emulator.
Launching Android application on hand set:
• To load application on real hand set, you need to plug handset into your
computer, using USB cable.
• First confirm whether configurations for debugging your application are
correct or not and launch application as shown below
1. In eclipse ,choose Run , Debug configuration option
2. Select configuration Helloworld_cofiguration. which you created for
helloworld application
3. Select target tab, set deployment target selection Mode to Manual.
Manual option allows us to choose device or AVD to connect to when
using this configuration
4. Apply changes to configuration file by clicking Apply button
5. Plug an Android device into computer, using USB cable
6. Select Run, Debug in Eclipse or Press F11 key. Dialog box appears, showing
all available configurations for running and debugging your application.
Physical device connected to computer are also listed. Double click
running android device. Eclipse now installs android application on
handset, attaches debugger and runs the application
The Dalvik Virtual Machine (Dalvik VM):
While running Android applications, the android runtime provides the Dalvik virtual machine
that provides an environment to deploy and run Android applications.

Dalvik VM is the androids platform virtual machine written by Dan Bornstein. It is specifically
designed Virtual Machine for android and optimized for mobile devices with limited battery,
memory and computation capability.
When you run an application, the androids SDK access information in the XML files, converts it
into the java source code and place it the R.java file.
The java code in the R.java class file is compiled into the java byte code files, which, with the
help of a tool named dx, is converted into Dalvik byte code and stored in .dex format.
The Dalvik Executable format is optimized for efficient storage and low memory consumption.
Android applications are not deployed in dex code is bundled into an APK file.

The Application Package (APK) file:


The dex code that you get after converting the java file is bundled with other
required data and resources, including the manifest file AndroidMnaifest.xml into an application
package file (.apk).
APK files represent a single application and install it on a mobile device or
emulator. Each APK installed on an Android device is given its own ID that remains unchanged
for long as APK resides on that device. APK must be signed with a certificate whose private key is
held by its developer.
MOBILE APPLICATION DEVELOPMENT
(Common to CSE, CSE-AI, AIML, CSE-IOT)
Course Code 21A050422
By
CH. VENKATESWARLU
Unit II
Basic Widgets
Understanding the Role of Android Application Components
Understanding the Utility of Android API
Overview of the Android Project Files
Understanding Activities
Role of the Android Manifest File
Creating the User Interface
Commonly Used Layouts and Controls
Event Handling
Displaying Messages Through Toast
Creating and Starting an Activity
Using the Edit Text Control
Choosing Options with Checkbox
Choosing Mutually Exclusive Items Using Radio Buttons
WIDGET
Widget is a component of an
interface, that enables a user to
perform a function (or) access a
service.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com. androidunleashed.welcomemsg "
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style.AppTheme">
<activity android:name=".WelcomeMsgActivity"
android:label= "@string/title_activity_welcome_msg”>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
The <manifest> tag, is the root element of this XML document and contains several
attributes.
<uses-sdk>: This tag is optional and is used to specify the Maximum, Minimum and
preferred API level required for the application to operate. Three attributes are used.

<application> tag: which is the parent of application controls tags. @string and
@drawable refer to the strings and drawable resources, respectively.

<activity> tag: which describes an Activity component.


This tag's name attribute identifies a class that is an Activity, welcomemsactivity.
It relative to com.androidunleashed.welcomemsg package.

<intent-filter>: The intents are used to interact with the applications and services.
By default, the intent specifies the action as MAIN and the category as LAUNCHER; that
is, it makes application launcher to launch when the application starts.
The following are some of the most commonly used tags:

<service> tags: Used for declaring service. service refer to the process that run in the
background without a user interface.

<receiver> tags: Used for declaring broadcast receivers. Boardcast receivers are used
to listen and respond to broadcast announcements. An application can have any number
of broadcast receivers. A broadcast receiver responds by taking a specific action.

<provider> tags: Used for declaring content providers. They help in handling, storing,
and sharing data such as audio, images, video and contact lists with other applications.

<uses-permission> tags: Used for declaring the permission that the application needs.
Example:
<uses-permission android:name="android.permission.CAMERA"/>:
Used for the application that needs to use the camera.
<uses-permission android:name="android.permission.INTERNET"/>:
Used for the application that needs to access the internet.

Using the Manifest Editor:


To manipulate androidmanifest.xml file use of the manifest editor in eclipse, right click
the androidmanifest.xml file in the package explorer window, and select open with
android manifest editor.
Creating the User Interface:
There are three approaches to creating user interface in android. You can create user
interface entirely in java code or entirely in XML or in both.

You want to prompt the user to enter a name,and in return the application displays a
welcome message along with the entered name.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Enter your name:"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/user_name"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/click_btn"
android:text="Click Me"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/response"/>
</LinearLayout>

Commonly Used Layouts and Controls:


LinearLayout: In this layout, all elements are arranged in a descending column from top to
bottom or left to right. Each element contains properties to specify how much of the screen space
it will consume.
RelativeLayout: In this layout, each child elements is laid out in relation to other child elements.
That is, child elements appear in the relation to the parent.
AbsoluteLayout: In this layout, each child is given a specific location within the bounds of the
parent layout object. This layout is not suitable for devices with different screen sizes.
FrameLayout: This is a layout used to display a single view. Views added to this are always
placed at the top left of the layout. Any other view that is added to the FrameLayout overlaps the
previous view.
TableLayout: In this layout, the screen is assumed to be divided in table rows, and each of the
child elements is arranged in a specific row and column.
GridLayout: In this layout, child views are arranged in a grid format (in the rows and columns
pattern). The views can be placed at the specified row and column location. Also, more than one
view can be placed at the given row and column position.
The following list highlights some of the controls commonly used in Android applications:

1. Textview: A read-only text label. It supports multiline display, string formatting


automatic word wrapping.

2. EditText: An editable text box that also accepts multiline entry and word-
wrapping.

3. ListView: A ViewGroup that creates and manages a vertical list of views,


displaying them as rows within the list.

4. Spinner: A TextView and an associated list of items that allows us to select an


item from the list to display in the text box.

5. Button: A standard command button.

6. CheckBox: A button allowing a user to select (check) or unselect (uncheck).

7. RadioButton: A mutually exclusive button, which when selected, unselects all other
buttons in the group.
EVENT HANDLING
Event handling should be three ways:
Creating an anonymous inner class
Implementing the OnClickListener interface
Declaring the event handler in the XML definition of the control

Creating an Anonymous Inner Class:


In this method of event handling, an anonymous class is defined with an OnClickListener
interface, and an onClick(View v) method is implemented in it.
The anonymous inner class is passed to the listener through the setOnClickListener( )
method.
Package com.androidunleashed.welcomemsg;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import android.view.View;
public class WelcomeMsgActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_msg);
Button b=(Button)this.findViewById(R.id.click_btn);
Displaying Messages through Toast:
A Toast is a transient message that automatically disappears after a while without user
interaction. It is used to inform the user about happenings that are not very important.

A Toast is created by calling the static method, makeText (), of the Toast class.
The syntax of the makeText () method is shown below:
 Toast.makeText (Activity_context, string_to_display, duration)

The method needs the Activity (Context) String to display, as well as the duration for
which the message is displayed on the screen. You can also supply the ID of the String
resource that you want to display.

The duration is expressed in the form of constants, such as Toast.LENGTH_SHORT or


Toast.LENGTH_LONG, to determine the duration for which the string’s message
remains on the screen.

 You call the show() method on the returned Toast instance to display the containing
string or message.
package com.androidunleashed.Welcomemsg;

import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.view.View;
import android.widget.Toast;

public class WelcomeMsgActivity extends Activity


{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_msg);
}
public void dispMessage(View v)
{
EditText name=(EditText) findViewById(R.id.user_name);
String str="welcome "+name.getText( ).toString( )+" ! ";
Toast.makeText (WelcomeMsgActivity.this, str, Toast.LENGTH_SHORT) .show () ;
}
}
Creating and Starting an Activity:
The structure that is used to start, stop, and transaction between
Activities within an application is called Intent.

Describing Operations through Intent:


Intent is a data structure; it consists of an action that the application
needs to perform, data to operate on, and other information helpful in
executing the operation.
Intent can be explicit or implicit as follows:

Explicit Intent-
In an explicit intent, specify the Activity required to respond to the intent;
that is, explicitly designate the target components. Because, an explicit
intent is limited to be used within an application

Implicit Intent-
In an implicit intent just declare intent and leave it to the platform to find
an Activity that can respond to the intent. It is the job of the Android
platform to search for the most suitable component to handle the implicit
intent.
Method Used to start an activity:
The method used to start an activity is startActivity(). First create an
implicit or explicit intent object and pass it to the startActivity() method
in the format here:
startActivity (my_intent) ;
Where my_intent passed as a parameter to startActivity(). The
startActivity() method find and starts the single Activity that best
matches the given intent.

To explicit specify the Activity that you want to start through an intent,
create a new intent specifying the current application context and class
name of the activity you want to launch and pass this Intent to the
startActivity () method,as shown here:
startActivity (new Intent (this, welcome.class));

If startActivity() is unable to find the specified activity, an


android.content.ActivityNotFound Exception is thrown.
Creating your own Layout file.
To create a new layout file, from the Package Explorer window, right click the res/
layout folder and select the New, Android XML File option. A dialog box appears asking
for information about the new Android XML File. In the File text box, enter the
filename as welcome (no need to add the .xml extension).

Creating a new Activity.


To create an Activity, right-click the package com. androidunieashed.weicomeapp and
select the New, Class option. A New Java Class dialog box appears, requesting you to
enter the name of the Java file. In the Name text box, enter the name of the Activity file,
welcome (no need to add the .java extension).

Register the new Activity.


The new Activity welcome .java must be declared in the AndroidManifest .xml file to
make it visible to Android and start it.

<activity android:name=".Welcome" android:label="@string/app_name" />

Starting the Activity.


startActivity(new lntent(this, Welcome.class));
Attributes Used to Configure the EditText Control:
1. android: layout_width 09. android: password
2. android: layout_height 10. android: minWidth
3. android: singleLine 11. android: maxWidth
4. android: hint 12. android: minHeight
5. android: lines 13. android: maxHeight
6. android: textSize 14. android: scrollHorizontally
7. android: autoText 15. android: inputType
8. android: capitalize
android: inputType
There are many possible values that include
number textCapWords time
Phone textEmailAddress textAutoCorrect
Text datetime textMultiLine
textCapCharacter date textPassword

Adding an Event Listener to the EditText Control:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/user_name"
android:hint="Enter your name:"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/response"/>
</LinearLayout>
Package.com.androidunleashed.edittextapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.EditText;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.KeyEvent;

public class EditTextAppActivity extends Activity {


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

final TextView resp= (TextView) this.findViewById (R.id.response);


final EditText username=(EditText) findViewById(R.id.user_name);
username.setOnKeyListener(new OnKeyListener()
{
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if((event.getAction()== KeyEvent.ACTION_UP) &&
(keyCode==(KeyEvent.KEYCODE_ENTER)))
{
resp.setText("Welcome "+username.getText()+"!");
return true;
}
return false;
}
});
}
}
Use the traditional implementation the onClickListener interface, that invokes the
onClick() method when any of the CheckBox controls are clicked. (OR)
Implement the OnCheckedchangeListener interface that invokes the callback method
oncheckedchanged () when the state of the check box changes.

<CheckBox android:id=”@+id/purchase”
android:layout_height=”wrap_content”
android:layout_width=”match_parent”
android:text=”purchase”/>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select Items you Want"/>

<CheckBox
android:id="@+id/checkbox_pizza"
android:layout_height="wrap_content"
android:text="pizza $15"
android:layout_width="match_parent"/>

<CheckBox
android:id="@+id/checkbox_hotdog"
android:layout_height="wrap_content"
android:text="Hot Dog $5"
android:layout_width="match_parent"/>
<CheckBox
android:id="@+id/checkbox_burger"
android:layout_height="wrap_content"
android:text="Burger $10"
android:layout_width="match_parent"/>

<Button
android:layout_width="match_parent“
android:layout_height="match_parent"
android:id="@+id/bill_btn“
android:text="Calculate Bill"/>

<TextView
android:layout_width="match_parent“
android:layout_height="wrap_content“
android:id="@+id/amount"/>

</LinearLayout>
package com.androidunleashed.checkboxapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.widget.CheckBox;
import android.view.View;
import android.view.View.OnClickListener;

public class CheckBoxAppActivity extends Activity implements OnClickListener


{
CheckBox c1,c2,c3;
TextView resp;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_box_app);
Button b=(Button)this.findViewById(R.id.bill_btn);
resp=(TextView)this.findViewById(R.id.amount);

c1=(CheckBox)this.findViewById(R.id.checkbox_pizza);
c2=(CheckBox)this.findViewById(R.id.checkbox_hotdog);
c3=(CheckBox)this.findViewById(R.id.checkbox_burger);
b.setOnClickListener(this);
}
public void onClick(View v)
{
int amt=0;

if(c1.isChecked()) {
amt=amt+15;
}

if(c2.isChecked()) {
amt=amt+5;
}

if(c3.isChecked()) {
amt=amt+10;
}

resp.setText("Bill is "+Integer.toString(amt));
}
}
To create a group of radio buttons, first create a RadioGroup and then populate the
group with few RadioButtoncontrols, as shown in the following example:
<RadioGroup
android:id=”@+id/group_hotel”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:orientation=”vertical”>
<RadioButton
android:id=”@+id/radio_fivestar”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Five Star”/>
<RadioButton
android:id=”@+id/radio_threestar”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Three Star”/>
</RadioGroup>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select the type of hotel"/>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="@+id/radio_fivestar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Five Star"/>
<RadioButton
android:id="@+id/radio_threestar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Three Star"/>
</RadioGroup>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content” android:id="@+id/hoteltype"/>
</LinearLayout>
packagecom.androidunleashed.radiobutttonapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.RadioButton;
import android.view.View;
import android.view.View.OnClickListener;

public class RadioButtonAppActivty extends Activity{


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activty_radio_button_app);
RadioButton radioFivestar=(RadioButton)findViewById(R.id.radio_fivestar);
RadioButton radioThreestar=(RadioButton)findViewById(R.id.radio_threestar);
radioFivestar.setOnClickListener(radioListener);
radioThreestar.setOnClickListener(radioListener);
}
private OnClickListener radioListener=new OnClickListener(){
public void onClick(View v){
TextView selectedHotel=(TextView)findViewById(R.id.hoteltype);
RadioButton rb=(RadioButton) v;
selectedHotel.setText("The hotel type selected is:" + rb.getText());
}
};
}
Similarly, the other RadioGroup that represents room types will have three RadioButton controls to show
three options: Ordinary Room, Luxury Room, and Grand Suite.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select the type of hotel"/>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="@+id/radio_fivestar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Five Star"/>
<RadioButton
android:id="@+id/radio_threestar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Three Star"/>
</RadioGroup>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/hoteltype"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select the type of room"/>
<RadioGroup
android:id="@+id/group_room"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="@+id/radio_suite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Grand Suite"/>
<RadioButton
android:id="@+id/radio_luxury"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Luxury Room"/>
<RadioButton
android:id="@+id/radio_ordinary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ordinary Room"/>
</RadioGroup>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content” android:id="@+id/roomtype" /> </LinearLayout>
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.RadioButton;
import android.view.View;
import android.view.View.OnClickListener;
public class RadioButtonAppActivity extends Activity{
String str1=" ";
String str2=" ";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio_button_app);

RadioButton radioFivestar = (RadioButton) findViewById(R.id.radio_fivestar);


RadioButton radioThreestar=(RadioButton) findViewById(R.id.radio_threestar);
RadioButton radioSuite = (RadioButton) findViewById(R.id.radio_suite);
RadioButton radioLuxury = (RadioButton) findViewById(R.id.radio_luxury);
RadioButton radioOrdinary = (RadioButton) findViewById(R.id.radio_ordinary);

radioFivestar.setOnClickListener(radioListener1);
radioThreestar.setOnClickListener(radioListener1);
radioSuite.setOnClickListener(radioListener2);
radioLuxury.setOnClickListener(radioListener2);
radioOrdinary.setOnClickListener(radioListener2); }
private OnClickListener radioListener1 = new OnClickListener() {
public void onClick(View v)
{
TextView selectedOptions = (TextView) findViewById(R.id.hoteltype);
RadioButton rb = (RadioButton) v;
str1 = "The hotel type selected is: " + rb.getText();
selectedOptions.setText(str1 + "\n" + str2);
}
};

private OnClickListener radioListener2 = new OnClickListener() {


public void onClick(View v)
{
TextView selectedOptions = (TextView) findViewById(R.id.roomtype);
RadioButton rb = (RadioButton) v;
str2="Room type selected is: "+rb.getText();
selectedOptions.setText(str1+"\n"+str2);
}
};

}
MOBILE APPLICATION DEVELOPMENT
(Common to CSE, CSE-AI, AIML, CSE-IOT)
Course Code 21A050422
By
CH VENKATESWARLU
UNIT-III LAYING OUT CONTROLS IN CONTAINERS

Introduction to Layouts
Linear Layout
Applying the Orientation Attribute
Applying Height and Width Attributes
Applying the Padding Attribute
Applying the weight attribute
Applying the Gravity Attribute
Using the android: layout_gravity Attribute
Relative Layout
Relative Layout Control Attributes
Absolute Layout
Frame Layout
Table Layout
Table Layout Operations
Grid Layout
Screen Orientation Adaptations
I. Introduction to Layouts
Layouts are basically containers for other items known as views, which are displayed on the
screen. Layouts help manage and arrange views as well. Layouts are defined in the form of XML
files that cannot be changed by our code during runtime.

Layout Manager Description


LinearLayout Organizes its children either horizontally or vertically.
RelativeLayout Organizes its children relative to one another or to the parent.
AbsoluteLayout Each child control is given a specific location within the bounds of the
container.
FrameLayout Displays a single view; that is, the next view replaces the previous view
and hence is used to dynamically change the children in the layout.
TableLayout Organizes its children in tabular form.
GridLayout Organizes its children in grid format.

II. LinearLayout
The LinearLayout is the most basic layout, and it arranges its elements sequentially, either
horizontally or vertically. To arrange controls within a linear layout, the following attributes are
used:
•android: orientation — Used for arranging the controls in the container in horizontal or
vertical order.
•android: layout _width — Used for defining the width of a control.
•android: layout_height — Used for defining the height of a control.
•android: padding — Used for increasing the whitespace between the boundaries of the
control and its actual content.
•android: layout_weight—Used for shrinking or expanding the size of the control to
consume the extra space relative to the other controls in the container
•android: gravity—Used for aligning content within a control
•android: layout_gravity—Used for aligning the control within the container

Applying the orientation Attribute


The orientation can be modified at runtime through the setOrientation() method. That is, by
supplying the values HORIZONTAL or VERTICAL to the setOrientation() method.

Applying the height and width Attributes


The values for the height and width attributes in the following three ways:
•By supplying specific dimension values for the control in terms of px (pixels), dip/ dp (device
independent pixels), sp (scaled pixels), pts (points), in (inches), and mm (millimeters). For
example, the android: layout_width="20px" attribute sets the width of the control to 20 pixels.
•By providing the value as wrap_content.
•By providing the value as match_parent.

Applying the padding Attribute


The padding attribute is used to increase the whitespace between the boundaries of the control
and its actual content. The android: paddingLeft, android: paddingRight, android: paddingTop,
and android: paddingBottom attributes
android: padding=“5dip”
android: paddingLeft="5dip"
To set the padding at runtime, we can call the setPadding() method.
Let's apply the LinearLayout and add three Button controls to the layout.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent“
android:orientation="vertical" >
<Button
android:id="@+id/Apple"
android:text="Apple"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/Mango"
android:text="Mango"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/Banana"
android:text="Banana"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
The activity_linear_layout_app.xml File on Setting Horizontal Orientation to the Button
Controls

<LinearLayout xmlns:android= http://schemas.android.com/apk/res/android


android: layout_width- "match_parent“
android:layout_height="match_parent"
android:orientation="horizontal" >
<Button
android: id="@+id/Apple"
android: text="Apple"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+ id/Mango"
android:text="Mango"
android: layout_width= "wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/Banana"
android: text= "Banana"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Applying the weight Attribute
The weight attribute affects the size of the control. That is, we use weight to assign the capability to expand or
shrink and consume extra space relative to the other controls in the container. The values of the weight attribute
range from 0.0 to 1.0, where 1.0 is the highest value.
The activity_linear_layout_app.xml File on Applying the weight Attribute to the Button Controls
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/Apple"
android:text="Apple"
android:layout_width="wrap_content"
android:layout_height="wrap_content“
android:layout_weight=“0.0" />
<Button
android:id="@+id/Mango"
android:text="Mango“
android:layout_width="wrap_content"
android:layout_height=wrap_content"
android:layout_weight="1.0" />
<Button
android:id="@+id/Banana"
android:text="Banana"
android:layout_width="wrap_content"
android:layout_height=wrap_content"
android:layout_weight="0.0" />
</LinearLayout>
Similarly if we set the weight of Apple, Mango, and Banana t0 0.0,1.0 and 0.5, respectively then check the output.
Applying the Gravity Attribute
The Gravity attribute is for aligning the content within a control.
For example, to align the text of a control to the center, we set the value of its
android:gravity attribute to center.
The valid options for android:gravity include left, center, right, top, bottom,
center_horizontal, center_vertical, fill_horizontal, and fill_vertical.

The task performed by few of the said options is as follows:


center _vertical—Places the object in the vertical center of its container, without
changing its size.
fill_vertical—Grows the vertical size of the object, if needed, so it completely fills its
container
center_horizontal—Places the object in the horizontal center of its container, without
changing its size.
fill_horizontal—Grows the horizontal size of the object, if needed, so it completely
fills its container.
center—Places the object in the center of its container in both the vertical and
hori­zontal axis, without changing its size.
We can also combine two or more values of any attribute using the | operator.
android:gravity="center_horizontal|center_vertical”
Using the android: layout_gravity Attribute
Where android:gravity is a Setting used by the View,
the android: layout_gravity is used by the container.
That is, this attribute is used to align the control within the container.

To align the Button controls Mango and Banana to the center and to the right of
the LinearLayout container, add the following statements to the respective tags
in the xml layout file:
android:layout_gravity="center“
android:layout_gravity="right“

Let's add the following three attributes to the Button controls Apple, Mango,
and Banana:
android:gravity="left" android:gravity="center"
and
android:gravity="right“
For example, assigning the android: layout_ weight=“1.0" to all three controls
android:gravity="center_vertical" for the Apple control
android:gravity="center_vertical | right" for the Banana control
III. RelativeLayout
In RelativeLayout, each child element is laid out in relation to other child elements;
that is, the location of a child element is specified in terms of the desired distance
from the existing children.
<RelativeLayout xmlns :android= "http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android: id="@+id/Apple"
android:text="Apple"
android: layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop=“15dip"
android: layout_marginLeft="20dip" />
<Button
android:id="@+id/Mango"
android:text="Mango"
android: layout_width= "match_parent"
android:layout_height="wrap_content"
android: padding=" 28dip"
android: layout_toRightOf =" @+id/Apple"
android:layout_marginLeft="15dip"
android:layout_marginRight="10dip"
android:layout_alignParentTop= "true" />
</RelativeLayout>
Layout Control Attributes
The attributes used to set the location of the control relative to a
container are

android: layout_alignParentTop—The top of the control is set to align with the top of
the container.
android: layout_alignParentBottom—The bottom of the control is set to align with the
bottom of the container.
android: layout_alignParentLeft—The left Side of the control is Set to align with the
left side of the container.
android:layout_alignParentRight—The right side of the control is set to align with the
right side of the container.
android :layout_centerHorizontal—The control is placed horizontally at the center of
the container.
android:layout _centervertical— The control is placed vertically at the center of the
container.
android: layout_centerinParent— The control is placed horizontally and vertically at
the center of the container.
The attributes to control the position of a control in relation to other
controls are
android :layout_above— The control is placed above the referenced control.
android :layout_below— The control is placed below the referenced control.
android: layout_toLeftOf— The control is placed to the left of the referenced
control.
android :layout_toRightOf—The control is placed to the right of the referenced
control.

The attributes that control the alignment of a control in relation to other controls
are
android: layout_alignTop— The top of the control is set to align with the top of
the referenced control.
android: layout_alignBottom—The bottom of the control is set to align with the
bottom of the referenced control.
android: layout_alignLeft—The left side of the control is set to align with the left
side of the referenced control.
android:layout_alignRight—The right side of the control is set to align with the
right side of the referenced control.
android: layout_alignBaseline—The baseline of the two controls will be aligned.
For spacing, Android defines two attributes:
android:layout_margin and android:padding.

The android:layout_margin attribute defines spacing for the container, while


android:padding defines the spacing for the view.

Let's begin with padding.


android:padding— Defines the spacing of the content on all four sides of the
control. To define padding for each side individually, use android:paddingLeft,
android:paddingRight, android:paddingTop, and android:paddingBottom.

android :paddingTop—Defines the spacing between the content and the top of the
control.
android:paddingBottom—Defines the spacing between the content and the bottom
of the control.
android: paddingLeft—Defines the spacing between the content and the left side of
the control.
android :paddingRight—Defines the spacing between the content and the right side
of the control.
Here are the attributes that define the spacing between the control and the
container:
android:layout_margin—Defines the spacing of the control in relation to the
controls or the container on all four sides. To define spacing for each side individually,
use the
android:layout_marginLeft,android:layout_marginRight,android:layout_marginTop,and
android:layout_marginBottom options.

android :layout_marginTop— Defines the spacing between the top of the control
and the related control or container.
android: layout_marginBottom—Defines the spacing between the bottom of the
control and the related control or container.
android :layout_marginRight— Defines the spacing between the right side of the
control and the related control or container.
android: layout _marginLeft— Defines the spacing between the left side of the
control and the related control or container.
IV. AbsoluteLayout

Each child in an AbsoluteLayout is given a specific location within the


bounds of the container.
Such fixed locations make AbsoluteLayout incompatible with devices of
different screen size and resolution.
The controls in AbsoluteLayout are laid out by specifying their exact X
and Y positions.
The coordinate 0,0 is the origin and is located at the top-left corner of
the screen.
The AbsoluteLayout class is not used often, as it is not compatible with
Android phones of different screen sizes and resolutions.
V. Using ImageView
An imageview control is used to display images in Android applications. An
image can be displayed by assigning it to the imageview control and including
the android: src attribute in the XML definition of the control. Images can also
be dynamically assigned to the ImageView control through Java code.
A sample ImageView tag when used in the layout file is shown here:
<lmageView
android:id=“@+id/first_image"
android:src = "@drawable/bintupic"
android:layout_width="wrap_content"
android: layout_height= "wrap_content ”
android: scaleType="fitXY"
android: adjustViewBounds=“true"
android: maxHeight=“100dip"
android:maxWidth=“250dip"
android:minHeight="100dip"
android: minWidth=“250dip"
android:resizeMode="horizontal|vertical" />
android:src—Used to assign the image from drawable resources. You do not
need to specify the image file extension. JPG and GIF files are supported, but
the preferred image format is PNG(Portable Network Graphics(Bit Mapped
Images)).

android:scaleType—Used to scale an image to fit its container. The valid


values for this attribute include fitXY, center, centerlnside, and fitCenter. The
value fitXY independently scales the image around the X and Y axes without
maintaining the aspect ratio to match the size of container.

Android:adjustViewBounds—If set to true, the attribute adjusts the bounds


of the imageview control to maintain the aspect ratio of the image displayed
through it.

android:resizeMode—The resizeMode attribute is used to make a control


resizable so we can resize it horizontally, vertically, or around both axes. The
available values for the resizeMode attribute include horizontal, vertical, and
none.
VI. FrameLayout
FrameLayout is used to display a single view. The view added to a FrameLayout
is placed at the top-left edge of the layout. Any other view added to the
FrameLayout overlaps the previous view; that is, each view stacks on top of the
previous one.
To display images in Android applications, the image is first copied into the
res/drawable folder and from there, it is referred to in the layout and other
XML files.

There are four types of drawable folders: drawable-xhdpi, drawable-hdpi,


/res/drawable-mdpi, and /res/drawable-ldpi. We have to place images of
different resolutions and sizes in these folders. The graphics with the
resolutions 320dpi, 240dpi, 160 dpi, and 120dpi (96 X 96 px, 72 x 72 px, 48 X 48
px, and 36 X 36 px), are stored in the res/drawable-xhdpi, res/drawable-hdpi,
res/drawable-mdpi, and res/ drawable-ldpi folders, respectively. The
application picks up the appropriate graphic from the correct folder.
VII. TableLayout
The TableLayout is used for arranging the enclosed controls into rows and
columns. Each new row in the TableLayout is defined through a TableRow
object. A row can have zero or more controls, where each control is called a
cell. The number of columns in a TableLayout is determined by the maximum
number of cells in any row. The width of a column is equal to the widest cell in
that column.
Operations Applicable to TableLayout
We can perform several operations on TableLayout columns, including
stretching, shrinking, collapsing, and spanning columns. TableLayout does not
display border lines for rows, columns, or cells.
Stretching Columns
Examples:
android: stretchcolumns=“1"—The second column (because the column
numbers are zero-based) is stretched to take up any available space in the row.
android:stretchcolumns=“0,1"—Both the first and second columns are
stretched to take up the available space in the row.
android:stretchcolumns="*"—All columns are stretched to take up the
available space.
Shrinking Columns
We can shrink or reduce the width of the column(s) using the
android:shrinkcolumns attribute in the TableLayout.
Examples:
android:shrinkcolumns="0"—The first column's width shrinks or reduces by
word- wrapping its content.
android:shrinkcolumns=“*"—The content of all columns is word-wrapped to
shrink their widths.
Collapsing Columns
android:collapseColumns="0"—The first column appears collapsed; that is, it is
part of the table but is invisible. It can be made visible through coding by using
the setColumnCollapsed() method.
Spanning Columns
We can make a column span or take up the space of one or more columns by
using the android:layout_span attribute. The value assigned to this attribute
must be >=1.
Example: android:layout_span="2"
VIII. GridLayout
GridLayout lays out views in a two-dimensional grid pattern, that is, in a series
of rows and columns. The intersection of row and column is known as a grid
cell, and it is the place where child views are placed.
It is easier to use GridLayout when compared to TableLayout. Without
specifying intermediate views, we can flexibly place the views randomly in the
grid by specifying their row and column positions. More than one view can be
placed in a grid cell. Besides this, views can span multiple grid cells too.
No need to specify layout_height and layout_width for the GridLayout child
views as they default to WRAPCONTENT.

Specifying Row and Column Position


android: layout_row="0"
android: layout_column=“0“
When either or both of the preceding attributes are not specified, GridLayout
uses the next grid cell by default for placing the view.
Spanning Rows and Columns
android: layout_rowSpan="2"
android: layout_columnSpan=“3“

Inserting Spaces in the GridLayout


For inserting spaces, a spacing view called Space is used. That is, to insert
spaces, the Space view is inserted as a child view.
<Space
android:layout_row=“1"
android:layout_column="0"
android:layout_width="5Odp"
android:layout_height="lOdp" />
Similarly, the following statements insert a space at the third row in the
GridLayout that spans three columns:
<Space
android: layout_row=“3”
android:layout_column="0"
android:layout_columnSpan="3"
android:layout_gravity="fill" />
IX. Adapting to Screen Orientation
As with almost all smart phones, Android supports two screen orientations:
portrait and landscape. When the screen orientation of an Android device is
changed, the current activity being displayed is destroyed and recreated
automatically to redraw its content in the new orientation. In other words, the
onCreate () method of the activity is fired whenever there is a change in screen
orientation.

Portrait mode is longer in height and smaller in width, whereas landscape


mode is wider but smaller in height. Being wider, landscape mode has more
empty space on the right side of the screen. At the same time, some of the
controls don't appear because of the smaller height. Thus, controls need to be
laid out differently in the two screen orientations because of the difference in
the height and width of the two orientations.
There are two ways to handle changes in screen orientation:

Anchoring controls—Set the controls to appear at the places relative to the


four edges of the screen. When the screen orientation changes, the controls
do not disappear but are rearranged relative to the four edges.
For anchoring controls relative to the four edges of the screen, use a Relative
Layout container.
To switch between portrait mode and landscape mode on the device emulator,
press the ctrl+F11 keys.

Defining layout for each mode—A new layout file is defined for each of the
two screen orientations. One has the controls arranged to suit the Portrait
mode, and the other has the controls arranged to suit the Landscape mode.
In this method, define two layouts. One arranges the controls in the default
portrait mode, and the other arranges the controls in landscape mode.
MOBILE APPLICATION DEVELOPMENT
(Common to CSE, CSE-AI, AIML, CSE-IOT)
Course Code 21A050422
By
CH VENKATESWARLU
UNIT-III UTILIZING RESOURCES AND MEDIA
Resources include text data, bitmaps, audio, videos, and other items used by the Android
application. Most commonly resources are kept separately in XML files and accessed in Java
code through the IDs assigned to them.

Resources
Types of Resources
Values Resources
Dimension Resources
Color Resources
Styles and Themes
Arrays, String Arrays, and Integer Arrays
Drawable Resources
The Toggle Button
Creating an Image Switcher Application
Scrolling Through ScrollView
Playing Audio
Playing Video
Displaying Progress with ProgressBar
Using Assets
I. Resources
Resources in Android refer to the external files that hold the information, such
as strings, images, layouts, and audio, to be supplied to an Android application.
Because resources are external, we can maintain and modify them whenever
we want without disturbing the code.
For example, the strings resource keeps the strings used in an Android
application.

Resources are broadly divided into three categories—values, drawable, and


layout—and are stored in the res folder of our project hierarchy.

The values resources in turn represent resources such as strings, colors,


dimensions, styles, and string or integer arrays.

All resource types have a respective subfolder in the res folder.

The ADT Wizard automatically creates a res folder that contains subfolders for
the values, drawable, and layout resources.
II. Types of Resources
drawable folder—Depending on the target platform chosen, our application
can have either a single directory, drawable, or four directories, drawable-ldpi,
drawable-mdpi, drawable-hdpi, and drawable-xhdpi, where we can store the
images used in our application.

•If our application has a single directory, drawable, then the images to be used
in our application, regardless of resolution, are stored in it. If our application
has four directories, then the images with different screen resolutions are
stored in the respective directories.
That is, the images of low, medium, high, and extra high resolutions are stored
in the drawable-ldpi, drawable-mdpi, drawable- hdpi, and drawable-xhdpi
directories, respectively. Android chooses the image(s) from the respective
directory, depending on the density of the device used to run the application.

layout folder—This folder contains a layout file automatically created for us.
The default name assigned to this file is activity_main.xml, but we can assign
any name to it.
menu folder—This folder contains XML file(s) that represent application menus.
values folder—This folder by default contains a strings.xml file that we can use to
define values resources that include strings, colors, dimensions, styles, and string or
integer arrays.
The following is a list of some XML files that we can create in the values folder:
arrays .xml—For defining arrays resources.
colors .xml—For defining color resources that define color values.
dimens .xml—For defining dimension resources to standardize certain application
measurements.
strings. xml—For defining string resources.
styles .xml—For defining styles resources to format or change the appearance of our
views and application.
There are many Android devices with different Android versions, and managing
themes across them is a critical task.
values-v11—The folder contains the styles .xml file that declares the holographic
theme, which is used when the application runs on Android 3.0 (API Level 11) or
higher.
values-v14—The folder contains the styles .xml file that declares the Device Default
theme, which is used when the application runs on Android 4.0 (API Level 14) or
higher.
Supported Subdirectories of the res Folder
Subdirectory Name Stores
anim Files that define animations.
color XML files that define a list of colors.
drawable-xhdpi Extra high resolution images. The xhdpi stands for extra high dots
per inch.
drawable-hdpi High-resolution images. The hdpi stands for high dots per inch.
drawable -ldpi Low-resolution images. The ldpi stands for low dots per inch.
drawable-mdpi Medium-resolution images. The mdpi qualifier stands for medium
dots per inch.
menu XML files that represent application menus.
raw Non-XML data such as audio files.
xml Additional XML files used in our application.
libs Reference libraries.

On compilation, an R class file is created that contains references to all the resources created
and hence enables us to reference them in the Java code. For each of the resource types, the R
class contains static subclasses for string, drawable, and layout resource types. The subclasses
created are R.string, R.drawable, and R.layout, respec­tively. Through these subclasses, access
their associated resources in Java code.
NOTE: Don't edit the R. java file, as it is regenerated every time something gets changed, added,
or deleted in the /res/* subdirectory.
III. Creating Values Resources
The resources in the values directory include different types, such as strings, colors,
dimensions, and string or integer arrays.
All the values are stored in XML files in the res/values folder. The filename can be
anything, but most commonly, the string resources file is named strings .xml.

Remember, the resource file names should contain only lowercase letters, numbers,
period (.), and underscore (_) symbols.

Default Code in the strings.xml File


<resources>
<string name="app_name”>ValuesResourcesApp</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name=“title_activity_values_resources_app">
ValuesResourcesAppActivity</string>
</resources>
Code Written in the strings.xml File
<resources>
<string name="app_name">ValuesResourcesApp</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_values_resources_app" >ValuesResourcesAppActivity</string>
<string name="str_name">XYZ Restaurant</string>
<string name="str_address">ll, Hill View Street, New York</string>
<string name="str_message" ><b>Welcome</b></string>
</resources>
The string resources file has a root element, <resources>, followed by one or more child
elements, <string>. Each <string> element represents one string resource. Besides the text for
the string resource, it contains a name property used to assign a unique resource ID to the
string.
Use the string resources of the preceding XML file in other resource files by using the following
syntax:
@string/resource_ID
For example, @string/str_address
All the string resources mentioned in the preceding string resource file will be compiled and
placed in the R. java file. In the Java code, we can access the resources from the R. java file,
using the following syntax:
R.string.resource_ID
R. string.str_name
There is no need to add any prefix while accessing any control from the layout.
The resource ID is enough. The syntax is R.id.resource_ID
The getString() method and pass the resource ID of the concerned string resource to access it in
Java code.
getString(R.string.str_address);

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


android: orientation="vertical"
android: layout_width= "match_parent“
android: layout_height= "match_parent" >
<TextView
android:id="@+id/name_view"
android: layout_width- "match_parent"
android:layout_height="wrap_content"
android:text=“@string/str_name" />
<TextView
android:id="@+id/address_view"
android:layout_width="match_parent"
android: layout_height=" wrap_content" />
<Textview
android: id="@+id/message_view"
android: layout_width="match_parent"
android: layout__height="wrap_content"
android:text=“@string/str_message" />
</LinearLayout >
package com.androidunleashed.valuesresourcesapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Textview;
public class ValuesResourcesAppActivity extends Activity
{ @Override
public void onCreate(Bundle savedlnstanceState)
{ super.onCreate(savedlnstanceState);
setContentView(R.layout.activity_values_resources_app);
String strAddress=getString(R.string.str_address);
Textview addressView=(Textview)findViewByld(R.id.address_view);
addressView.setText(strAddress);
}
}
FIGURE 4.2 The three Textviews displaying the text assigned to them via String resource and Java
code
IV. Dimension Resources
Dimension resources are used for standardizing certain application measurements. These
resources can be used to specify the sizes for fonts, layouts, and widgets. Also, we can modify
the size of any control in the application without changing the code.
Code Written in the dimens.xml File
<?xml version="l.0" encoding="utf-8"?>
<resources>
<dimen name=" small_size" > 15dp< /dimen>
<dimen name="medium_size">15 sp</dimen>
<dimen name=" large_size”>20pt</dimen> </resources>
We can use any of the following units of measurement:
px—Pixels
in—Inches
mm—Millimeters
pt—Points
dp—Density-independent pixels based on a 160-dpi (pixel density per inch) screen
sp—Scale-independent pixels
<LinearLayout xmlns :android= "http: //schemas . android, com/apk/res/android"
android:orientation= "vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id=“@+id/name_view"
android:layout_width= "match_parent“
android:layout_height="wrap_content"
android:text="@string/str_name"
android:textSize="@dimen/small_size" />
<TextView
android:id="@+id/address_view"
andro id:layout_width= "match_pa rent"
android:layout_height ="wrapcontent" />
<TextView
android: id=“@+id/message_view "
android: layout_width= "match_parent"
android:layout_height="wrap_content"
android: text = “@string/str_message"
android:textSize =“@dimen/large_size" />
</LinearLayout>
To apply the dimension resource medium size to our Textview address_view, add these statements to
the Java file ValuesResourcesAppActivity. java:
float addressSize= this.getResources().getDimension(R.dimen.medium_size);
addressview.setTextSize(addressSize);
V. Color Resources
To define a color resource, use the color element. The color value is specified
in the form of hexadecimal RGB values preceded by an optional Alpha channel.
The Alpha channel represents the transparency. We can specify the color
either through single-character hex values or double-character hex values
formats, as shown here:
#RGB—For example, #F00 for a Red color.
#RRGGBB—For example, #FF0000 for a Red color
#ARGB—For example, #5F00 for a Red color with an Alpha of 5.
#AARRGGBB—For example, #50FF0000 for a Red color with an Alpha of 50.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="red_color">#F00</color>
<color name="green_color">#00FF00</color>
<color name="blue_alpha_color">#500000FF</color>
</resources>
<LinearLayout xmlns:android=http://schemas.android.com/apk/res/android
android:orientation="vertical"
android:layout_width="match_parent"
android: layout_height= "match_parent ” >
<TextView
android:id="@+id/name_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_name"
android:textS i ze="@dimen/small_s i ze"
android:textColor="@color/red_color"/>
<TextView
android:id="@+id/address_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/message_view"
android:layout_width="match_parent"
android:layout_height=“wrap_content"
android:text="@string/str_message"
android:textSize="@dimen/large_size"
android:textColor="@color/blue_alpha_color"/>
</LinearLayout >
import android.app.Activity;
import android.os.Bundle;
import android.widget.Text View;
public class VaiuesResourcesAppActivity extends Activity {
@0verride
public void onCreate(Bundle savedlnstanceState) {
super.onCreate(savedlnstanceState);
setContentView(R.layout.activity_values_resources_app);
String strAddress=getString(R.string.str_address);
Textview addressview=(Textview)findViewByld(R.id.address_view);
addressView.setText(strAddress);
float addressSize= this.getResources().getDimension(R.dimen.medium_size);
addressView.setTextSize(addressSize);
int addressColor=this.getResources().getColor(R.color.green_color);
addressView.setTextcolor(addressColor);
}
}
VI. Styles and Themes
A style is a collection of attributes such as color, font, margin, and padding that can
apply collectively to views, Activity, or an entire application. That is, instead of applying
attributes individually to the components of an application.

A style is created by using a style element with one or more item child elements. The
style element includes a name property to specify the resource ID.

An item element defines an attribute and its value shown in this syntax:
<resources>
<style name="resource_ID">
<item name="attribute_name">value </item>
</style>
</resources>

Styles support inheritance; that is, the attributes of any existing style can be accessed
and included in the current style by using the parent property of the style element.
For example:
<style name="style2" parent="style1" >
The Code Written in the styles.xml File
<resources>
<style name="AppTheme" parent="android:Theme.Light" />
<style name="style 1”>
<item name="android:textColor">#00FF00 </item>
<item name="android:typeface">serif</item>
<item name="android:textSize">30sp </item> </style>
<style name="style2" parent="style 1" >
<item name="android: textColor">#0000FF</item>
<item name="android:typeface">sans</item>
<item name="android:background" >#FFOOOO</item>
<item name="android:padding">10dip</item> </style>
<style name="style3" parent="style2" >
<item name= "android:textColor">#00FF00</items>
<item name=" android:background" >#00000000</item>
<item name="android:typeface">monospace</item>
<item name= "android:gravity">center</item>
</style>
</resources>
The Layout File activity_values_resources_app.xml on Applying Styles to
Textview Controls
<LinearLayout xmlns:android= "http://schemas .android, com/apk/res/android"
android: orientation=" vertical"
android: layout_width= "match_parent"
android: layout_height="match_parent" >
<TextView
android: id=“@+ id/name_view"
style="@style/style1"
android:layout_width= "match_parent"
android:layout_height="wrap_content"
android:text="@string/str_name" / >
<TextView
android:id="@+id/address_view"
style= “@style/style2"
android:layout_width= "match_parent"
android:layout_height= "wrap_content"
android:text="@string/str_address" />
<TextView
android:id= “@+id/message_view"
style="@style/style3"
android:layout_width= "match_parent"
android:layout_height="wrap_content"
android:text="@string/str_message" />
</LinearLayout>
Applying Themes
Apply the style element to an entire Activity or application by adding the android: theme
attribute to the Android manifest. For example, after add the android: theme attribute to the
<activity> element in the Android manifest, all the attributes of the style are applied to every
view within the Activity.
Let's apply style3, which defined in the styles.xml file, to the entire application by modifying the
android: theme attribute in AndroidManifest .xml file
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidunleashed.valuesresourcesapp"
android:versionCode="1" android:versionName=“1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
andro id:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/style3” >
<activity
android:name=".VaiuesResourcesAppActivity"
android:labels"@string/title_activity_values_resources_app" >
<intent-filter>
<action android:name= "android. intent .action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filters>
</activity> </application> </manifest>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android: orientation= "vertical"
android:layout_width="match_parent"
android: layout_he ight=" ma tch_paren t” >
<TextView
android: id="@+id/name_view"
android:layout_width="match_parent"
android:layout_height= "wrap_content"
android:text =“@string/str_name” />
<TextView
android:id="@+id/address_view"
android:layout_width="match_parent"
android:layout_he ight="wrap_content"
android:text="@string/str_address" />
<TextView
android:id="@+id/message_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android: text="@string/str_message" />
</LinearLayout>

After the application is run, we find that the content of all three views appears in monospace
font, green foreground color, black background color, 30sp in size, and the text appears at the
center of the container.
VII. Arrays
Arrays refer to a collection of values or elements. Any element in an array can be referenced
directly by specifying its index/subscription value. Arrays are considered to be one of the most
flexible data sources for an application. Arrays can be in the form of strings or integers and are
used for storing the data of their respective data type.
Using String Arrays
The string array provides an array of strings. Such a resource is popularly used with selection
widgets such as ListView and spinner that need to display a collection of selectable items to the
user. To define a string array, we use the following syntax:
<string-array name="array_name">
<item>text1</item>
<item>text2</item>
...
...
</string-array>
The name property acts as the resource ID and text1, text2, and so on represent the elements of
the string. The syntax for defining an integer array is shown here:
<integer-array name="array_name">
<item>number1</item>
<item>number2</item>
...
...

</integer-array>
Code in the strings.xml File on Adding a String Array
<resources>
< string name ="app_name"> StringArrayApp</string >
<string name="menu_settings">Settings</string>
<string name="title_activity_string_array_app">StringArrayAppActivity</string>
<string-array name="fruits”>
<item>Apple</item>
<item>Mango</item>
<item>Orange</item>
<item>Grapes</item>
<item>Banana</item>
</string-array>
</resources>
Code in the Layout File activity_string_array_app.xml on Adding the TextView Control
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/fruits_view"
android:layout_width="match_parent“
android:layout_height="wrap_content" />
</LinearLayout>
Code Written in the Java Activity File stringArrayAppActivity. java
package com.androidunieashed.stringarrayapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Textview;
public class StringArrayAppActivity extends Activity
{ @Override
public void onCreate(Bundle savedlnstanceState)
{
super.onCreate(savedlnstanceState);
setContentView(R.layout.activity_string_array_app);
Textview fruitsView = (Textview)findViewByld(R.id.fruits_view);
String [] fruitsArray = getResources().getStringArray(R.array.fruits);
String str = "";
for(int i = 0; i < fruitsArray.length; i++)
{ str += fruitsArray[i] + "\n";
}
fruitsView.setText(str);
}
}
Using Integer Arrays
Creating an integer array is similar to creating a string array; the only difference is that
the tag string-array, which we used for creating the string array, is replaced by integer-
array.
The strings.xml File on Defining an Integer Array
<resources>
<string name="app_name">StringArrayApp</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_string_array_app">StringArrayAppActivity</string>
<integer-array name="OddNumbers">
<item>1</item>
<item>3</item>
<item>5</item>
<item>7</item>
<item>9</item>
</integer-array>
</resources>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/oddnums_view"
android:layout_width="match_parent"
android: layout_height= "wrap_content” />
</LinearLayout>
import android.app.Activity;
import android.os.Bundle;
import android.widget.Textview;
public class StringArrayAppActivity extends Activity
{ @Override
public void onCreate(Bundle savedlnstanceState)
{ super.onCreate(savedlnstanceState);
setContentView(R.layout.activity_string_array_app);
Textview oddNumsView = (Textview)findViewByld(R.id.oddnums_view);
int[] oddNumsArray = getResources().getlntArray(R.array.OddNumbers);
String str = "";
for(int i = 0; i < oddNumsArray.length; i++)
{ str += oddNumsArray[i] + "\n“;
}
oddNumsView.setText(str);} }
VIII. Using Drawable Resources
When it comes to displaying images, Android supports three common image formats:
PNG, JPG, and GIF. The images for the Android application are stored in the directory
res/drawable. Depending on the target platform chosen while creating a new
application, ADT either creates a single directory, res/drawable, or several: drawable-
ldpi, drawable- mdpi, drawable-hdpi, and drawable-xhdpi. Each directory is meant for
storing images of different screen resolutions.

Remember, all image file names should be lowercase and contain only letters,
numbers, and underscores. After add images to the res/drawable folders, the gen
folder is regenerated where the R. java file resides. The R. java file includes a reference
to the newly added image and hence can be used in the layout file or other Java code.
The syntax for referencing the image in the layout file is
@drawable/image_filename
In Java code, the image can be referenced using the following syntax:
R. drawable. image_filename
Remember, the image file name in the syntax shown refers to the base name of the
file, that is, the file name without the extension.
To display the image, let's add an imageview control to the layout file. Write the code in the layout file
<LinearLayout xmlns :android="http://schemas .android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/image_toview"
android:src="@drawable/bintupic"
android:layout_width="match_parent"
android: layout_height="match_parent" / >
</LinearLayout>
Also specify the image for the image view control through Java code. To try this, let's remove the reference
to the bintupic image in the imageview control that made through the src attribute:

package com.androidunleashed.dispimageapp;
import android.app.Activity;
import android.os.Bundle;
import android. widget. ImageView;
public class DispimageAppActivity extends Activity
{ @Override
public void onCreate(Bundle savedlnstanceState)
{ super.onCreate(savedlnstanceState);
setContentView(R.layout.activity_disp_image_app);
ImageView image = (ImageView) findViewByld(R.id.image_toview);
Image.setlmageResource (R.drawable .bintupic) ;
}
}
IX. Switching States with Toggle Buttons
The ToggleButton toggles between the two states, something like a radio button. A ToggleButton can only be
in one state out of two mutually exclusive states, for example, on and off. To display a ToggleButton, use the
<ToggleButton> tag in the layout file. To set the text for the button, the two attributes android: textOn and
android :textOff are used. The default values for the two attributes are ON and OFF, respectively.
<ToggleButton
android:layout_width= "wrap_content"
android:layout_height="wrap_content"
android:textOn="Play"
android:textOff="Stop" />
<LinearLayout
xmlns:android=“http: //schemas. android. com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select the Play button"
android:id="@+id/response"/>
<ToggleButton
android:id="@+id/playstop_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="Play"
android:textOf f ="Stop"/>
</LinearLayout>
import android.app.Activity;
import android.os.Bundle ;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.view.View.OnClickListener;
import android.view.View;
public class ToggleButtonAppActivity extends Activity
{ @Override
public void onCreate(Bundle savedlnstanceState)
{ super.onCreate(savedlnstanceState);
setContentView(R.layout.activity_toggle_button_app);
final TextView resp =(TextView)this.findViewById(R.id.response);
final ToggleButton playStopButton =(ToggleButton)findViewById(R.id.playstop_btn);
playStopButton.setChecked(true);
playStopButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (playStopButton.isChecked() ) {
resp.setText("Stop button is toggled to Play button");
}
else { resp.setText("Play button is toggled to Stop button"); }
}
});
}
}
Also add a background image to the ToggleButton by adding the
android:background attribute to the <ToggleButton> tag in the layout file. The following
statement sets the ic_launcher.png image as the background image of the ToggleButton:
android:background="@drawable/ic_launcher“

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.view.View.OnclickListener;
import android.view.View;
public class ToggieButtonAppActivity extends Activity
{@Override
public void onCreate(Bundle savedlnstanceState)
{ super.onCreate(savedlnstanceState);
setContentView(R.layout.activity_toggle_button_app);
final TextView resp = (TextView)this.findViewByld(R.id.response);
final ToggleButton playstopbutton = (ToggleButton) findViewByld(R.id.playstop_btn);
playstopbutton.setChecked(true);
playstopbutton.setOnClickListener (new OnClickListener() { public void onClick(View v) {
if (playstopbutton. isChecked() ) {
playstopbutton.setBackgroundDrawable(getResources().getDrawable(R. drawable.play));
resp.setText("Stop button is toggled to Play button");
}
else {
playstopbutton.setBackgroundDrawable(getResources().getDrawable(R. drawable.stop));
resp.setText("Play button is toggled to Stop button");
}
} }); } }
Modify the android:textOn and android:textOff attributes in the <ToggleButton> tag Of the
layout file main.xml. We make the two attributes appear as shown here:
android:textOn="" android:textOff=""
<LinearLayout xmlns:android="http: //schemas .android.com/apk/res/android"
android:orientation= "vertical"
android:layout_width= "match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select the Play button"
android:id="@+id/response" android:gravity="center" />
<ToggleButton android:id=“@+id/playstop_btn"
android:layout_width= "wrap_content"
android:layout_he ight=“wrap_content"
android:layout_gravi ty="center"
android:textOn= " "
android:textOff=“ ”
android:background=“@drawable/play" / >
</LinearLayout>
X. Creating an Image Switcher Application
On startup, this application initially displays an image through an imageview control with a
ToggleButton at the bottom of the screen. When the ToggleButton is clicked, the image
displayed in the imageview control changes. After click the ToggleButton again, the previous
image is redisplayed in the imageview control.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientat ion= "vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="@+id/image_toview"
android:src="@drawable/bintupic"
android:layout_width="wrap_content"
android:layout_height ="wrap_content"
android:adjustViewBounds="true" />
<ToggleButton
android:id="@+id/change_image"
android:layout_widths="wrap_content"
android:layout_height= "wrap_content"
android:textOn=" Previous Image "
android:textOff="Next Image"
android:layout_gravity="center"
android:layout_marginTop=“ 10dip” />
</LinearLayout>
import android.app.Activity;
import android.os.Bundle;
import android.widget.Imageview ;
import android.widget.ToggleButton;
import android.view.View;
import android.view.View.OnClickListener;
public class DispimageAppActivity extends Activity {
@Override
public void onCreate(Bundle savedlnstanceState) {
super.onCreate(savedlnstanceState);
setContentView(R.layout.activity_disp_image_app);
final Imageview image = (Imageview) findViewById(R.id.image_toview);
final ToggleButton changeButton= (ToggleButton) findViewById(R. id.change_image) ;
changeButton.setOnClickListener(new OnClickListener()){
public void onClick(View v){
if (changeButton.isChecked()) {
image.setlmageResource(R.drawable.bintupic2);
}
else {
image.setlmageResource(R.drawable.bintupic);
}
}
});
}
}
XI Scrolling Through Scrollview
A scrollview is a special type of control that sets up a vertical scrollbar in a view container. This
control is used when try to display views that are too long to be accommodated in a single
screen. The scrollview can have only one child view, so usually a view container layout is used as
a child, which in turn contains other child controls that want to scroll through. All the child
controls in the layout have one continuous scrollbar.

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android: id="@+id/scrollwid"
android: layout_width= "match_parent"
android: layout_height = "match_parent"
android:fillViewport="true"
android:orientation="vertical" >
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns: tool s=" http: / / schemas. android. com/tool s"
android:layout_width="match_parent"
android: layout_height= "match_parent"
android:orientation= "vertical" >
<ImageView
android:id="@+id/image_toview"
android: src= "@drawable/img1"
android:layout_width="200dip"
android:layout_height="250dip"
android:layout_gravity="center" />
<ImageView
android: id= "@+id/image_toview2”
android:src=“@drawable/img2"
android: layout_width="200dip"
android: layout_height="250dip"
android: layout_gravity= "center"
android: layout_marginTop="10dip" />
<ImageView
android:id="@+id/image_toview3"
android:src=“@drawable/img3"
android:layout_width="200dip"
android:layout_height="250dip"
android:layout_gravity="center"
android:layout_marginTop="10dip" />
</LinearLayout>
</ScrollView>
Use Of the android: fillviewport Attribute
When the size of the child control(s) is larger than the display, the Scrollview behaves naturally
by applying a scrolling effect to the child controls. However, if the size of the child control(s) is
smaller than the display, the scrollview automatically shrinks to match the size of its content and
take as much space as the size of its content. When set to true, the android:fillviewport attribute
makes the child control(s) of the scrollview expand to the size of the display.

The scrollview control is used for vertical scrolling. For horizontal scrolling, Horizontalscrollview
is used. The Horizontalscrollview acts the same as the scrollview except that it scrolls child
controls horizontally.
You shouldn't put a Listview inside a scrollview because the Listview class implements its own
scrolling and is optimized for dealing with large lists. The gestures on Listview will not be
received by Listview, but by the parent scrollview.
XII. Playing Audio
Adding Audio to the Application
The audio file that want to play must be located in the res/raw folder of our applica­tion. The
raw folder isn't created automatically, so need to create it manually. The raw folder is a special
folder that is not processed at all; hence the content of the files copied in this folder is retained.
Right-click the res folder in the Package Explorer window and select New, Folder. In the dialog
box that opens, enter the name of the new folder as raw and click the Finish button.
In the raw folder, let's copy an audio file called song1.mp3. The Java class r. java file is
automatically regenerated after the audio file is added to the application allowing us to access
it.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical”
android:layout_width="match_parent"
android:layout_height="mach_parent”>
<TextView
android:layout_width=”match_parent"
android:layout_height="wrap_content”
android:text="Playing Audio" />
<Button android:id="@+id/playbtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Play" />
</LinearLayout>
import android.app. Activity;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.media.MediaPlayer;
public class PlayAudioAppActivity extends Activity { @Override
public void onCreate(Bundle savedlnstanceState) {
super.onCreate(savedlnstanceState);
setContentView(R.layout.activity_play_audio_app);
Button playButton = (Button) findViewByld(R.id.piaybtn);
playButton.setOnClickListener(new Button.OnclickListener() {
public void onClick(View v) {
MediaPlayer mp =MediaPlayer.create(PlayAudioAppActivity.this,R.raw.song1) ;
mp.start();
}
});
}
}
Display an image on the Button control by adding the following attributes to the <Button>
element:
android:drawableTop—The image is displayed above the button text.
Example:- android: drawableTop= “@drawable/ i c_launcher “
android:drawableBottom—The image is displayed below the button text
android:drawableLeft—The image is displayed to the left of the button text
android:drawableRight—The image is displayed to the right of the button text
PlayAudioApp works fine, but it doesn't have a stop or Pause button to stop and resume playing
the audio. To switch the status of the audio from play to stop and vice versa, we replace the
Button Control With the ToggleButton Control.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android: layout_width= "match_parent ”
android:layout_height="wrap_content"
android: gravity=“center"
android:id=“@+id/response"/>
<ToggleButton android:id=“@+id/playstop_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android: textOn="Stop"
android: textOff= "Play" android:layout_gravity="center" /> </LinearLayout>
import android.app.Activity;
import android.os .Bundle ;
import android.widget.ToggleButton;
import android.view.View;
import android.widget.Textview;
import android.media.MediaPlayer;
import android.view.View.OnclickListener;
public class PlayAudioAppActivity extends Activity {
@Override
public void onCreate(Bundle savedlnstanceState) {
super.onCreate(savedlnstanceState);
setContentView(R.layout.activity_play_audio_app);
final TextView response = (TextView)this.findViewByldfR.id.response);
response.setText("Select Play button to play audio");
final MediaPlayer mp = MediaPlayer.create(PlayAudioAppActivity.this,R.raw.song1);
final ToggleButton playStopButton = (ToggleButton)findViewByld (R. id .playstop_btn) ;
playStopButton.setOnClickListener(new OnclickListener() {
public void onClick(View v) {
if (playStopButton. isChecked() ) {
response.setText("Select Stop button to stop audio");
mp.start();
}
else {
response.setText("Select Play button to play audio");
mp.pause (); } }
});
} }
XIII. Playing Video
To play video in an application, Android provides a videoview control, which, along with the
MediaController, provides several buttons for controlling video play. These buttons allow us to
play, pause, rewind, and fast-forward the video content displayed via the videoview control. To
understand the steps for playing a video, let's create a new Android project called playvideoApp.
We can play a video that is available on the Internet or one that is loaded onto an SD card of our
device or emulator.
Loading Video onto an SD Card
An emulator must be running while loading video onto an sd card. Switch on the emulator by
selecting the window, AVD Manager option. Select the demo AVD virtual device and select the
start button. Select the launch button to run the emulator. Remember only the emulator with an
sd card option should be run.
To load a video on to an sd card, follow these steps:
1. Open the DDMS perspective by selecting the window, open perspective, DDMS option.
2. In the DDMS perspective, open the file explorer by selecting window, show view, file
explorer.
3. If you can’t see the running emulator anywhere, open the devices view by selecting
window, show view, devices option. We are able to see all the running emulators, and we
can select the one that we want to use for playing the video.
4. In the file explorer view, see different folders and files in the emulator.
5. Click the button push a file onto the device. We see a dialog box for choosing a video from
disk drive. After selecting the video, select the ok button to load the selected video onto the
sd card.
We capture the VideoView control from the layout and map it to the videoView object.
Then we use a MediaController and set it the media controller of the videoView
object.

The videoview object is used for displaying video content and the button controls that
enable us to perform play, pause, rewind, or fast-forward actions on the video.
A MediaController provides these buttons. Hence the videoview's media controller is
set by calling setMediaController() to display the different button controls. Then, we
use the setVideoPath() method of the VideoView object to refer to an SD card (sdcard)
for the video.mp4 file.

We can also use setVideoURI() method to access the video from the Internet. After
setting the focus to the videoview control through requestFocus () method, we use its
start () method to start the video.

Run the application. We get the output showing a button, play video, as shown in
Figure
XIV. Displaying Progress with ProgressBar
Certain tasks, such as downloading a file, installing software, executing complex
queries, and playing audio and video, take time to execute. While executing such tasks,
we need to continually inform the user about the task progress by displaying a
progress indicator.

The ProgressBar is a control commonly used for displaying the progress of execution of
tasks. The default mode of the ProgressBar view is a circular indicator that animates
to show that a task is active but doesn't show actual progress. This icon is used when
there is no specific duration for completion of the task.
A more informative solution is a horizontal progress bar that displays an indicator
showing the amount of a task that is completed (or is left to complete). To make the
ProgressBar display in the form of a horizontal bar, set its style attribute to
@android:style/Widget.ProgressBar.Horizontal, as shown in this example:

<ProgressBar android:id="@+id/progressbar"
android:layout_width="match_parent"
android: layout_height="wrap_content"
style="@android:style/Widget.ProgressBar.Horizontal" />
The following styles can be applied to the ProgressBar:
►widget.ProgressBar.Horizontal
►Widget.ProgressBar.Small
►widget.ProgressBar.Large
►Widget.ProgressBar.Inverse
►widget.ProgressBar.Small.Inverse
►Widget.ProgressBar.Large.Inverse

The ProgressBar for Widget. ProgressBar .Horizontal, Widget. ProgressBar. Small, and widget.
ProgressBar appears as shown in Figure (left, middle, and right, respectively).
FIGURE (left) Horizontal style ProgressBar, (middle) small style ProgressBar, and (right) large style
ProgressBar

The inverse style is used when our application uses a light-colored theme, such as a white
background. The minimum value of the ProgressBar is by default 0. The maximum value of the
ProgressBar is set by the android:max attribute. For example, the following statement, when
applied to the ProgressBar control in the layout file, sets the maximum value of the ProgressBar
to 100:
android:max="100“
We can also set the maximum value of the ProgressBar through a setMax() Java method.
The following code sets the maximum value of the ProgressBar to 100:
progressBar.setMax(100);
To display progress through an indicator in the ProgressBar control, we call the setProgress()
method of the ProgressBar class, passing in an integer value to indicate the progress. For
example, the following statement sets the progress to 60, making the indicator appear at the 60
percent complete mark:
progressBar.setProgress(60);
XV. Using Assets
Besides the res/ directory, Android provides another directory, assets/, where we can
keep asset files to be included in our application.
The difference between resources and assets is that the resources are accessible in an
Android application through the resource IDs generated in the R. java file. Android
automatically generates an R. java file that contains the IDs of the resources found in
res/ folder, making it possible to access them through Java code.
Content placed in the assets/ directory is maintained in raw file format, and no IDs are
generated for these files. To read the content from the assets/ folder in an Android
application, use the AssetManager, which reads the content from the external files in
the form of a stream of bytes.

In the application that are going to create as an example, add a text file asset. The
content in the text file added to the assets folder is accessed using the AssetManager
and is displayed in a TextView.
MOBILE APPLICATION DEVELOPMENT
(Common to CSE, CSE-AI, AIML, CSE-IOT)
Course Code 21A050422
By
CH VENKATESWARLU
UNIT-IV
Using Selection Widgets and Debugging
1. Using Listview
2. Populating Listview Through String Resources and ArrayAdapters
3. Creating Listview by Extending ListActivity
4. Styling the Standard ListAdapters
5. Using the spinner Control and Populating spinner Through Resources and ArrayAdapter
6. Using AutoCompleteTextview
7. Using the Gridview Control and Its Properties
8. Using the Gridview Control and Displaying Images in Gridview
9. Creating an Image Gallery Using the viewPager Control
10. Using the Debugging Tool: Dalvik Debug Monitor Service (DDMS)
11. Debugging Applications, Placing Breakpoints in an Application, and Using Debug
Perspective
12. Adding Logging Support to Android Applications

Lists and drop-down lists are called Listview and spinner controls in Android.
I. Using Listview
A Listview is used to display a list of vertically scrolling items, allowing users to select one or more of
them. Several attributes can be used to configure this control.
Attribute Description
android:entries Used to refer to an array resource for displaying options in the Listview
android:choiceMode Used to define the number of items that are selectable from the
Listview. Valid values are none—Doesn't allow selection of any
option from the Listview
singleChoice—Allows selection of a single option from the Listview
multipleChoice—Allows selection of more than one option from
the Listview
multipleChoiceModal Used to allow selection of more than one item in a custom
selection mode
android:drawSelectorOnTop When set to true, the selector (an orange bar) is drawn
over the selected item. Otherwise, the selector is drawn behind
the selected item. The default value is false.
android: transcriptMode Used to Set the transcript mode for the list. The transcript mode
helps in deciding whether we want the list to automatically scroll
to the bottom. The valid values are
disabled—Disables the transcript mode (default value). The
Listview does not scroll automatically.
normal—The Listview automatically scrolls to the bottom when a
new item is added to the adapter and a notification is generated.
alwaysScroll—The Listview always automatically scrolls to the bottom.
A sample Listview control may appear as follows:
<ListView
android: id=“@android:id/list"
android: layout_width= "match__parent"
android:layout_height="match_parent"
android:entries="@array/fruits"
android: choiceMode=“singleChoice"
android: drawSelectorOnTop= "false"
android: transcriptMode="normal" />

This sample defines a Listview with the ID list, whose items are populated by the string
array fruits. Only one item is selectable from the Listview. No selector appears on the
top of the Listview, and it also scrolls to the bottom when a new item is added to the
data source.

For creating Listview controls, use either of the following methods:


The regular Activity base class
An activity that extends android. app. ListActivity
II.Creating a Listview with an Activity Base Class
The Listview can be populated by one of the following two methods:
By Listview through a string resource
By Listview through Adapter
Populating Listview Through String Resource
The item or option selected from the Listview is displayed via the Textview control.
Open the String resource file /res/values/strings.xml, and add a string-array structure called
fruits that lists various fruits that we want to display via the Listview control.

<resources>
<string name="app_name">ListViewApp</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_list_view_app">ListViewAppActivity</string>

<string-array name="fruits">
<item>Apple</item>
<item>Mango</item>
<item>0range</item>
<item>Grapes</item>
<item>Banana</item>
</string-array>
</resources>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation= "vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Listview android:id="@+id/fruits_list"
android:layout_width="match_parent"
android: layout_height="match_parent"
android:entries=“@array/fruits"
android:drawSelectorOnTop="false"/>
<TextView
android:id="@+id/selectedopt"
android:layout_width=" match_parent”
android:layout_height= "wrap_content" />
</LinearLayout>

To populate the Listview, the string-array fruits is assigned to the Listview through the
android entries attribute. That is, the android:entries attribute in the layout XML file is
used for populating Listview from the string resource. The android:drawSelectorOnTop
attribute is set to false, because we don't want the selector to be drawn over the
selected item.
To display the option selected from the Listview in the Textview control, we need to
access the string-array Textview and attach an event listener to the Listview to sense
for the occurrence of an event on it.
package com.androidunleashed.listviewapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Textview;
import android.widget.Listview;
import android.widget.AdapterView;
import android.widget.AdapterView.OnltemClickListener;
import android.view.View;
public class ListViewAppActivity extends Activity {
@Override
public void onCreate(Bundle savedlnstanceState) {
super.onCreate(savedlnstanceState);
setContentView(R.layout.activity_list_view_app);

final String[] fruitsArray = getResources().getStringArray(R.array.fruits);


final Textview selectedOpt=(Textview)findViewByld(R.id.selectedopt);
Listview fruitsList = (Listview)findViewById(R.id.fruits_list);
fruitsList.setOnltemClickListener(new OnltemClickListener() {
@Override
public void onltemClick(AdapterView<?> parent, View v, int position, long id)
{
selectedopt.setText("You have selected "+fruitsArray[position]);
}
});
}
}
Adapters
Android provides a framework of adapters (also known as data adapters) that are used to
provide a data source for displaying content in the form of choices in selection widgets;
that is, they help create child elements for the selection widgets.
The data source refers to the content, including elements in arrays and data in database
tables. The Adapters serve two purposes.
First, they provide the data source for a selection widget.
second, they convert individual elements of data into specific views to be displayed inside
the selection widget.
The second purpose is important, as it casts the data to suit the selection widget
environment, overriding its default behaviour, and also enables us to format the data in the
available formats. Android provides many basic Adapters such as
ListAdapter,
ArrayAdapter, and CursorAdapter.
We can also create Our Own Adapter.

Populating Listview Through the ArrayAdapter


The ArrayAdapter is one of the adapters provided by Android that provides data sources
(child elements) to selection widgets and also casts the data into specific view(s) to be
displayed inside the selection widgets.
An ArrayAdapter can be created through string resource, as well as through string arrays
defined in Java code.
<LinearLayout xmlns: android= "http: / /schemas.android.com/apk/res/android"
Xmlns:tool s="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width= "match_parent"
android:layout_height="wrap_content">
<ListView
android:id=“@+id/fruits_list"
android:layout_width="match_parent"
android :layout_height="match_parent"
android:drawSelectorOnTop="false"/>
<TextView
android:id="@+id/selectedopt"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout >

Write code into the Java activity file to serve the following purposes:
Create an ArrayAdapter through a string array and assign it to the Listview for
displaying items
Display the item selected from the Listview in the Textview
package com.androidunleashed.listviewdemo1;
import android.app.Activity;
import android.os.Bundle;
import android.widget.AdapterView.OnltemClickListener;
import android.widget.Textview;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.widget. AdapterView;
import android.view.View;

public class ListViewDemolActivity extends Activity {


@Override
public void onCreate(Bundle savedlnstanceState)
{
super.onCreate(savedlnstanceState);
setContentView(R.layout.activity_list_view_demo1);

final String[] fruits={"Apple", "Mango", "Orange", "Grapes", "Banana"};


final Textview selectedOpt=(Textview)findViewById(R.id.selectedopt);

Listview fruitsList = (Listview)findViewById(R.id.fruits_list);


final ArrayAdapter<String> arrayAdpt= new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, fruits);
fruitsList.setAdapter(arrayAdpt);
fruitsList.setOnltemClickListener(new OnltemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View v, int position,long id){
selectedopt.setText("You have selected "+fruits[position]);
}
});
}
}

An ArrayAdapter is the simplest of the adapters and acts as the data source for the
selection widgets Listview, Gridview, and so on.
An ArrayAdapter makes use of the Textview control to represent the child views in a
view.
In the above code shown, an ArrayAdapter is created through the following code:
ArrayAdapter<String> arrayadpt=new ArrayAdapter<String> (this,
android.R.layout.simple_list_item_1, fruits)
This constructor creates an ArrayAdapter called arrayAdpt that can display the
elements of the specified array, fruits, via the Textview control.
The ArrayAdapter constructor consists of the following:
this (the current context)—As the Activity is an extension of the context class, we use the
current instance as the context.
android.R.layout.simple_list_item_1—Points to a Textview defined by the Android SDK that
will be used for displaying each item in the Listview. The elements of the array that is specified
next needs to be wrapped or cast in a view before being assigned to any selection widget for
display. So, the android.R.layout. Simple_list_item_1 simply turns the strings defined in the
string array into a Textview for displaying them in a Listview.
array—The data source—an array of strings for the Listview.
III. Creating Listview by Extending ListActivity
As ListActivity automatically constructs a full-screen list for us. Also there is no need of
using the onCreate () method for defining the content view of the activity for the
simple reason that ListActivity already contains a Listview control.

<LinearLayout xmlns:android="http://schemas .android, com/apk/res/android"


xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width= "match_parent"
andro id:layout_he ight ="wrap_content">
<ListView
android:id=“@android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android :drawSelectorOnTop=" false" />
<TextView
android:id=“@+id/selectedopt"
android:layout_width= "match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
import android.os.Bundle;
import android.app.ListActivity;
import android.widget.Textview;
import android.widget.ArrayAdapter;
import android.widget.Listview;
import android.view.View;
public class ListViewDemo2Activity extends ListActivity {
String[] fruits={"Apple", "Mango", "Orange", "Grapes", "Banana"};
@Override
public void onCreate(Bundle savedlnstanceState)
{
super.onCreate(savedlnstanceState);
setContentView(R.layout.activity_list_view_demo2);
Textview selectedopt=(Textview)findViewById(R.id.selectedopt);

ArrayAdapter<String> arrayAdpt = new ArrayAdapter<String>(this,


android.R.layout.simple_list_item_single_choice,fruits); #1

getListView().setChoiceMode(Listview.CHOICE_MODE_SINGLE); #2
setListAdapter(arrayAdpt);
}
@Override
public void onListltemClick(Listview parent, View v, int position, long id)
{
super.onListltemClick(parent, v, position, id);
selectedopt.setText("You have selected "+fruits[position]);
}
}

The simple_list_item_single_choice term in Statement #1 and the ListView.


CHOICE_MODE_SINGLE in statement #2 allow us to select a single item from the Listview.

On running the application, we see that items in the Listview control appear in the form of
a RadioButton control, allowing us to select only a single item at a time. The chosen item is
displayed through the Textview control.

To enable users to select multiple items from the Listview, replace simpie_list_item_
single_choice with simple_list_item_multiple_choice in statement #1 and change the
choice mode in statement #2 from Listview.CHOICE_MODE_SINGLE to
Listview.CHOICE_MODE_MULTIPLE.
After we make these two changes, the statements appear as shown here:
ArrayAdapter<String> arrayAdpt = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice,fruits);
getListViewO.setChoiceMode(Listview.CHOICE_MODE_MULTIPLE);
IV. Using the spinner Control
The spinner is akin to a drop-down list that displays a list of items, allowing the user to select the
desired item. After the user touches a Spinner or presses the center button of the D-pad, a list
of items is displayed, allowing the user to select an item from the list. To populate the spinner
control, we use two methods: one via the string resource and the other via the ArrayAdapter
that acts as a data source.
Populating a spinner Through Resources
Define two resources, one to display a prompt in the spinner control and the other to display a
list of choices. To display a prompt in the spinner control, define a string resource.
STRINGS.XML
<resources>
<string name="app_name">SpinnerAppActivity</string>
<string name="choose_msg">Choose a fruit</string>
</resources>
Define the resource for displaying options in the Spinner Control. Use a string-array to do this.
ARRAYS.XML
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="fruits">
<item>Apple</item>
<item>Mango</item>
<item>Banana</item>
<item>Orange</item>
<item>Grapes</item>
</string-array> </resources>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:prompt="@string/choose_msg"
android:entries="@array/fruits">
</Spinner>
<TextView
android:id="@+id/selectedopt"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>

The prompt attribute is a string that appears at the top of the spinner control to guide the user.
The choose msg string resource, representing the string choose a fruit is set to appear as a
spinner control prompt.
The entries attribute is used to specify the data source to populate the spinner control.
We set the entries attribute to the string array fruits that we just defined in arrays.xml.

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Spinner;
import android.widget.AdapterView;
import android.view.View;
import android.widget.AdapterView.OnItemSelectedListener;

public class SpinnerAppActivity extends AppCompatActivity {


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

final TextView selectedOpt=(TextView)findViewById(R.id.selectedopt);


Spinner spin=(Spinner)findViewById(R.id.spinner);

final String[] fruitsArray = getResources().getStringArray(R.array.fruits);


spin.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id)
{
selectedOpt.setText("You have selected " + fruitsArray[position]);
}
@Override
public void onNothingSelected(AdapterView<?> parent)
{
selectedOpt.setText(" ");
}
});
}
}

The onNothingSelected () method is implemented to make the selectedOpt Textview


blank; that is, it removes any previous message being displayed through Textview
control that was selected earlier from the spinner control.
V. Populating a Spinner Through ArrayAdapter
Before populating the spinner control with ArrayAdapter, we make it empty by
removing the android:entries="@array/fruits" attribute from the XML definition of the
Spinner control in the layout file main.xml. After we remove the entries attribute, the
elements of the fruits string array no longer are displayed in the Spinner control. After
we remove the entries attribute from the spinner control, the layout file appears as
shown
<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:prompt="@string/choose_msg"
</Spinner>

import android.app.Activity;
import android.os.Bundle;
import android.widget.Textview;
import android.widget.Spinner;
import android.widget.ArrayAdapter;
import android.widget.AdapterView;
import android.view.View
import android.widget.AdapterView.OnltemSelectedListener;
public class SpinnerAppActivity extends Activity {
@Override
public void onCreate(Bundle savedlnstanceState) {
super.onCreate(savedlnstanceState);
setContentView(R.layout.activity_spinner_app);

final Textview selectedOpt=(Textview)findViewByld(R.id.selectedopt);


final String[] fruits={"Apple", "Mango", "Orange", "Grapes", "Banana"};
Spinner spin=(Spinner)findViewByld(R.id.spinner);
ArrayAdapter<String> arrayAdpt=new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, fruits);
spin.setAdapter(arrayAdpt);

spin.setOnltemSelectedListener(new OnltemSelectedListener()
{
public void onItemSelected(AdapterView<?:> parent, View v, int position, long id) {
selectedOpt.setText("You have selected " +fruits[position]);
}
public void onNothingSelected(AdapterView<?> parent)
{ selectedopt.setText("");
}
});
}
}
VI. AutoCompleteTextView
The AutoCompleteTextView control is an EditText control with auto-complete functionality. As
the user types, suggestions based on the entered characters appear. The user can select any of
the displayed suggestions to fill in the EditText control. To implement the auto-complete facility,
we create an ArrayAdapter and set it to display items or suggestions from a data source,
preferably an array, and wrap them in a view, called something like simple_list_item_1 or
simple_dropdown_item_1.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="Enter product name: "
android:layout_width= "match_parent”
android:layout_height="wrap_content" />
<AutoCompleteTextView
android:id="@+id/product_names"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>

To display a list of suggestions, create an ArrayAdapter and associate it with


AutoCompleteTextview.

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextview;
public class AutoCompleteAppActivity extends Activity
{ @Override
public void onCreate(Bundle savedlnstanceState)
{
String[] products ={"Camera","Handi Cam","Cell phone","Laptop","Car"};
super.onCreate(savedlnstanceState);
setContentView(R.layout.activity_auto_complete_app);

ArrayAdapter<String> arrayAdapt = new ArrayAdapter<String>(this,


android.R.layout.simple_dropdown_item_1line, products);

AutoCompleteTextview productNames = (AutoCompleteTextview)


findViewByld(R.id.product_names);
productNames.setThreshold(1);
productNames.setAdapter(arrayAdapt);
}
}
The array elements are wrapped in a simple_dropdown_item_1line View to show the
suggestions. The arrayAdapt ArrayAdapter is then associated with the AutoCompleteTextView,
using the setAdapter () method.
The setThreshold () method is used to indicate the minimum number of charac­ters that a user
must enter before the suggestions are displayed. We have set it to value 1 to display suggestions
when the user has typed even a single character.

NOTE: AutoCompleteTextView is a subclass of the EditText class.


VII. Using the Gridview Control
The Gridview control is a viewGroup used to display text and image data in the form of a
rectangular, scrollable grid. To display data in the grid, we first define a Gridview control in the
XML layout, and then bind the data that we want to be displayed to it using the ArrayAdapter.
ViewGroup is a view that contains other views known as child views. The viewGroup
class is a base class for layout managers that are used to contain and arrange several views.
Listview, Gridview, and other container controls are good examples of viewGroups.
Gridview Attributes
The number of rows displayed through Gridview is dependent on the number of elements
supplied by the attached adapter. The size and number of columns is controlled through the
following attributes:

android :numColumns—Defines the number of columns. If we supply a value, auto_ fit,


Android computes the number of columns based on available space.
android:verticalSpacing and android:horizontalSpacing—Define the amount of whitespace
between the items in the grid.
android: columnwidth—Defines the width of each column.
android :stretchMode—The attribute determines whether the column can stretch or expand
to take up the available space. The valid values for this attribute are
none—Does not allow columns to stretch or expand
columnwidth—Makes the columns take up all available space
spacingwidth—Makes the whitespace between columns take up all available space
<LinearLayout xmlns :android= "http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android: layout_width= "mateh_parent"
android:layout_height="match_parent">

<TextView android:id="@+id/selectedopt"
android:layout_width="match_parent"
android:layout_height=“wrap_content"
android:text="Select a fruit " />

<GridView android:id="@+id/grid"
android:layout_width="match_parent"
android: layout_he ight = "match_parent"
android:verticalSpacing="2dip"
android:horizontalSpacing="5dip"
android:numColumns="auto_fit"
android:columnWidth="13Odip"
android:stretchMode="columnWidth"
android:gravity="center" />

</LinearLayout >
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget .GridView;
import android.widget .ArrayAdapter;
import android.widget.AdapterView;
import android.view.View;
public class GridviewAppActivity extends Activity implements
AdapterView.OnltemClickListener
{
Textview selectedOpt;
String[] fruits={"Apple", "Mango", "Banana", "Grapes", "Orange", "Pineapple", "Strawberry",
"Papaya", "Guava", "Pomegranate", "Watermelon", "Chickoo", "Dates", "Plum", "Cherry",
"Kiwi"};
@Override
public void onCreate(Bundle savedlnstanceState);
super. onCreate (savedlnstanceState) ;
setContentView(R.layout.activity_grid__view_app) ;

selectedOpt=(Textview)findViewByld(R.id.seiectedopt);
Gridview g=(Gridview)findViewByld(R.id.grid);

ArrayAdapter<String>arrayAdpt=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,fruits);
g.setAdapter(arrayAdpt);
g.setOnltemClickListener(this);
}
public void onItemclick(AdapterView<?> parent, View v, int position, long id)
{
selectedOpt.setText("You have selected "+fruits[position]);
}
public void onNothingSelected(AdapterView<?> parent)
{
selectedopt. setText ("”);
}
}

If we reduce the size of the column width in the Gridview definition, we can accommodate more
columns. For example, modifying the attribute shown in main.xml accommodates three columns
in the Gridview:
android:columnWidth=“100dip“
VIII. Displaying Images in GridView
In this section, learn to create our own custom adapter and
subsequently use it to display images in the Gridview control.
Let's create a new application called GridimageApp.
Assuming the image filenames that want to display through the
Gridview control are prod1.png, prod2 .png, prod3 .png, prod4 .png, and
prod5.png, copy them into the res/drawable folders.
In this application there are two controls: a Textview control for
displaying the selected image number and a GridView control for
displaying images in a grid.

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height = " match_parent“
android:orientation="vertical" >
<TextView android:id="@+id/selectedopt"
android:layout_width="match_parent"
android: layout_height="wrap_content"
android:text="List of Products " />

<GridView android:id="@+id/grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:verticalSpacing="2dip"
android:horizontalSpacing="2dip"
android:numColumns= "auto_fit"
android:columnWidth=“100dip"
android:stretchMode="columnWidth"
android:gravity="center" />

</LinearLayout>
import android.app.Activity;
import android.os.Bundle;
import android.widget.Gridview;
import android.view.View;
import android.widget.ImageView;
import android.content.Context;
import android.widget.BaseAdapter;
import android.widget.AdapterView;
import android.widget.Textview;
import android.view.ViewGroup;

public class GridimageAppActivity extends Activity implements


AdapterView.OnltemClickListener {
Textview selectedopt;
@Override
public void onCreate(Bundle savedlnstanceState) {
super.onCreate(savedlnstanceState);
setContentView(R.layout.activity_grid_image_app);

selectedOpt=(Textview) findViewById(R.id.seiectedopt);
GridView g=(GridView) findViewByld(R.id.grid);
g.setAdapter(new ImageAdapter(this));
g.setOnltemClickListener(this);
}
public void onltemClick(AdapterView<?> parent, View v, int position, long id) {
int p=position+1;
selectedOpt.setText("You have selected the image number "+p);
}
public class ImageAdapter extends BaseAdapter
{
private Context contxt;
Integer[] images = { R.drawable.prod1, R.drawable.prod2, R.drawable.prod3, R.drawable.prod4,
R.drawable.prod5 };
public ImageAdapter(Context c)
{
contxt = c;
}
public int getCount()
{
return images.length;
}
public Object getltem(int position)
{
return position;
}
public long getltemld(int position)
{
return position;
}
public View getview(int position, View convertView, ViewGroup parent)
{
ImageView imageview = new ImageView(contxt);
imageview.setlmageResource(images[position]);
imageview.setLayoutParams(new Gridview.LayoutParams(100,120));
return imageview;
}
}
}
To create our custom adapter, ImageAdapter, we extend the BaseAdapter abstract
class that is provided by Android. To display the adapter's content (images) via
Gridview, ImageAdapter is set to the Gridview object, g, via the setAdapter () method.

We instantiate our imageAdapter, passing it the application context. An array called


images is defined containing the resource IDs of the images that we copied into res/
drawable folders.
The images array acts as a data source, providing the images that we want to display.
Because imageAdapter is set to the Gridview control, it can access the adapter
methods to display content. The adapter's methods getCount(), getItem(), and
getItemid () are used to determine the number of images to be displayed and the
unique identifier of the specified image.
The getView () method is used to retrieve the appropriate view, that is, the image at the
specified position. In the getView() method, the member context is used to create a new
imageview. The imageview is assigned an image from the images array that we defined earlier.
The height and width of the image are set by setting the Gridview.LayoutParams() method.
IX. Creating an Image Gallery Using the ViewPager Control
The ViewPager control (android, support.v4.view.ViewPager) helps in showing data,
which may be text, image, and so on, in the form of pages with the horizontal swiping
behaviour. That is, the pages of data being displayed can be flipped left and right.
To identify and to keep track of the pages being displayed through ViewPager, a key
object is associated with each of them.
The ViewPager needs a data adapter to define and load the data for each page. The
data adapter that is used to define the data for each page to be displayed through the
ViewPager control is the PagerAdapter (android. support. v4 . view. PagerAdapter)
class.

While implementing the PagerAdapter, must override the following methods:

instantiateltem(View container, int position)—Used for Creating and instantiating


the page and adding it to the container. Using the Layoutinf later service, the method
also inflates the appropriate layout and adds it to the specified container.
Syntax:
public Object instantiateltem(View container, int position)
container—Represents the container in which the page has to be displayed.
position—Represents the position of the page to be instantiated.
destroyItem(View container, int position,Object object)—Used for removing
the page of the specified position from the container.

isviewFromObject (view view, Object object)—Determines whether the specified


page is associated with a specific key object.

getCount ()—Defines the size of the paging range, that is, the count of the number
of the pages.

The position of the pages is zero based by default; that is, the first page to the left is in
position 0, the next page to the right is position 1, and so on.

We can also set the initial position of the pager through the setCurrentItem() method.
To listen to the change in state of the selected page, we need to define a class that
extends simpieOnPagechangeListener. When a page from the viewPager is selected,
the callback method onPageSelected() is called.

Let's apply all the knowledge gained so far in creating an application that displays a
scrol­lable image gallery, and when an image is selected from the gallery, the selected
image number is displayed. Let's name this application viewPagerApp.

The first step is to copy the images that we want to display through the gallery into the
res/drawable folders of the application. Assuming we have the files named prod1 .png,
prod2 .png, prod3 . png, prod4 .png, and prod5 .png on our local disk drive, copy them
into the res/drawable folders of our project.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vert ical" >
<TextView android:id=“@+id/selectedopt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Image Gallery”
android:gravity=“center"
android:textstyle="bold" />

<android.support.v4.view.ViewPager
android:id=“@+id/viewpager"
android:layout_widtn="match_parent"
android:layout_height="100dip"
Android:layout_marginTop=" 25dip" / >

</LinearLayout>
import android.os.Bundle;
import android.app.Activity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.PagerAdapter;
import android.widget.TextView;
import android.view.View;
import android.widget.ImageView;
import android.support.v4.view.ViewPager.SimpleOnPageChangeListener;

public class ViewPagerAppActivity extends Activity {


public Textview selectedopt;
@Override
public void onCreate(Bundle savedlnstanceState) {
super. onCreate (savedlnstanceState) ;
setContentView(R.layout.activity_view_pager_app);
selectedOpt=(Textview) findViewByld(R.id.selectedopt);

ViewPager viewPager = (ViewPager) findViewByld(R.id.viewpager);


viewPager.setAdapter(new ImageAdapter());
viewPager.setOnPageChangeListener(new PageListener());
}
public class ImageAdapter extends PagerAdapter {
Integer[] images = { R.drawable.prod1, R.drawable.prod2, R.drawable.prod3, R.drawable.prod4,
R.drawable.prod5
};
public Object instantiateItem(View container, int position)
{
ImageView view = new ImageView(ViewPagerAppActivity.this);
view.setImageResource(images[position]);
((ViewPager) container).addView(view, 0);
return view;
}
@0verride
public int getCount()
{ return images.length;
}
@Override
public void destroyItem(View arg0, int arg1, Object arg2)
{
((ViewPager) arg0).removeView((View) arg2);
}
@Override
public boolean isViewFromObject(View arg0, Object arg1)
{
return arg0 == ((View) arg1);
}
private class PageListener extends SimpleOnPageChangeListener{
public void onPageSelected(int position)
{
seiectedopt.setText("You have selected the page number "+position);
}
}
}
The Textview and ViewPager controls defined in activity_view_pager_app.xml With
the IDs selectedopt and viewpager, respectively, are fetched and mapped to the
respective objects selectedOpt and ViewPager.
We create our custom adapter, ImageAdapter, by extending the PagerAdapter class.
The ImageAdapter is set to the ViewPager object, viewPager, to display the adapter's
content—the images via the ViewPager control.
An array called images is defined, containing the resource IDs of the images that we
copied into the res/drawable folders. The images array acts as a source of images that
we want to display.

The instantiateltem(), getCount(), destroyltem(), and isViewFromObject() methods


define the pages, determine the number of images to be displayed via ViewPager, and
define the respective unique identifier of the selected image.
A setonPagechangeListener is attached to the ViewPager so that when any image is selected
from it, the onpageselected() callback method is invoked, which in turn displays the position of
the clicked image through the Textview control.
X. Using the Debugging Tool: Dalvik Debug Monitor Service (DDMS)
The DDMS is a powerful debugging tool that is downloaded as part of the Android SDK.
DDMS can be run either by selecting the DDMS icon on the top-right corner of the Eclipse
IDE or by selecting the window, open Perspective, DDMS option.

When we run DDMS, it automatically connects to the attached Android device or any
running emulator, DDMS helps with a variety of tasks, including

Finding bugs in applications running either on an emulator or on the physical device.


Providing several services such as port forwarding, on-device screen capture,
incoming call, SMS, and location data spoofing.
Showing the status of active processes, viewing the stack and heap, viewing the
status of active threads, and exploring the file system of any active emulator.
Providing the logs generated by LogCat, so we can see log messages about the state
of the application and the device. Logcat displays the line number on which the
error(s) occurred.
Simulating different types of networks, such as GPRS and EDGE.
Debug—Used to debug the selected process.

update Heap—Enables heap information of the process. After clicking this icon, use the Heap
icon on the right pane to get heap information.

Dump HPROP file—Shows the HPROF file that can be used for detecting memory leaks.

cause GC—Invokes Garbage Collection.

update Threads—Enables fetching the thread information of the selected process. After
clicking this icon, we need to click the Threads icon in the right pane to display information
about the threads that are created and destroyed in the selected process.

start Method Profiling—Used to find the number of times different methods are called in an
application and the time consumed in each of them. Click the start Method Profiling icon,
interact with the application, and click the stop Method profiling icon to obtain information
related to the different methods called in the application.

stop process—Stops the selected process.

screen Capture—Captures our device/emulator screen. If the application is running and its
output is being displayed through the device/emulator, clicking the Screen Capture icon displays
the Device Screen Capture dialog box, as shown in Figure 5.12 (left). The text, Capturing, tells us
that the output of the application or image being displayed in the device/emulator is in the
process of being captured.
Back to DDMS, on the right pane , we find the following tabs:
Threads—Displays information about the threads within each process, as shown in Figure 5.13
(left). The following information about the threads is displayed:
Thread id—Displays the unique ID assigned to each thread
status—Displays the current status of the thread—whether it is in running, sleeping, starting,
waiting, native, monitor, or zombie state
utime—Indicates the cumulative time spent executing user code
stime—Indicates the cumulative time spent executing system code
Name—Displays the name of the thread
Heap—Displays the heap information of the process (provided the update Heap button from
the Devices tab has been clicked). Select the cause GC button to begin the garbage collection
process. The object types and the size of memory allocated to them are displayed. After we
select an object type, a bar graph is displayed, showing the number of objects allocated for a
particular memory size in bytes.

Allocation Tracker—Tracks the objects allocated to an application. Click the start Tracking
button, interact with the application, and then click Get Allocations to see the list of objects
allocated to the application. After we click the Get Allocations button again, the newly allocated
objects are added to the earlier displayed list of allocated objects. We can also click the stop
Tracking button to clear the data and restart.

Network statistics—Helps us in getting information regarding network usage of our


application, that is, when our app made network requests, speed of data transfer—and other
related information.
File Explorer—Displays the file system on the device.
We can view and delete files on the device/emulator through this tab.
We can even push or pull files from the device using the two icons, Pull a file from the
device and Push a file onto the device, that are shown at the top.
To copy a file from the device, select the file in the File Explorer and click the Pull a file
from the device button. The Get Device File dialog box opens up, prompting us to
specify the path and filename where we want to store the pulled device file.
Similarly, to copy a file to the device, click the Push file onto the device button in the
File Explorer tab. The Put File on Device dialog box opens up, letting us browse the
local disk drive. Select the file we want to copy to the device and click open button to
copy it to the device.

Emulator Control
Voice
SMS
XI. Debugging Applications
The two most common ways of debugging an application and finding out what went
wrong are placing breakpoints and displaying log messages.
Placing Breakpoints in an Application
Breakpoints are used to temporarily pause the execution of the application, allowing
us to examine the content of variables and objects. To place a breakpoint in an
application, select the line of code where you want to place a breakpoint and either
press ctrl+shift+B, select Run, Toggle Breakpoint, or double-click in the marker bar to
the left of the line in the Eclipse code editor. You can place as many breakpoints as you
want in our application.
Using the Debug Perspective
Debug Pane
Expression Pane
Breakpoints Pane
Variables Pane
XII. Adding Logging Support to Android Applications
LogCat is commonly used for debugging an application. This utility is provided through the Log
class of the android.util package and displays the log messages, exceptions, warnings,
system.out.println, and intermediate results that occur during runtime. The methods in the
android.util.Log class are shown in Table 5.2.

TABLE 5.2 Methods Used in the Log Class


Method Purpose
Log.e() Log errors
Log.w() Log warnings
Log.i() Log informational messages
Log.d() Log debug messages
Log.v() Log verbose messages

These methods display log messages of different severity levels. To add logging support to our
application, add the following import statement to the Activity file for the Log class:
import android.util.Log;

The logging messages need to be tagged as follows:


Log.i("debug_tag", "Message to display");

Examples:
Log.i("InfoTag", "Program is working correctly up till here");
Log.e("ErrorTag", "Error--Some error has occurred here");
MOBILE APPLICATION DEVELOPMENT
(Common to CSE, CSE-AI, AIML, CSE-IOT)
Course Code 21A050422
By
CH VENKATESWARLU
UNIT – IV
Displaying and Fetching Information Using Dialogs and Fragments
AlertDialogs
Getting Input via Dialog Boxes
Understanding DatePickerDialogs
Understanding TimePickerDialogs
Selecting Date and Time in One Application
Understanding Fragments and Their Life Cycles
Creating Fragments Through XML and Java Code
Understanding Specialized Fragments, ListFragment, DialogFragment, and
Preference Fragment

A dialog is a smaller window that pops up to interact with the user. It can display
important messages and can even prompt for some data. Once the interaction with
the dialog is over, the dialog disappears, allowing the user to continue with the
application.
Fragments, as the name suggests, enable us to fragment or divide our Activities into
encapsulated reusable modules, each with its own user interface, making our
application suitable to different screen sizes. That is, depending on the available
screen size, we can add or remove fragments in our application.
What Are Dialogs?
When we want only a little information, or want to display an essential message, dialogs are
preferred. Dialogs are also used to guide users in providing requested information, confirming
certain actions, and displaying warnings or error messages.
The following is an outline of different dialog window types provided by the Android SDK:
Dialog— The basic class for all dialog types.
AlertDialog— A dialog with one, two, or three Button controls.
CharacterPickerDialog— A dialog that enables you to select an accented character
associated with a regular character source.
DatePickerDialog— A dialog that enables you to set and select a date with a
DatePicker control.
ProgressDialog— A dialog that displays a ProgressBar control showing the progress
of a designated operation.
TimePickerDialog— A dialog that enables you to set and select a time with a
TiraePicker control.
A dialog is created by creating an instance of the Dialog class. The Dialog class creates a dialog in
the form of a floating window containing messages and controls for user interaction. In Android,
the dialogs are called asynchronously; that is, the dialogs are displayed and the main thread that
invokes the dialogs returns and continues executing the rest of the application. The rest of the
code continues to execute in the background and also allows users to simultaneously interact
with the dialog. That means the dialogs in Android are modal in nature. If the dialog is open,
users can interact only with the options and controls in the dialog until it is closed. While the
user interacts with the dialog, the parent activity resumes its normal execution for efficiency.
Each dialog window is defined within the activity where it will be used. A dialog window can be
created once and displayed several times. It can also be updated dynamically.

The following is a list of the Activity class dialog methods:


showDialog()—Displays a dialog and creates a dialog if one does not exist. Each dialog has a
special dialog identifier that is passed to this method as a parameter.
onCreateDialog()—The callback method that executes when the dialog is created for the first
time. It returns the dialog of the specified type.
onPrepareDialog()—The callback method used for updating a dialog.
dismissDialog()— Closes the dialog whose dialog identifier is supplied to this method.
The dialog can be displayed again through the showDialog() method.
removeDialog()—The dismissDialog() method doesn't destroy a dialog. The dismissed dialog
can be redisplayed from the cache. If we do not want to display a dialog, we can remove it from
the activity dialog pool by passing its dialog identifier to the removeDialog() method.

The onCreateDialog () method is called only once while creating the dialog for the first time,
whereas the onPrepareDialog () method is called each time the showDialog() method is called,
allowing the activity to update the dialog before displaying it to the user. Basically, instead of
creating new instances of a dialog each time, onCreateDialog() and onPrepareDialog() persist
and manage dialog box instances.
By overriding the onCreateDialog method, we specify dialogs that will be created when
showDialog() is called. All the dialog windows are created by extending the Dialog class.
AlertDialog
An AlertDialog is a popular method of getting feedback from the user. This pop-up dialog
remains there until closed by the user and hence is used for showing critical messages that need
immediate attention or to get essential feedback before proceeding further.
The simplest way to construct an AlertDialog is to use the static inner class AlertDialog.Builder
that offers a series of methods to configure an AlertDialog. This example creates a new
AlertDialog.Builder Object called alertDialog:
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
In this example, this refers to the context, that is, the current activity created here. We can add a
title, icon, and message to the alertDialog object that we want to display in the dialog. We can
define buttons and controls for user interaction to display in the dialog. We can also register
event listeners with the dialog buttons for handling events.

Methods of the AlertDialog. Builder Subclass


The methods of the AlertDialog.Builder subclass that can use to configure the AlertDialog box
are
setTitle() and seticon()—For specifying the text and icon to appear in the title bar of the
dialog box.
setMessage ()—For displaying a text message in the dialog box.
setPositiveButton(),setNeutralButton(),and setNegativeButton()—
For configuring the following three buttons:
Positive button—Represents the OK button.
Negative button—Represents the cancel button.
Neutral button—Represents a button to perform a function other than OK or Cancel.
<LinearLayout xmlns :android= "http://schemas.android, com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation=“vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="match_parent"
android:layout_height=“wrap_content"
android:id="@+id/click_btn"
android:text="Click for Alert Dialog" />
</LinearLayout>
import android.app.Activity;
import android.os.Bundle;
import android, view. View .OnClickListener;
import android.widget.Button;
import android.view.View;
import android.app.AlertDialog;
import android.content.Dialoglnterface ;
public class AlertDialogAppActivity extends Activity implements OnClickListener {
@Override
public void onCreate(Bundle savedlnstanceState) {
super.onCreate(savedlnstanceState);
setContentView(R.layout.activity_alert_dialog_app);
Button b = (Button)this.findviewById(R.id.click_btn);
b.setonclickListener(this); }
@Override
public void onClick(View v) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Alert window");
alertDialog.setIcon(R.drawable.ic_launcher);
alertDialog.setMessage("This is an alert");
alertDialog.setPositiveButton("OK", new Dialoglnterface.OnclickListener() {
public void onClick(Dialoglnterface dialog, int buttonld) {
return; } });
alertDialog.show(); } }
FIGURE 6.1 Button with the caption click for Alert Dialog displayed on application startup (left),
and the AiertDiaiog appears on selecting the Button control (right)
Getting Input via the Dialog Box
We modify our current Android project AlertDialogApp to get input from the user. We make the
following changes to the application:
Dynamically create an EditText control and set it as part of the AlertDialog to prompt the user
for input.
Add a Textview control to the layout file to display the data entered by the user in
AlertDialog.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns : tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id=“@+id/click_btn"
android:text="Click for Alert Dialog"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/response"/>
</LinearLayout>
Import android.app.Activity;
Import android.os.Bundle;
Import android.view.View.OnClickListener;
Import android.widget.Button;
Import android.widget.EditText;
Import android.widget.Textview;
import android.view.View;
import android.app.AlertDialog;
import android. content. Dialoglnterface;
public class AlertDialogAppActivity extends Activity implements OnclickListener {
Textview resp;
@Override
public void onCreate(Bundle savedlnstanceState) {
super.onCreate(savedlnstanceState);
setContentView(R.layout.activity_alert_dialog_app);
resp = (Textview)this.findViewById(R.id.response);
Button b = (Button)this,£indViewById(R.id.click_btn);
b.setOnClickListener(this);
}
@Override
public void onClick(View v) (
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Alert window");
alertDialog.setlcon(R.drawable.ic_launcher);
alertDialog.setMessage("Enter your name ");
final EditText username = new EditText(this);
alertDialog.setView(username);
alertDialog.setPositiveButton("OK", new Dialoglnterface.OnclickListener()
{
public void onClick(DialogInterface dialog, int buttonld)
{
String str = username.getText().toString();
resp.setText ("Welcome "+str+ "!");
return;
}
});

alertDialog.setNegativeButton("Cancel", new Dialoglnterface.OnclickListener()


{
public void onClick(DialogInterface dialog, int buttonld)
{ return;
}
alertDialog.show();
}
}
FIGURE Getting input from the user via the AlertDialog (left), and the data entered by the user
displayed through Textview (right)
DatePickerDialog
DatePickerDialog is used to see and modify the date. Supply the day, month, and year values to
its constructor to initialize the date initially displayed through this dialog. The constructor
includes a callback listener to inform the current context when the date has been set or
changed. To initialize the current date to the dialog, use a calendar instance.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns :tools="http://schemas.android.com/tools"
android:orientat ion="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="@+id/datevw"
android:layout_width=“wrap_content"
android:layout_height="wrap_content"/>
<Button android:id=“@+id/date_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set the Date" />
</LinearLayout>
The code in the activity file does the following:
Access the system's current date through the calendar instance.
Display the current system date in the Textview control.
Display the DatePickerDialog, initialized to display the current system date when the Button
control is clicked.
Access the date set by the user in the DatePickerDialog when its Set button is clicked and
display it through the Textview control.
Import android.app.Activity;
Import android.os.Bundle;
Import android.widget.Textview;
Import android.widget.Button;
import java.util.Calendar;
import android.app.DatePickerDialog;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.DatePicker;

public class DatePickerAppActivity extends Activity {


private Textview dispDate;
private int yr, mon, dy;
@Override
public void onCreate(Bundle savedlnstanceState) {
super.onCreate (savedlnstanceState};
setContentView(R.layout.activity_date_picker_app);

dispDate = (Textview) findViewByld(R.id.datevw);


Button dateButton = (Button) findViewById(R.id.date_button);
final Calendar c = Calendar.getInstance();
yr = c.get(Calendar.YEAR);
mon = c.get(Calendar.MONTH);
dy = c.get(Calendar.DAY_OF_MONTH);
dispDate.setText("Current date is: "+(mon+1)+"-"+dy+"-"+yr);
dateButton.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
new DatePickerDialog(DatePickerAppActivity.this, dateListener, yr,mon, dy).show();
}
});
}
private DatePickerDialog.OnDateSetListener dateListener = new
DatePickerDialog.OnDateSetListener()
{
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth){
yr = year;
mon = monthOfYear;
dy = dayOfMonth;
dispDate.setText("Current date is: "+(mon+1)+"-"+dy+"-"+yr);
}
};
}
TimePickerDialog
The TimePickerDialog allows us to set or select time through the built-in Android TimePicker
view. We can set the values of hour and minute with values of hour ranging from 0 through 23
and minutes from 0 through 59.
The dialog provides a callback listener, OnTimeChangedListener or OnTimeSetListener, which
tells US when a time is changed Or set by the user.
To initialize the TimePickerDialog so it displays the current system time, we use the calendar
class. An instance of calendar class is created that is initially set to be the current system time.

The current hour and minute values are fetched from the calendar instance and passed to the
TimePickerDialog constructor to initialize it, which sets it to display current system time.
We also pass a Boolean value, true, to the constructor to indicate that we want to display the
24-hour clock and not the 12-hour clock that displays AM/PM. The constructor also includes a
callback listener to inform the current context (i.e., the current activity) when the time is set or
changed in the TimePickerDialog.
Selecting the Date and Time in One Application
To see how the system date and time can be set in an application, let's create a new Android
application and name it DateTimePickerApp. In this application, we use a Textview and two
Button controls. The Textview control displays the current system date and time, and the two
Button controls, set Date and set Time, are used to invoke the respective dialogs. When the set
Date button is selected, the DatePickerDialog is invoked, and when the set Time button is
selected, the TimePickerDialog is invoked.

<LinearLayout xmlns : android="http: //schemas. android, com/apk/res/android"


xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent”
android:layout_height="match_parent”>
<TextView android:id=“@+id/datetimevw"
android:layout_width="wrap_content"
android:layout_height="wrap_content”/>
<Button android:id=“@+id/date_button"
android:layout_width="match_parent"
android:layout_height="wrap_content”
android:text="Set Date"/>
<Button android:id=“@+id/time_button"
android:layout_width="match_parent"
android:layout_height="wrap_content”
android:text="Set Time" />
</LinearLayout>
Java activity file to perform the following tasks:
Display the current system date and time in the Textview control.
Invoke DatePickerDialog and TimePickerDialog when the Set Date and Set Time Button
controls are clicked.
Initialize DatePickerDialog and TimePickerDialog to display the current system date and time
via the calendar instance.
Display the modified date and time set by the user via the DatePickerDialog and
TimePickerDialog through the Textview control.

import android.app.Activity;
import android.os.Bundle;
import android.widget.Textview;
import android.widget.Button;
import java.util.Calendar;
import android.app.TimePickerDialog;
import android.app.DatePickerDialog;
import android.view.View.OnClickListener;
import android.view.view;
import android.widget.TimePicker;
import android.widget.DatePicker;
public class DateTimePickerAppActivity extends Activity {
private Textview dateTimeView;
private Calendar c;
private int h, m,yr,mon,dy;
@0verride
public void onCreate(Bundle savedlnstanceState) {
super.onCreate(savedlnstanceState);
setContentView(R.layout.activity_date_time_picker_app);
dateTimeView=(Textview) findViewByld(R.id.datetimevw);
Button timeButton = (Button) findViewById(R.id.time_button);
Button dateButton = (Button) findViewById(R.id.date_button);
c = Calendar.getInstance();
h = c.get(Calendar.HOUR_OF_DAY);
m = c.get(Calendar.MINUTE);
yr = c.get(Calendar.YEAR);
mon = c.get(Calendar.MONTH);
dy = c.get(Calendar.DAY_OF_MONTH);
dateTimeView.setText("Current date is "+ (mon+1)+"-"+dy+"-"+yr+" and current time is:
"+h+":"+m);
dateButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new DatePickerDialog(DateTimePickerAppActivity.this, dateListener,yr, mon, dy).show(); }
});
timeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new TimePickerDialog(DateTimePickerAppActivity.this, timeListener,h,m,true).show(); }
});
private DatePickerDialog.OnDateSetListener dateListener = new DatePickerDialog.
OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
yr = year;
mon = monthOfYear;
dy = dayOfMonth;
dateTimeView.setText("Current date is "+ (mon+1)+"-"+dy+“-”+yr+" and current time is: "+h+"
:”+m) ; } };
private TimePickerDialog.OnTimeSetListener timeListener = new TimePickerDialog.
OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hour, int minute) {
h = hour;
m = minute;
dateTimeView.setText("Current date is "+ (mon+1)+"-"+dy+"-"+yr+" and current time is:
"+h+":"+m); } };
}

The respective listeners, onDateSetListener and OnTimeSetListener, invoke their callback


methods, onDateSet () and onTimeSet(), when the Done button in the DatePickerDialog or
TimePickerDialog is selected by the user. The two callback methods access the newly set date
and time and display them through the Textview control.
We can also format the date and time. Let's modify the DateTimePickerAppActivity. java file
import android.app.Activity;
import android. os . Bundle ;
import android.widget.Textview;
import android.widget.Button;
import java.util.Calendar;
import android.app.TimePickerDiaiog;
import android.app.DatePickerDialog;
import android, view. View. OnClickListener;
import android.view.View;
import android.widget.TimePicker;
import android.widget.DatePicker;
import java.text.DateFormat;
public class DateTimePickerAppActivity extends Activity {
private Textview dateTimeView;
private Calendar c;
DateFormat DateTimeFormat = DateFormat.getDateTimeInstance();
@Override
public void onCreate(Bundle savedlnstanceState) {
super.onCreate(savedlnstanceState);
setContentView(R.layout.activity_date_time_picker_app);
dateTimeView = (Textview) findViewByld(R.id.datetimevw);
Button timeButton = (Button) findViewById(R.id.time_button);
Button dateButton = (Button) findViewByldlR.id.date_button);
c = Calendar.getlnstance();
dateTimeView.setText(DateTimeFormat.format(c.getTime()));
dateButton.setOnClickListener(new OnClickListener() {
public void onClick(view v) {
new DatePickerDialog(DateTimePickerAppActivity.this, dateListener,c.get(Calendar.YEAR),
c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)),show(); } });
timeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new TimePickerDialog(DateTimePickerAppActivity.this, timeListener,
c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE),true).show(); } });
private DatePickerDialog.OnDateSetListener dateListener = new DatePickerDialog.
OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
c.set(Calendar.YEAR,year);
c.set (Calendar.MONTH,monthOfYear);
c.set(Calendar.DAY_OF_MONTH,dayOfMonth);
dateTimeView.setText(DateTimeFormat.format(c.getTime())); } };
private TimePickerDialog.OnTimeSetListener timeListener = new
TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hour, int minute) {
c.set(Calendar.HOUR_OF_DAY, hour);
c.set(Calendar.MINUTE, minute);
dateTimeView.setText(DateTimeFormat.format(c.getTime()));
} };
}
Fragments
A Fragment is a piece of an activity which enable more modular activity design.
It will not be wrong if we say, a fragment is a kind of sub-activity.

A fragment has its own layout and its own behaviour with its own life cycle callbacks.

we can add or remove fragments in an activity while the activity is running.

We can combine multiple fragments in a single activity to build a multi-pane UI.
 A fragment can be used in multiple activities.
Fragment life cycle is closely related to the life cycle of its host activity which means when the
activity is paused, all the fragments available in the activity will also be stopped.
A fragment can implement a behaviour that has no user interface component.
 Fragments were added to the Android API in Honeycomb version of Android which API
version 11.
 Create fragments by extending Fragment class and we can insert a fragment into our
activity layout by declaring the fragment in the activity's layout file, as a <fragment> element.

 we had a limitation because ,we can show only a single activity on the screen at one given
point in time. So we were not able to divide device screen and control different parts
separately. But with the introduction of fragment we got more flexibility and removed the
limitation of having a single activity on the screen at a time.
Now we can have a single activity but each activity can comprise of multiple fragments which
will have their own layout, events and complete life cycle.
The application can embed two fragments in Activity A, when running on a tablet-sized device.

However, on a handset-sized screen, there's not enough room for both fragments, so Activity A
includes only the fragment for the list of articles, and when the user selects an article, it starts
Activity B, which includes the second fragment to read the article.
Fragment Lifecycle
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.


Create an Android project called FragmentsApp.
In this application, we are going to create two fragments: Fragment1 and Fragment2.
Fragment1 contains a selection widget, Listview, that displays a couple of fruits to choose from.
Fragment2 contains a Textview control to display the fruit selected from the Listview of
Fragment1.
The fragments use individual XML layout files to define their views, so for the two fragments,
let's add two XML files called fragment1.xml and fragment2.xml to the res/layout folder.
To define a ListView control in the first fragment, the code written in the XML file,
fragment1.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#0000FF" >

<ListView
android:id="@+id/fruits_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="false" />

</LinearLayout>
For distinguishing the two fragments, the background of this fragment is set to blue.
To define a Textview control for the second fragment, the code written in the XML file
fragment2.xml is
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
android:id="@+id/selectedopt"
android:layout_width="match_parent"
android:layout_height= "wrap_content"
android:text="Please select a fruit" />

</LinearLayout>
The code written in the Java Class file of the first fragment, FragmentlActivity.Java is
import android.app.Fragment;
import android.os.Bundle;
import android.view.ViewGroup;
import android.view.View;
import android.view.LayoutInflater;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.content.Context;
import android.widget.AdapterView ;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

public class Fragment1Activity extends Fragment {


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
Context c = getActivity().getApplicationContext ();
View vw = inflater.inflate(R.layout.fragment1, container, false);
final String[] fruits={"Apple", "Mango", "Orange", "Grapes", "Banana"};
ListView fruitsList = (ListView) vw.findViewById(R.id.fruits_list);
ArrayAdapter<String> arrayAdpt= new ArrayAdapter<String>(c,
android.R.layout.simple_list_item_1, fruits);
fruitsList.setAdapter(arrayAdpt);
fruitsList.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
TextView selectedopt = (TextView) getActivity().findViewById(R.id.selectedopt);
selectedopt.setText("You have selected "+((TextView) v).getText().toString());
}
});
return vw;
}
}
write the code in the Java class file of the second fragment Fragment2Activity .java.
import android.app.Fragment;
import android.os.Bundle;
import android.view.ViewGroup;
import android.view.View;
import android.view.LayoutInflater;

public class Fragment2Activity extends Fragment {


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
return inflater.inflate(R.layout.fragment2, container, false);
}
}
To accommodate both the fragments in the application, the code written into the layout file
activity_fragments_app.xml appears as
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation= "horizontal" >
<fragment
android:name="com.androidunleashed.fragmentsapp.Fragment1Activity"
android:id="@+id/fragment1"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height ="match_parent" />
<fragment
android:name="com. androidunleashed.fragmentsapp.Fragment2Activity"
android:id="@+id/fragment2"
android:layout_weight="0"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
</LinearLayout>
The fragments are set to refer to their respective Java class through the android: name attribute,
both the fragments appear beside each other.
We don't have to write any code into FragmentsAppActivity. Java. We can leave the default code
unchanged, as
import android.app.Activity;
import android.os.Bundle;

public class FragmentsAppActivity extends Activity{


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragments_app);
}
}
Fragments with Orientation
1) main.xml  <f1>
2) Res/layout_landmain xml with <f1>, <f2>
3) F1.xml
4) F2.xml
5) F1.javacode with orientationif(landscape)- 2 Frags else Intent(showitem.class)
6) F2.javashowitem.java
7) Android manifest.xml
8) Main.java

Fragments with Java


1) F1.xml
2) F2.xml
3) Main .xml
4) F1.java
5) Main.java
6) ShowItemActivity.java
7) Manifest.xml
Fig: In portrait mode, only the UI of the first fragment, Listview, is displayed (left), and the item
selected from the Listview is displayed via another activity (right).

Fig: In Landscape mode, the Ul of both fragments, Listview and Textview, is displayed (left), and
the item selected from the Listview is displayed via the Textview of the second fragment (right).
Creating Fragments with Java Code
We have been defining fragments statically by using < fragment > elements in the layout file of
the application. Now learn how to add fragments to the activity during runtime. For creating,
adding, and replacing fragments to an activity dynamically, we use the FragmentManager.
FragmentManager
The FragmentManager is used to manage fragments in an activity. To access the
FragmentManager, the method used is getFragmentManager() , as shown here:
FragmentManager fragmentManager = getFragmentManager();
To perform fragment transactions, we use the instance of the FragmentTransaction as shown
here:
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
A new FragmentTransaction is created using the beginTransaction() method of the
FragmentManager.
The following code shows how to add a fragment:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment1Activity fragment = new Fragment1Activity();
fragmentTransaction.add(R.id.fragment_container, fragment, "TAG1");
fragmentTransaction.commit();

Here the Fragment1Activity is the Java class of the fragment, which is also used to load the UI of
the fragment from its XML file. We assume that the fragment_container is the ID of the
container that exists in the layout file where we want to put our fragment. The TAG1 refers to
the unique ID to identify and access the fragment. The commit () method is used to apply the
changes.
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if(null==fragmentManager.findFragmentByTag(TAGl)){
Fragment1Activity fragment = new FragmentiActivity();
fragmentTransaction.add(R.id.fragment_container, fragment, "TAG1");
}
fragmentTransaction.commit(); We can see that the findFragmentByTag () method of the
FragmentManager checks to see whether any fragment with the given tag exists.

fragmentTransact.replace(R.id.fragment_container,fragment2, "TAG2");
In this statement, the views of fragment2 replace the content being displayed in the
fragment_container of the Activity layout. The following code identifies the fragment via the
findFragmentByid () method and then removes it:

FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();


Fragment fragment = fragmentManager.findFragmentByldfR.id.fragment);
fragmentTransaction.remove(fragment);
fragmentTransaction.commit() ; Here we assume that a fragment with the ID fragment exists in
the Activity. To identify the fragment through the findFragmentByTag() method, the statement
can be replaced by the following:
Fragment fragment = fragmentManager.findFragmentByTag(TAG1);
Let's create a new Android project called FragmentCodeApp. The code in fragment1.xml is the
same as above Listing. Similarly, the code written into fragment2.xml is the same as that shown
in Listing. Write the code shown in the main layout file of the application,
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height ="match_parent"
android:orientation="horizontal" >
<LinearLayout
android:id="@+id/fragmentl"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height = "match_parent" />
<LinearLayout
android:id="@+id/fragment2"
android:layout_weight=" 0"
android:layout_width="wrap_content"
android:layout_height = "match_parent" />
</LinearLayout>
To load the views defined in fragment1.xml, write the code shown in the Java class file
FragmentlActivity. java.
com.androidunleashed.fragmentcodeapp;
import android.view.View;
import android.view.LayoutInflater;
import android.app.Fragment;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.content.Context;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.content.Intent;
import android.app.FragmentManager;
public class FragmentlActivity extends Fragment{
protected static final String FRAG2 = "2";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedlnstanceState) {
Context c = getActivity().getApplicationContext() ;
View vw = inflater.inflate(R.layout.fragment1, container, false);
final String[] fruits={"Apple", "Mango", "Orange", "Grapes", "Banana"};
ListView fruitsList = (ListView) vw.findViewById(R.id.fruits_li.st);
ArrayAdapter<String> arrayAdpt= new ArrayAdapter<String>(c,
android.R.layout.simple_list_item_l, fruits);
fruitsList.setAdapter(arrayAdpt);
final FragmentManager fragmentManager = getFragmentManager();
fruitsList.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View v, int position,long id){
if(null!=fragmentManager.findFragmentByTag(FRAG2)){
TextView selectedopt = (TextView) getActivity().findViewById(R.id.selectedopt);
selectedopt.setText("You have selected "+((TextView) v) .getText().toString() );
}
else
{ Intent intent = new Intent(getActivity().getApplicationContext(),
ShowItemActivity.class);
intent.putExtra("item",((TextView) v).getText().toString());
startActivity(intent);
}
}
});
return vw;
}
}
Creating Special Fragments
After understanding the procedure to create simple fragments, we learn to create special­ized
fragments such as list fragments, dialog fragments, and preference fragments. To create these,
we extend from the following subclasses of the Fragment base class:
ListFragment
DialogFragment
PreferenceFragment

ListFragment
1) F2.xml
2) F2.java
3) F1.java(No need of F1.xml) Extends ListFragment
4) Main.xml<F1>,<F2>
5) Main.java

DialogFragment
1) F2.xml
2) F2.java
3) Main.xml<F2>,<Button>
4) F1.java(No need of F1.xml) Extends DialogFragment
5) Main.java
Using PreferenceFragment
PreferenceFragment is a fragment that enables users to configure and personalize an
application. The PreferenceFragment can contain several Preference Views that help in
uniformly setting application.

Preference View Description


PreferenceScreen The root element of the XML used to define a preference screen

checkBoxPreference Displays a simple check box that returns true when checked
otherwise returns false

ListPreference Displays a list of radio buttons allowing the user to select one

EditText Preference Displays a dialog with an EditText control allowing the user to
enter text
RingtonePreference Displays radio buttons indicating the ringtones available for
selection

PreferenceCategory Used in grouping related preferences in categories

Preference A custom preference that acts like a Button control


PreferenceFragment
1) res/xml/preferences.xml
2) Strings.xml with two arrays: fruits, fruitselected
3) PrefActivity.java
4) activity_preference_frag.xml (main xml)
5) PreferenceFragAppActivity.java (main java)
The code written into the preferences. xml file is
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

<PreferenceCategory android:title="Category 1">


<CheckBoxPreference
android:title="Pizza"
android:defaultValue="false"
android:key="Pizzakey" />
<EditTextPreference
android:key="Namekey"
android:title="Enter your name: "
android:dialogTitle="Enter your information">
</EditTextPreference>
</PreferenceCategory>

<PreferenceCategory android:title="Category 2">


<RingtonePreference
android:showDefault="true"
android:key="Audio"
android:title="Select sound"
android:ringtoneType="notification">
</RingtonePreference>
<ListPreference
android:title="Fruits List "
android:key="fruits_list"
android:entries="@array/fruits"
android:entryValues="@array/fruitselected"
android:dialogTitle="Choose a fruit">
</ListPreference>
</PreferenceCategory>
<Preference
android:title="Submit"
android:key="submitPref"/>
</PreferenceScreen>

After we define the two arrays, the strings.xml file appears as


<resources>
<string name="app_name">PreferenceFragApp</string>
<string-array name="fruits">
<item>Apple</item>
<item>Mango</item>
<item>Orange</item>
<item>Grapes</item>
<item>Banana</item>
</string-array>
<string-array name="fruitselected">
<item>You have selected Apple</item>
<item>You have selected Mango</item>
<item>You have selected Orange</item>
<item>You have selected Grapes</item>
<item>You have selected Banana</item>
</string-array>
</resources>

Write the code in Java class file PrefActivity.java as


import android.app.Activity;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceFragment;

public class PrefActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content,new
PrefsFragment()).commit();
}
public static class PrefsFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedlnstanceState) {
super.onCreate(savedlnstanceState);
addPreferencesFromResource(R.xml.preferences);
Preference submitpref = (Preference) findPreference("submitPref");
submitpref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
getActivity().finish();
return true;
}
});
}
}
}
four Textview controls in the layout file activity_preference_frag.xml.
<LinearLayout xmlns:android= "http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/pizza"/>
<TextView
android:layout_width= "match_parent"
android:layout_height="wrap_content"
android:id="@+id/name"/>
<TextView
android:layout_width= "match_parent"
android:layout_height="wrap_content"
android:id="@+id/ringtone"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/fruit"/>
</LinearLayout>
the main activity file PreferenceFragAppActivity.java.
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.preference.PreferenceManager;
import android.content.SharedPreferences;
import android.widget.TextView;

public class PreferenceFragAppActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startActivity(new Intent(this,PrefActivity.class));
}
@Override
public void onResume() {
super.onResume();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
TextView Pizza = (TextView) findViewById(R.id.pizza);
TextView Name = (TextView) findViewById(R.id.name);
TextView Ringtone = (TextView) findViewById(R.id.ringtone);
TextView Fruit = (TextView) findViewById(R.id.fruit);
if(Boolean.valueOf(prefs.getBoolean("Pizzakey",false)))
Pizza.setText("You have selected Pizza");
else
Pizza.setText("");
Ringtone.setText("The ringtone selected is " + prefs.getString("Audio","Silent"));
Name.setText("The name entered is " + prefs.getString("Namekey",""));
String selectedFruit = prefs.getString("fruits_list", "Apple");
Fruit.setText(selectedFruit);
}
}
MOBILE APPLICATION DEVELOPMENT
(Common to CSE, CSE-AI, AIML, CSE-IOT)
Course Code 21A050422
By
CH VENKATESWARLU
UNIT-V
Building Menus and Storing Data

Using Databases

Communicating with SMS and Emails


UNIT-V
Creating Interactive Menus and ActionBars
Menus and Their Types
Creating Options Menus with XML
Creating Menus with Coding
Handling Menu Selections
Using Check Boxes/Radio Buttons in Menus
Adding Shortcut Keys
Using the ActionBar
Displaying Action Items
Creating Tabbed ActionBar
Creating Drop-Down List ActionBar

In almost all applications we encounter menus that display options in


the form of menu items. Choosing a menu item results in the initiation
of the desired task. Menus are therefore the preferred way of indicating
the possible actions in an application.
Menus are the preferred way of indicating the possible actions in an application.
Choosing a menu item results in the initiation of the desired task.

The ActionBar is a widget that replaces the title bar at the top of an Activity displaying
navigation and important functionality of an application. It provides a consistent UI of
an application. It also displays the key actions that are commonly used in an
application and that are constantly visible on the screen.
ActionBar is also commonly used to provide a quick link to an application's home.

Menus and Their Types


Android SDK supports three types of menus: Options, Submenu, and Context

Options Menu—Also known as the Activity menu, this menu is displayed when a MENU
button is clicked. In an options Menu, the menu items are displayed in the form of
text, check box, or radio buttons. It can display shortcut keys but does not display
icons.
In older Android API levels (Levels 10 and below), there were two types of Options
Menus:
Icon Menu
Expanded Menu
► Icon Menu—
The icon Menu appears when the user presses the MENU button on the device. The
icon Menu shows the first six menu items of the menu in the form of large, finger-
friendly buttons arranged in a grid at the bottom of the screen.
The menu items in the icon Menu can display icons as well as text. The icon Menu
does not display check boxes, radio buttons, or the shortcut keys for menu items.
It is not mandatory to have icons for icon Menu items; text will also do for the Icon
Menu.

► Expanded Menu—
If the menu has more than six menu items, the first five items are displayed as an icon
Menu and the sixth option appears as a More button.
Clicking the More button displays the Expanded Menu that shows the scrollable list of
the rest of the menu items that could not be accommodated in the icon Menu.
The Expanded Menu can display menu items in the form of text, check boxes, or radio
buttons. Also, it can display shortcut keys but does not display icons.
Pressing the Back button from the Expanded Menu takes you back to the Activity the
menu was launched from.
Note:The icon Menu and Expanded Menu are not supported in Android API levels 11
and higher.

Submenu—Submenu refers to the menu that displays more detailed or specific


menu options when a menu item is selected.
A submenu is displayed as a floating window showing all of its menu options. The
name of the submenu is shown in the header bar, and each menu option is displayed
with its full text, check box, radio button (if any), and shortcut key.
Icons are not displayed in the submenu options. We cannot add a submenu to any
menu option of a submenu as Android does not support nested submenus.
Pressing the Back button closes the floating window without navigating back to the
Expanded or icon menus.

Context Menu—The context Menu is displayed when we tap-and-hold on the


concerned view or when a user holds the middle D-pad button or presses the
track­ball.
context Menus support submenus, check boxes, radio buttons, and shortcuts, but we
cannot display icons in a Context Menu.
In the context Menu's header bar, we can display a title and icon.
BY USING SNIPPING TOOL SCREEN SHOTS ARE CAPTURED.
MOBILE APPLICATION DEVELOPMENT
(Common to CSE, CSE-AI, AIML, CSE-IOT)
Course Code 21A050422
BY
CH VENKATESWARLU
UNIT-V
Using Databases
► Using SQLiteOpenHelper

► Fetching Desired Rows from Data Tables

► Using Cursors

► Accessing Databases Through the ADB

► Accessing Databases Through Menus

► Creating Data Entry Forms

► Displaying Table Rows Via ListView


Android offers the SQLite relational database library for persisting data. It's an open-source,
lightweight, and powerful database available in the form of a C library. It uses SQL (Structured
Query Language) for storing and retrieving information and performing database maintenance.

SQLite is extremely reliable and is popularly used in devices with restricted computing power.
Through SQLite, we can create individual databases for each application and store and manage
application-related data.

I. Using the SQLiteOpenHelper Class


Android databases are stored in the /data/data/<package_ name>/databases folder on devices
or emulators.
The SQLiteOpenHelper class is an abstract class that provides a way to get read or write access
to a database.
The SQLiteOpenHelper class is an abstract class used to create, open, and upgrade databases.
It provides several methods including getWritableDatabase(), getReadableDatabase(), and
close() that returns an SQLiteDatabase object that lets the calling code do the reading, writing,
and closing of the database, respectively.
The SQLiteDatabase class also provides methods including insert () and query(), which are used
to insert rows in the database table and execute different SQLite queries on the database table.

The query() method accepts several parameters such as the database table to query, columns,
and criteria, and returns a cursor representing the rows that satisfy the supplied criteria.

The cursor class provides several methods to traverse the result set and move to the desired row
and column position in the result set.

Building an SQLite Project


In this application, we create a database called shopping, and in it we create a table called
products.
The products table consists of three columns: code, product_name, and price to store the code,
product name, and price, respectively. To the products table, we add a couple of rows.

Also, we access the rows in the products table and display them via the Textview control.

To take advantage of the SQLiteopenHelper class and its method, we need to extend it.
Write code in DatabaseManager. java to perform the following tasks:

Inherit from the SQLiteOpenHelper class to access and take advantage


of the methods defined in it.
Open and return the writable and readable database file instance to
perform writing and reading operations on the database, respectively.
Create a database table, products, consisting of three columns: code,
product_name, and price.
Add rows to the products table. The information for the new product
is supplied by the activity file DatabaseAppActivity. java.
java.lang.Object
Fetch rows from the products table and return them to the activity file
DatabaseAppActivity. java for displaying on the screen.
import android.database.sqlite.SQLiteDatabase;
import android.content.Context;
import android.content.ContentValues;
import android.database .Cursor;
import android.database.sqlite.SQLiteOpenHelper;
import android.utii.Log;
public class DatabaseManager {
public static final String DB_NAME = "shopping";
public static final String DB_TABLE = "products";
public static final int DB_VERSION = 1;
private static final String CREATE_TABLE = "CREATE TABLE " + DB_TABLE + " (code
INTEGER PRIMARY KEY, product_name TEXT, price FLOAT);
private SQLHelper helper;
private SQLiteDatabase db;
private Context context;
public DatabaseManager(Context c){
this.context = c;
helper=new SQLHelper(c);
this.db = helper.getWritableDatabase();
}
public DatabaseManager openReadable() throws android.database.SQLException {
helper=new SQLHelper(context);
db = helper.getReadableDatabase();
return this; }
public void close()
{ helper.close();
}
public void addRow(Integer c, String n. Float p)
{
ContentValues newProduct = new ContentValues();
newProduct.put("code", c );
newProduct.put ("product_name”, n);
newProduct.put("price", p);
try{
db.insertOrThrow(DB_TABLE, null, newProduct);
}
catch(Exception e) {
Log.e("Error in inserting rows ", e.toString() );
e.printstackTrace();
}
}
public String retrieveRows()
{
String[] columns = new String[]{"code", "product_name", "price"};
Cursor cursor = db.query(DB_TABLE, columns, null, null, null, null, null);
String tablerows = "";
cursor.moveToFirst();
while (cursor.isAfterLast() == false)
{
tablerows = tablerows + cursor.getInt(0) + ", "+cursor.getstring(1)+", " + cursor.getFloat(2)+ "\n";
cursor.moveToNext();
}
if (cursor != null && !cursor.isClosed() )
{
cursor.close();
}
return tablerows;
}
public class SQLHelper extends SQLiteopenHelper {
public SQLHelper(Context c)
{
Super(c, DB_NAME, null, DB_VERSION);
}
@0verride
public void onCreate(SQLiteDatabase db)
{ db . execSQL (CREATE_TABLE) ;
}
@0verride
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w("Products table","Upgrading database i.e. dropping table and recreating it");
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
onCreate(db);
}
}
}

II. Fetching the Desired Rows from Tables


To fetch the desired rows from a database table, we execute queries containing a criterion
against the given database.
The queries are executed through the query () method provided by the SQLiteDatabase class.
The parameters that are passed to the query () method are shown here:
db.query(bool_uniq, db_table, array_colurans, where_ clause, select_arg, group_by,
having_clause, order);.

Table 8.1 shows the meaning of these parameters.


Parameter Usage
bool_uniq Optional Boolean value to determine whether the result set should contain
only unique values. A True value confirms the unique values in the result set.
db_table The database table to be queried.
array columns A string array containing the list of columns we want in the result set.
where clause Defines the criteria for the rows to be returned. For specifying values in the
clause, ? wildcard(s) are used, which are then replaced by the values stored
in the select arg parameter.
select_arg An array of strings that provide values for the ? wildcards used in the
where_clause parameter.
group_by Defines the condition for grouping the returned result set.
having_clause Defines the conditions to be applied to the groups defined in the group_ by
clause.
order Defines the order of the returned rows.
Examples:
The following two queries return all the products table rows for the code, product_name, and
price columns. The first query confirms that only unique rows should be fetched:
public static final String DB_TABLE = "products";
String[] columns = new String[]{"code", "product_name“,"price"};
Cursor cursor = db.query(true, DB_TABLE, columns, null, null, null, null, null);
Cursor cursor = db.query(DB_TABLE, columns, null, null, null, null, null);
The following query returns the rows with the product name camera and the result set is sorted
on the product code:
String whereClause="product_name=Camera";
String order="code";
Cursor cursor = db.query(DB_TABLE, columns, whereClause, null, null, null, order);

The returned rows from the query () method are in the form of cursor objects.

A Cursor object does not create a separate result set of the extracted rows, but points at the
result set that is part of a database table.

When we call the moveToFirst() method on the cursor object, the cursor is moved to the first
row in the result set.

Thereafter, all the products table rows that exist in the cursor object are fetched one by one by
calling the moveToNext() method and returned.

The cursor is closed when all the rows pointed at in its result set are traversed.
III. Using Cursors
Cursors are pointers pointing at the result set of the underlying data and can be set to
traverse the rows and retrieve column data of the result set.
The Cursor class provides several methods that can be used to set the pointer at the
desired row and column position of the result set.

Method Usage
moveToFirst Moves the cursor to the first row in the result set
moveToNext Moves the cursor to the next row
moveToPrevious Moves the cursor to the previous row
getCount Returns the count of the rows in the result set
getColumn- Returns the index for the column with the specified name. It throws
IndexOrThrow an exception if no column exists with that name
getColumnName Returns the column name with the specified column index
getColumnNames Returns a string array that contains all the column names in the
current cursor
moveToPosition Moves the cursor to the specified row
getPosition Returns the current cursor position
import android.app.Activity;
import android.os.Bundle;
import android.widget.Textview ;
public class DatabaseAppActivity extends Activity {
private DatabaseManager mydManager;
private Textview response;
private Textview productRec;
@Override
public void onCreate(Bundle savedlnstanceState)
{
super.onCreate(savedlnstanceState);
setContentView(R.layout.activity_database_app);
response=(Textview)findViewByld(R.id.response);
productRec=(Textview)findViewByld(R.id.prodrec);
mydManager = new DatabaseManager(this);
mydManager.addRow(101, "Camera", Float.parseFloat("15"));
mydManager.addRow(102, "Laptop", Float.parseFloat("1005.99"));
mydManager.close();
mydManager = new DatabaseManager(this);
mydManager.openReadable();
String tableContent = mydManager.retrieveRows();
response.setText("The rows in the products table are:");
productRec.setText(tableContent); mydManager.close();
}
}
Written into the Layout File activity_database_app.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android: layout_height= "match_parent" >
<Textview
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/response" />
<TextView
android:id=“@+id/prodrec"
android: layout_width="match_parent"
android: layout_height= "wrap_content”/>
</LinearLayout>
IV. Accessing Databases with the ADB
The ADB (Android Debug Bridge) is a client/server program that is part of the Android SDK and is
used to communicate with, control, and manage Android devices and emulators.
Perform several tasks via adb commands, including viewing applications, deleting them,
installing new applications, and executing shell commands.

To access the ADB through the Windows operating system, open the command prompt and
navigate to the folder where adb. exe is located.
By default, the file, adb. exe is installed in C:\Program Files (x86) \Android\android-
sdk\platform-tools. We can issue the following commands to interact with a device or emulator.

The adb devices command shows the list of currently running emulator(s) and devices:
C:\Prograra Files (x86) \Android\android-sdk\platform-tools>adb devices
List of devices attached
emulator-5554 offline

The adb shell command activates the shell, where we can issue Unix-like commands:
C:\Program Files (x86)\Android\android-sdk\platform-tools>adb shell
The ls -l long listing command shows the list of directories in the emulator/device:
On executing the ls command, we see the list of files and directories in the databases
subdirectory. As expected, the name of our shopping database is displayed:
# ls
ls
Shopping

Then, make the shopping database active by using the sqlite3 shopping command:
# sqlite3 shopping
sqlite3 shopping
SQLite version 3.5.9
Enter ".help" for instructions

The SQLite version information is displayed with the directive to type the .help command to see
help instructions. We also see an sqlite> prompt to issue database related commands.

The .tables command displays the tables that exist in the currently active database:
sqlite> .tables
.tables
android_metadata products
The . schema command displays the structure (field names, their types, width, and so on) of all
the tables that exist in the currently active database:
sqlite> .schema
.schema
CREATE TABLE android_metadata (locale TEXT);
CREATE TABLE products (code INTEGER PRIMARY KEY, product_name TEXT, price FLOAT);

The SQL SELECT command can be used to see the number of rows in the products table of our
shopping database:
sqlite> select * from products;
select * from products;
101|Camera|15.0
102|Laptop|1005.98999023438

We can also issue an SQL DELETE command to delete a row. The following command deletes a row
from the products table that has a product code equal to 102.
sqlite> delete from products where code=102;
delete from products where code=102;

When finished, we can leave the sqlite> prompt by giving an .exit command:
sqlite>.exit
V. Accessing the Database Through Menus
In the menu file, we define a menu consisting of two menu items called insert Rows and List
Rows.
These are used to initiate the tasks of inserting and accessing rows from the products table.
Code Written into the Menu File activity_database_app.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/insert_rows"
android:title="Insert Rows"
android:icon=“@drawable/ic_launcher"/>
<item android:id="@+id/list_rows"
android:title="List Rows"
android:icon="@drawable/ic_launcher”/>
</menu>
Code in the DatabaseAppActivity.java Activity File

package com.androidunleashed.databaseapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Textview; import android.view.Menu;
import android.view.Menulnflater;
import android.view.Menultem;

public class DatabaseAppActivity extends Activity {


private DatabaseManager mydManager; private Textview response;
private Textview productRec;
@0verride
public void onCreate(Bundle savedlnstanceState) { super.onCreate(savedlnstanceState);
setContentView(R.layout.activity_database_app);
response=(Textview)findViewByld(R.id.response);
productRec=(Textview)findViewByld(R.id.prodrec);
response.setText("Press MENU button to display menu");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Menulnflater inflater = getMenuInflater();
inflater .inflate(R.menu.activity_database_app, menu); return true;
}
@0verride
public boolean onOptionsItemSelected(Menu!tem item) {
switch (item.getltemld()) {
case R.id.insertrows: insertRec(); break;
case R.id.list_rows: showRec(); break;
}
return true;
}
public boolean insertRec()
{
mydManager = new DatabaseManager(this);
mydManager.addRow(101, "Camera", Float.parseFloat("15"));
mydManager.addRow(102, "Laptop", Float.parseFloat("1005.99"));
response.setText("The rows in the products table are inserted");
productRec.setText("");
mydManager. close ();
return true;
}
public boolean showRec(){
mydManager = new DatabaseManager(this);
mydManager.openReadable();
String tableContent = mydManager.retrieveRows();
response.setText("The rows in the products table are:");
productRec.setText(tableContent);
mydManager.close(); return true;
}
VI. Creating a Data Entry Form
To create a form for entering new product information three Textviews, three EditText controls,
and two Button controls are arranged in tabular format in the TableLayout.
Code Written into the Layout File activity_database_app.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent”>
<Textview
android:layout_width="match_parent“
android:layout_height="wrap_content"
android:id=“@+id/response"/>
<TextView
android:id=“@+id/prodrec"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TableLayout
android:id="@+id/add_table"
android:layout_width="match_parent"
android:layout_height="wrap_content”>
<TableRow >
<TextView
android:text="Product Code:”
android:padding="3dip" />
<EditText
android:id="@+id/prod_code"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</TableRow>
<TableRow >
<Textview
android:text="Product Narae:"
android:padding="3dip”/>
<EditText
android:id="@+id/prodname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minwidth="150dip"/>
</TableRow> <TableRow >
<TextView
android:text="Product Price:" android:padding="3dip" />
<EditText
android:id="@+id/prod_price"
android:layout_width="wrap_content"
android: layout_height="wrap_content"
android:minwidth=“50dip"/>
</TableRow>
<TableRow >
<Button
android:id=“@+id/add_button"
android:text=“Add Product"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="3dip" />
<Button
android:id="@+id/cancel_button"
android:text="Cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="3dip" /> </TableRow> </TableLayout>
</LinearLayout >
Code Written into the Java Class DatabaseManager.java
package com. androidunleashed.databaseapp;
Import android.database.sqlite.SQLiteDatabase;
Import android.content.Context;
Import android.content.Contentvaiues;
Import android. database. Cursor;
Import android.database.sqlite.SQLiteOpenHelper;
Import android.util.Log;
public class DatabaseManager (
public static final String DB_NAME = "shopping";
public static final String DB_TABLE = "products";
public static final int DB_VERSION = 1;
private static final String CREATE_TABLE = "CREATE TABLE “+ DB_TABLE +”(code
INTEGER PRIMARY KEY, product_name TEXT, price FLOAT);";
private SQLHelper helper;
private SQLiteDatabase db;
private Context context;
public DatabaseManager(Context c){ this.context = c;
helper=new SQLHelper(c);
this.db = helper.getWritableDatabase();
}
public DatabaseManager openReadable () throws android, database. SQLExcept ion {
helper=new SQLHelper(context); db = helper.getReadableDatabase0; return this;
}
public void close(){ helper.close();
}
public boolean addRow(int c, String n, float p){
ContentValues newProduct = new ContentValues();
newProduct.put("code", c) ;
newProduct.put("product_name", n);
newProduct.put("price", p);
try{db.insertOrThrow(DB_TABLE, null, newProduct);} catch(Exception e) {
Log.e("Error in inserting rows ", e.toString());
e.printStackTrace();
return false; }
db.close(); return true;
}
public String retrieveRows(){
String[] columns = new String[]{"code", "productjname", "price"};
Cursor cursor = db.query(DB_TABLE, columns, null, null, null, null, null);
String tablerows = cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
tablerows = tablerows + cursor.getlnt(0) + ", "+cursor.getString(1)+", "+ cursor.getFloat(2)+ "\n";
cursor.moveToNext();
}
if (cursor != null && !cursor.isClosedO) { cursor.close();
}
return tablerows;
public class SQLHelper extends SQLiteOpenHelper { public SQLHelper(Context c){
superfc, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("Products table", "Upgrading database i.e. dropping table and rec­reating it");
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
onCreate(db);
}
}
}
In the activity file, we need to write Java code to perform the following tasks:
Access the TableLayout container and make it visible when the insert Rows menu item is
selected. Also make it invisible when the List Rows menu item is selected.
Map the EditText and Button controls defined in the TableLayout to the EditText and Button
objects, respectively.
Associate ClickListener to the Add Product button defined in the TableLayout to listen for the
click event occurrence on the Button control.
Through the callback event of the ClickListener, onciickO, access the new product information
entered by the user and send it to the addRowO method defined in DatabaseManager. java as
parameters to insert them in the products table.
Hide the soft keyboard when the user is finished entering new product information.
Code Written into the DatabaseAppActivity.java Java Activity File package
com.androidunleashed.databaseapp;
Import android.app.Activity;
Import android.content.Context;
Import android.os.Bundle; import android.widget.Textview;
Import android.view.Menu;
Import android.view.Menulnflater;
import android.view.Menultem;
import android.view.view;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
public class DatabaseAppActivity extends Activity { private DatabaseManager mydManager;
private Textview response;
private Textview productRec;
EditText pcode, pname, price; Button addButton;
private TableLayout addLayout; private boolean reclnserted;
@Override
public void onCreate(Bundle savedlnstanceState) { super.onCreate(savedlnstanceState);
setContentView(R.layout.activity_database_app);
response=(Textview)findViewByld(R.id.response);
productRec=(Textview)findViewById(R.id.prodrec);
addLayout=(TableLayout)findViewById(R.id.addtable);
addLayout.setvisibility(View.GONE);
response.setText("Press MENU button to display menu");
Button addButton = (Button) findViewByld(R.id.addbutton) ;
addButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mydManager = new DatabaseManager(DatabaseAppActivity.this);
pcode=(EditText)findViewByld(R.id.prodcode);
pname=(EditText)findViewByld(R.id.prod_name);
price=(EditText) findViewBy Id (R. id. prod jprice);
recInserted=mydManager.addRowfInteger.parselnt(pcode.getText(). toString()),
pname.getText().toString(),Float.parseFloat (price.getText().toString()));
addLayout.setvisibility(View.GONE);
if(reclnserted)
response.setText("The row in the products table is inserted");
else
response.setText("Sorry, some errors occurred while inserting the row in the products table");
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUTMETHODSERVICE);
imm.hideSoftInputFromWindow(price.getWindowToken(), InputMethodMa-
nager.BlDENOTALWAYS);
mydManager.close(); pcode.setText("");
pname.setText("");
price.setText("");
productRec.setText("");
} }); }
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Menulnflater inflater = getMenuInflater ();
inflater.inflate(R.menu.activity_database_app, menu); return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getltemld() ) {
case R.id.insert_rows: addLayout.setvisibility(View.VISIBLE);
response.setText("Enter information of the new product");
productRec.setText(""); break;
case R.id.list_rows: showRecf);
break;
} return true;
}
public boolean showRec(){
addLayout.setvisibility(View.GONE);
mydManager = new DatabaseManager(this);
mydManager.openReadable();
String tableContent = mydManager.retrieveRows();
response.setText("The rows in the products table are:");
productRec.setText(tableContent);
mydManager.close(); return true;
} }
VII. Displaying Table Rows Via Listview
To display the information fetched from the database table with the Listview control instead of
the Textview control, the first step is to replace the response Textview that we used to display
products table rows with a Listview control. After we replace the Textview control with a
Listview control, activity_database_app.xrai appears as shown in Listing 8.9. Only the code in
bold is modified; the rest of the code is the same as we saw in Listing 8.6.

You might also like