MAD PPTs
MAD PPTs
MAD PPTs
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 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
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.
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 character R in the parameter refers to the auto-generated R. java class 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"
/>
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.
<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.
To access ADB through windows, open the command prompt and navigate to the folder where
adb.exe is located by using the cd 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
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.
<application> tag: which is the parent of application controls tags. @string and
@drawable refer to the strings and drawable resources, respectively.
<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.
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>
2. EditText: An editable text box that also accepts multiline entry and word-
wrapping.
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
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.
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;
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));
<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;
<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;
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;
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);
}
};
}
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.
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
<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
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.
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
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.
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, respectively. 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.
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 application. 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.
<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);
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;
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.
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]);
}
}
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;
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);
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>
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);
<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;
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.
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
scrollable 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;
When we run DDMS, it automatically connects to the attached Android device or any
running emulator, DDMS helps with a variety of tasks, including
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.
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.
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.
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.
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;
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 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.
<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;
}
});
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.
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); } };
}
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
<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;
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:
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.
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
Using Databases
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.
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.
► Using Cursors
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.
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.
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:
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;