You are on page 1of 31

Mobile Application Development

MODULE – 4: Creating the Activity, working with views & Multimedia 22MCA263

Objective:

4. Creating the Activity, working with views:


4.1. Exploring common views
4.2. Using a list view,
4.3. Creating custom views,
4.4. Understanding layout.
4.5. Using Selection Widgets and Debugging,
4.6. Displaying and Fetching Information Using Dialogs and Fragments.

5. Multimedia:
5.1. Playing Audio,

5.2. Playing Video and Capturing Media.

5.3. Advanced Android Programming: Internet, Entertainment, and Services.

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 1


Mobile Application Development
MODULE – 4: Creating the Activity, working with views & Multimedia 22MCA263

4). Creating the Activity, working with views

 What is an Activity?
An activity is one screen of an app. An Android app contains activities, meaning one or more
screens.
An Activity is an application component that provides a screen with which users can interact to do
something, such as dial the phone, take a photo, send an email, or view a map. Examples: Login
screen, sign up screen, and home screen.

 What are views?


Activities themselves are made up of subcomponents called views. An Android view is a widget
which appears on screen (Activity). View objects are mainly used to draw content on the screen of
any android device. The easiest way to use this object is through an XML file. The view elements
are TextView, ImageView, Button, EditText, etc.

 What is resource?
Views and other Android components make use of strings, colors, styles, and graphics, which are
compiled into a binary form and made available to applications as resources.
The relationship among activities, views, and resources is depicted in figure 3.1.

Figure 3.1 High-level diagram of Activity, View, resources, and manifest relationship

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 2


Mobile Application Development
MODULE – 4: Creating the Activity, working with views & Multimedia 22MCA263

a) Creating the Activity:


Application: Lets build “ReviewCriteria” screen where user adds his review to restaurants.
 Create Activity for below User screen.

public class ReviewCriteria extends Activity {


private static final int MENU_GET_REVIEWS = Menu.FIRST;
private Spinner cuisine;
private Button grabReviews;
private EditText location;
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this. setContentView(R.layout.review_criteria);
this.location = (EditText)findViewById(R.id.location);
this.cuisine = (Spinner)findViewById(R.id.cuisine);
this.grabReviews = (Button)findViewById(R.id.get_reviews_button);
ArrayAdapter <String> cuisines =
new ArrayAdapter <String> (this, R.layout.spinner_view,
getResources(), getStringArray(R.array.cuisines));
this.grabReviews.setOnClickListener ( new OnClickListener() {
public void onClick(View v) {
handleGetReviews();
}
});
}
}

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 3


Mobile Application Development
MODULE – 4: Creating the Activity, working with views & Multimedia 22MCA263

The ReviewCriteria class extends Activity.


1. Defines three views required in Activity like: location, cuisine, and grabReviews. Location is a
type of View known as an EditText, a basic text-entry component. cuisine is a fancy select list
component, known in Android terms as a Spinner, and grabReviews is a Button.
2. Every Activity will override onCreate(), where component initialization steps are invoked.
3. The setContentView() method is normally associate an XML layout file. An XML layout file
defines View objects, which are laid out in a tree, and can then be set into the Activity for use.

4. Java view objects are bound to the views of XML with findViewById() method by passing its
android:id attribute..
5. When we create the ArrayAdapter we define the View to be used for the element shown in the
Spinner before it is selected; after it is selected it uses the View defined in the drop-down.
6. An OnClickListener with our Button, respond when the button is clicked.

b) ACTIVITY LIFECYCLE

Beyond onCreate() and on_Pause(), Android provides other distinct stages, each of which is a part of
a particular phase of the life of an Activity class. The most encountered methods and the phases for
each part of the lifecycle are shown in figure 3.3.
 In the foreground phase, the Activity is viewable on the screen and on top of everything else
(when the user is interacting with the Activity to perform a task).
 In the visible phase, the Activity is on the screen, but it may not be on top and interacting with
the user (when a dialog or floating window is on top of the Activity, for example).
 The entire lifecycle phase refers to the methods that may be called when the application is not
on the screen, before it is created, and after it is gone prior to being shut down.
Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 4
Mobile Application Development
MODULE – 4: Creating the Activity, working with views & Multimedia 22MCA263

Table 3.1: The main high-level methods on the Activity class.


Method Purpose
onCreate() Called when the Activity is created. Setup is done here. Also provides access to any
previously stored state in the form of a Bundle, which can be used to restore what
the user was doing before this Activity was destroyed.
onRestart() Called if the Activity is being restarted, if it’s still in the stack, rather than starting
new.
onStart() Called when the Activity is becoming visible on the screen to the user.
onResume() Called when the Activity starts interacting with the user. (This method is always
called, whether starting or restarting.)
onPause() Called when the Activity is pausing or reclaiming CPU and other resources. This
method is where you should save state information so that when an Activity is
restarted, it can start from the same state it was in when it quit.
onStop() Called to stop the Activity and transition it to a nonvisible phase and subsequent
lifecycle events.
onDestroy() Called when an Activity is being completely removed from system memory. This
method is called either because onFinish() is directly invoked or because the system
decides to stop the Activity to free up resources.

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 5


Mobile Application Development
MODULE – 4: Creating the Activity, working with views & Multimedia 22MCA263

4.1. Exploring common views

Android provides a generous set of View classes in the android.view package. The class diagram
in figure 3.4 provides a high-level snapshot of what the overall View API looks like.

Figure 3.4 A class diagram of the Android View API

As is evident from the diagram in figure 3.4, View is the base class for many classes. ViewGroup is a
special subclass of View related to layout, as are other elements such as the commonly
used TextView. All UI classes are derived from the View class, including the layout classes (which
extend ViewGroup).

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 6


Mobile Application Development
MODULE – 4: Creating the Activity, working with views & Multimedia 22MCA263

Table 3.2 lists some of the methods available in the root View class.

Table 3.2. A subset of methods in the base Android View API

Method Purpose

setBackgroundColor(int color) Set the background color

setBackgroundDrawable(Drawable d) Set the background drawable (such as an image


or gradient)

setClickable(boolean c) Set whether element is clickable

setFocusable(boolean f) Set whether element is focusable

setLayoutParams(ViewGroup.LayoutParams l) Set parameters for layout (position, size, and


more)

setMinimumHeight(int minHeight) Set the minimum height (parent can override)

setMinimumWidth(int minWidth) Set the minimum width (parent can override)

setOnClickListener(OnClickListener l) Set listener to fire when click event occurs

setOnFocusChangeListener( Set listener to fire when focus event occurs


OnFocusChangeListener l)

setPadding(int left, int right, int top, Set the padding


int bottom)

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 7


Mobile Application Development
MODULE – 4: Creating the Activity, working with views & Multimedia 22MCA263

4.2. Using a list view

On the RestaurantFinder application’s ReviewList Activity , shown in figure 3.2, you can see a view that’s
different from the simple user inputs and labels we’ve used up to this point—this screen presents a scrollable
list of choices for the user to pick from.

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 8


Mobile Application Development
MODULE – 4: Creating the Activity, working with views & Multimedia 22MCA263

4.3. Creating custom views

In the ReviewList screen, we used an adapter of type ReviewAdapter to back our ListView. This
custom adapter contains a custom View object, ReviewListView. A ReviewListView is what our
ReviewList Activity displays for every row of data it contains. The adapter and view are shown in the
following listing.

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 9


Mobile Application Development
MODULE – 4: Creating the Activity, working with views & Multimedia 22MCA263

The ReviewAdapter extends BaseAdapter. BaseAdapter is an Adapter implementation that provides


basic event-handling support. Adapter itself is an interface in the android.widget package and
provides a way to bind data to a View with some common methods.
Our ReviewAdapter class accepts and stores two parameters in the constructor. This class
goes on to implement the required Adapter interface methods that return a count, an item, and an
ID; we use the ordinal position in the collection as the ID B. The next Adapter method to implement
is the most important: getView(). The adapter returns any view we create for a particular item in
the collection of data that it’s supporting. Within this method, we get a particular Review object
based on the position/ID. The UI framework might call getView() multiple times for a given item; for
example, the UI may need to make multiple layout passes in order to determine how items will fit
inside. If there isn’t a valid older view, we create an instance of a custom ReviewListView object to
return as the view c.
ReviewListView itself is an inner class inside ReviewAdapter; we never use it except to return
a view from ReviewAdapter d. Within it, you see an example of set_ting layout and view details in
code, rather than relying on their definition in XML. In this listing, we set the orientation,
parameters, and margin for our layout e. Next, we populate the simple TextView objects that will be
children of our new view and represent data. When these are set up via code, we add them to the
parent container, which is in this case our custom class ReviewListView f. This is where the data
binding happens—the bridge to the view from data. Another important thing to note about this is
that we’ve created not only a custom view, but also a composite one. We’re using simple existing
View objects in a particular layout to construct a new type of reusable view, which shows the detail
of a selected Review object on screen, as depicted in figure 3.2

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 10


Mobile Application Development
MODULE – 4: Creating the Activity, working with views & Multimedia 22MCA263

4.4. Understanding layout

One of the most significant aspects of creating your UI and designing your screens is understanding
layout. Android manages layouts through ViewGroup and Layout_Params objects. ViewGroup is a
view that contains other views and also provides access to the layout.

On every screen, all the views are placed in a hierarchical tree; every element can have one or more
children, with a ViewGroup at the root. All the views on the screen support a host of attributes that
we addressed in section 3.2.1. Dimensions—width and height—and other properties such as the
margins and whether to use relative or absolute placement are based on the LayoutParams a view
requests and what the par_ent can accommodate. The final layout reflects the cumulative
dimensions of the par_ent and its child views.

The main ViewGroup classes are shown in the class diagram in figure 3.4. The dia_gram in figure 3.6
expands on this class structure to show the specific LayoutParams inner classes of the view groups
and layout properties each type provides.

Figure 3.6. Common ViewGroup classes with LayoutParams and properties provided

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 11


Mobile Application Development
MODULE – 4: Creating the Activity, working with views & Multimedia 22MCA263

As figure 3.6 shows, the base ViewGroup.LayoutParams class supports height and width. From
there, an AbsoluteLayout type with AbsoluteLayout.LayoutParams allows you to specify the exact x
and y coordinates of the child View objects placed within. You should generally avoid the
AbsoluteLayout because it prevents layouts from looking good on larger or smaller screen
resolutions.

4.5. Using Selection Widgets and Debugging

Selection widgets refers to the group controls that display a list of choices from which users select items. To
constrain users to enter the correct data type or within a specific range and also to show the valid values, lists
and drop-down lists are commonly used in applications. Lists and drop-down lists are
called ListView and Spinner controls in Android. Besides ListView and Spinner

4.5.1. 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. Some of them are listed in Table 5.1.

Table 5.1. List of Attributes Used to Configure the ListView Control

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 12


Mobile Application Development
MODULE – 4: Creating the Activity, working with views & Multimedia 22MCA263

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

For creating ListView controls, we can use either of the following methods:
• The regular Activity base class
• An activity that extends android.app.ListActivity

a) Creating a ListView with regular Activity base class

In both cases, whether we are creating a ListView by extending the Activity class or
the ListActivity class, the ListView can be populated by one of the following two methods:
• By ListView through a string resource
• By ListView through Adapter

 ListView through a string resource

Open the string resource file /res/values/strings.xml, and add a string-array structure
called fruits that lists various fruits that we want to display via the ListView control. After we add
a string-array, the strings.xml file appears as shown in Listing 5.1.
Listing 5.1. The strings.xml File After Adding the Strings Array
<resources>
<string name="app_name">ListViewApp</string>
<string-array name="fruits">
<item>Apple</item>
<item>Mango</item>
<item>Orange</item>
<item>Grapes</item>
<item>Banana</item>
</string-array>
</resources>

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 13


Mobile Application Development
MODULE – 4: Creating the Activity, working with views & Multimedia 22MCA263

Listing 5.4. The Layout File activity_list_view_demo1.xml After Adding the ListView and TextView Controls

<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="wrap_content">
<ListView
android:id="@+id/fruits_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:entries="@array/fruits"

/>
<TextView

android:id="@+id/selectedopt"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>

Figure 5.2. Options displayed through Java code in the ListView control and the selected option
from ListView displayed through the TextView control

 ListView through a ArrayAdapter

The ArrayAdapter is one of the adapters provided by Android that provides data sources (child elements) to
selection widgets and also casts the data into specific view(s) to be displayed inside the selection widgets. In
this section, we learn to create an ArrayAdapter and use it to populate the ListView control.
An ArrayAdapter can be created through string resource, as well as through string arrays defined in Java
code. We try the latter method in this section.

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 14


Mobile Application Development
MODULE – 4: Creating the Activity, working with views & Multimedia 22MCA263

public class Fragment1Activity extends Fragment {


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

4.5.2. Using 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: (i) using string resource and (ii) Using ArrayAdapter that acts as a data source.
Listing 5.8. String Array Defined in the arrays.xml File

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


<resources>

<string-array name="fruits">
<item>Apple</item>
<item>Mango</item>
<item>Orange</item>
<item>Grapes</item>
<item>Banana</item>
</string-array>
</resources>

To display the Spinner control in the application, let’s define it in the layout
file activity_spinner_app.xml, as shown in Listing 5.10.

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 15


Mobile Application Development
MODULE – 4: Creating the Activity, working with views & Multimedia 22MCA263

Listing 5.10. The activity_spinner_app.xml File with a Defined Spinner 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">

<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:prompt="@string/choose_msg"
android:entries="@array/fruits"/>

<TextView
android:id="@+id/selectedopt"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>

The Spinner control displays a list of choices, and the TextView displays the choice selected by the
user from the Spinner control. 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.

Figure 5.4. Spinner control with a drop-down arrow (left), options displayed through an Arrays Resource in
the Spinner control (middle), and the option selected in the Spinner displayed through TextView (right)

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 16


Mobile Application Development
MODULE – 4: Creating the Activity, working with views & Multimedia 22MCA263

Using the Debugging Tool: Dalvik Debug Monitor Service (DDMS)

The DDMS is a powerful debugging tool that is downloaded as part of the Android SDK. DDMS can
be run either by selecting the DDMS icon on the top-right corner of the Eclipse IDE or by selecting
the Window, Open Perspective, DDMS option.
When we run DDMS, it automatically connects to the attached Android device or any running
emulator. DDMS helps with a variety of tasks, including.
 Finding bugs in applications running either on an emulator or on the physical device.
 Providing several services such as port forwarding, on-device screen capture, incoming call,
SMS, and location data spoofing.
 Showing the status of active processes, viewing the stack and heap, viewing the status of active
threads, and exploring the file system of any active emulator.
 Providing the logs generated by LogCat, so we can see log messages about the state of the
application and the device. LogCat displays the line number on which the error(s) occurred.
 Simulating different types of networks, such as GPRS and EDGE.

Figure 5.11 shows the DDMS tool window.

Figure 5.11. The DDMS tool window

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 17


Mobile Application Development
MODULE – 4: Creating the Activity, working with views & Multimedia 22MCA263

In the Devices tab, you see some icons, described here:


• Debug—Used to debug the selected process.
• Update Heap—Enables heap information of the process. After clicking this icon, use
the Heap icon on the right pane to get heap information.
• Dump HPROF file—Shows the HPROF file that can be used for detecting memory leaks.
• Cause GC—Invokes Garbage Collection.
• Update Threads—Enables fetching the thread information of the selected process. After
clicking this icon, we need to click the Threads icon in the right pane to display information
about the threads that are created and destroyed in the selected process.
• Start Method Profiling—Used to find the number of times different methods are called in an
application and the time consumed in each of them. Click the Start Method Profiling icon,
interact with the application, and click the Stop Method Profiling icon to obtain information
related to the different methods called in the application.
• Stop Process—Stops the selected process.

Ways of Debugging Applications

The two most common ways of debugging an application and finding out what went wrong
are placing breakpoints and displaying log messages.

a). 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. Let’s return to the Android
project, HelloWorldApp, that we created in Chapter 1, “Introduction to Android.” Add a few
statements to its activity file, as shown in Listing 5.22. The statements just perform simple
multiplication and display log messages. Only the statements in bold are newly added; the rest of the
code is the same as the code in Listing 1.5.
Listing 5.22. Code Added to the Java Activity File HelloWorldAppActivity.java
package com.androidunleashed.helloworldapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.util.Log;

public class HelloWorldAppActivity extends Activity {


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 18
Mobile Application Development
MODULE – 4: Creating the Activity, working with views & Multimedia 22MCA263

setContentView(R.layout.activity_hello_world_app);
TextView mesg = (TextView)findViewById(R.id.message);
mesg.setText("Hello World!");
int a,b,c;
a = 10;
b = 5;
c = a*b;
Log.v("CheckValue1", "a = " + a);
Log.v("CheckValue2", "b = " + b);
Log.v("CheckValue3", "c = " + c);
Log.i("InfoTag", "Program is working correctly up till here");

Log.e("ErrorTag", "Error--Some error has occurred here");


}
}

When we place these breakpoints, a blue dot appears on the left, indicating that the
breakpoints were successfully inserted (see Figure 5.17).

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 19


Mobile Application Development
MODULE – 4: Creating the Activity, working with views & Multimedia 22MCA263

b). Using the Debug Perspective


When the application switches from the Java to the Debug perspective, you see the callback stack,
console, code view, and variables, as shown in Figure 5.19.

Figure 5.19. The Debug perspective window showing different panes

The following panes are visible by default in Debug perspective:


• Debug—On the top left, this pane displays the application being debugged, along with its
currently running threads.
• Variables—Displays values of the variables at the specific breakpoints.
• Breakpoints—Lists all the breakpoints inserted in the code.
• Editor—At the middle left, this pane displays the application code pointing to the breakpoint
where the application is currently suspended.
• Outline—At the center right, this pane lists the imports, classes, methods, and variables used in
the application. When we select an item in the Outline pane, the matching source code in
the Editor pane is highlighted.
• Console—At the bottom left, the pane displays the status of emulator/device activity, such as the
launching of activities.
• LogCat—At the bottom right, this pane displays the system log messages.

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 20


Mobile Application Development
MODULE – 4: Creating the Activity, working with views & Multimedia 22MCA263

4.6. Displaying and Fetching Information Using Dialogs and Fragments

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?


We usually create a new activity or screen for interacting with users, but 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. We learned to work with the ProgressBar control in Chapter 4, “Utilizing
Resources and Media.”
• TimePickerDialog—A dialog that enables you to set and select a time with
a TimePicker 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.

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 21


Mobile Application Development
MODULE – 4: Creating the Activity, working with views & Multimedia 22MCA263

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


• showDialog()—Displays a dialog and creates a dialog if one does not exist. Each dialog has a
special dialog identifier that is passed to this method as a parameter.
• onCreateDialog()—The callback method that executes when the dialog is created for the first
time. It returns the dialog of the specified type.
• onPrepareDialog()—The callback method used for updating a dialog.
• dismissDialog()—Closes the dialog whose dialog identifier is supplied to this method. The
dialog can be displayed again through the showDialog() method.
• removeDialog()—The dismissDialog() method doesn’t destroy a dialog. The dismissed dialog
can be redisplayed from the cache. If we do not want to display a dialog, we can remove it
from the activity dialog pool by passing its dialog identifier to the removeDialog() method.
All these methods are deprecated, with the new preferred way being to use the DialogFragment
with the FragmentManager (explained later in the chapter). Older platforms should use the
compatibility library to use DialogFragment and the FragmentManager.

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

Methods of the AlertDialog.Builder Subclass

The methods of the AlertDialog.Builder are


• setTitle() and setIcon()—For specifying the text and icon to appear in the title bar of the
dialog box.
• setMessage()—For displaying a text message in the dialog box.
• setPositiveButton(), setNeutralButton(), and setNegativeButton()—For configuring the
following three buttons:
• Positive button—Represents the OK button.
• Negative button—Represents the Cancel button.
• Neutral button—Represents a button to perform a function other than OK or Cancel.

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 22


Mobile Application Development
MODULE – 4: Creating the Activity, working with views & Multimedia 22MCA263

Listing 6.1. The Layout File activity_alert_dialog_app.xml After Adding the Button 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">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id = "@+id/click_btn"
android:text = "Click for Alert Dialog" />
</LinearLayout>

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 23


Mobile Application Development
MODULE – 4: Creating the Activity, working with views & Multimedia 22MCA263

Getting Input via the Dialog Box

We modify our current Android project AlertDialogApp to get input from the user. We make
the following changes to the application:
• Dynamically create an EditText control and set it as part of the AlertDialog to prompt the
user for input.
• Add a TextView control to the layout file to display the data entered by the user
in AlertDialog.
Listing 6.3. The Layout File activity_alert_dialog_app.xml After 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" >
<Button
android:id = "@+id/click_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text = "Click for Alert Dialog"/>
<TextView
android:id = "@+id/response”
android:layout_width="match_parent"
android:layout_height="wrap_content" />

</LinearLayout>

We can see that the newly added code defines a response TextView control in the layout file. Next
we add code to the Java Activity file AlertDialogAppActivity.java to do the following tasks:
• Dynamically create an EditText control and set it as the content of the AlertDialog.
• Access the TextView control from the layout file main.xml and map it to a TextView object.
• Fetch the name entered by the user in the EditText control and assign it to
the TextView object for displaying a welcome message.
• Register an event listener for the Cancel button. Recall that the purpose of the Cancel button
is to cancel the operation and terminate the AlertDialog.

To perform all these tasks, the code shown in Listing 6.4 is added to AlertDialogAppActivity.java.
Only the code in bold is newly added; the rest is the same as we saw in Listing 6.2.

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 24


Mobile Application Development
MODULE – 4: Creating the Activity, working with views & Multimedia 22MCA263

Listing 6.4. Code Written into the Java Activity File AlertDialogAppActivity.java
package com.androidunleashed.alertdialogapp;
import android.app.Activity;
---
import android.widget.EditText;
import android.widget.TextView;
---
public class AlertDialogAppActivity extends Activity implements OnClickListener {
TextView resp;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.Alert_dialog_app);
resp = (TextView)this.findViewById(R.id.response);
Button b = (Button)this.findViewById(R.id.click_btn);
b.setOnClickListener(this);
}
@Override
public void onClick(View v) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Alert window");
alertDialog.setIcon(R.drawable.ic_launcher);
alertDialog.setMessage("Enter your name ");
final EditText username = new EditText(this);
alertDialog.setPositiveButton("OK", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int buttonId) {
String str = username.getText().toString();
resp.setText("Welcome "+str+ "!");
return;
}
});
alertDialog.setNegativeButton("Cancel", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int buttonId) {
return;
}
});
alertDialog.show();
}
}

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 25


Mobile Application Development
MODULE – 4: Creating the Activity, working with views & Multimedia 22MCA263

Fragments

 What is a fragment?
o The size of the screen changes when a device is oriented from portrait to landscape mode. In
landscape mode, the screen becomes wider and shows empty space on the right. The height becomes
smaller and hides the controls on the bottom of the display. There is a difference in screen sizes
between the Android phone and Android tablet, as well. Android tablets have a 7–10 inch display,
whereas Android phones are in the range of 3–5 inches.
o A fragment is a combination of an activity and a layout and contains a set of views that make up an
independent and atomic user interface. For example, one or more fragments can be embedded in the
activity to fill up the blank space that appears on the right when switching from portrait to landscape.
Similarly, the fragments can be dynamically removed if the screen size is unable to accommodate
the Views. That is, the fragments make it possible for us to manage the Views depending on the
target device.

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 26


Mobile Application Development
MODULE – 4: Creating the Activity, working with views & Multimedia 22MCA263

 The Life Cycle of a Fragment

Fig: Lifecycle of a Fragment

The life cycle of a fragment includes several callback methods, as listed here:
o onAttach()—Called when the fragment is attached to the activity.
o onCreate()—Called when creating the fragment. The method is used to initialize the items of the
fragment that we want to retain when the fragment is resumed after it is paused or stopped. For
example, a fragment can save the state into a Bundle object that the activity can use in
the onCreate() callback while re-creating the fragment.
o onCreateView()—Called to create the view for the fragment.
o onActivityCreated()—Called when the activity’s onCreate() method is returned.
o onStart()—Called when the fragment is visible to the user. This method is associated with the
activity’s onStart().
o onResume()—Called when the fragment is visible and is running. The method is associated with
the activity’s onResume().
o onPause()—Called when the fragment is visible but does not have focus. The method is attached to
the activity’s onPause().
o onStop()—Called when fragment is not visible. The method is associated with the
activity’s onStop().
o onDestroyView()—Called when the fragment is supposed to be saved or destroyed. The view
hierarchy is removed from the fragment.
o onDestroy()—Called when the fragment is no longer in use. No view hierarchy is associated with
the fragment, but the fragment is still attached to the activity.
o onDetach()—Called when the fragment is detached from the activity and resources allocated to the
fragment are released.

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 27


Mobile Application Development
MODULE – 4: Creating the Activity, working with views & Multimedia 22MCA263

A fragment also has a bundle associated with it that serves as its initialization arguments. Like an
activity, a fragment can be saved and later automatically restored by the system.

To define a ListView control in the first fragment, the code shown in Listing 6.12 is written into the
XML file, fragment1.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/fruits_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="false"/>
</LinearLayout>

Listing 6.14. Code Written into the Java Class File Fragment1Activity.java
import android.app.Fragment;
----
public class Fragment1Activity extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
------ }
}

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 28


Mobile Application Development
MODULE – 4: Creating the Activity, working with views & Multimedia 22MCA263

Multimedia

Android supports multimedia by using the open source multimedia system called OpenCORE from
PacketVideo Corporation. OpenCORE provides the foundation for Android’s media services, which
Android wraps in an easy-to-use API. In addition to the OpenCORE framework, the Android platform is
migrating to a Google-written multimedia framework named Stagefright. Both frameworks are provided in
version 2.2 (Froyo) and in subsequent versions of the SDK. It’s anticipated that most, if not all, of the
multimedia functionality will be handled by the Stagefright code base.

4.7. Playing Audio,

most basic need for multimedia on a cell phone is the ability to play audio files, whether new ringtones,
MP3s, or quick audio notes. Android’s Media Player is easy to use.

Programming Audio Playback


So, how do you play back audio? As shown in the following code snippet, there are four ways to
instantiate a new player object:
Context appContext = this;
MediaPlayer resourcePlayer = MediaPlayer.Create(appContext,
Resources.Raw.my_audio);
MediaPlayer filePlayer = MediaPlayer.Create (appContext, Android.Net.Uri.parse ("file://"+
Android.OS.Environment.ExternalStorageDirectory
+"/localfile.mp3"));
MediaPlayer urlPlayer = MediaPlayer.Create(appContext,
Android.Net.Uri.parse("http://site.com/audio/audio.mp3"));
MediaPlayer contentPlayer = MediaPlayer.Create(appContext,
Settings.System.DefaultRingtoneUri);

You can see from this snippet that the four ways to instantiate a MediaPlayer object are to use the
static Create function and pass in the application context and one of the following additional
parameters:
 A resource identifier (Resources.Raw.my_audio)
 A URI to a local file using the file:// schema
(“file://”+ Android.OS.Environment.ExternalStorageDirectory +”/localfile.mp3)
 A URI to an online audio resource as a URL (http://site.com/audio/audio.mp3)
 A URI to a local content provider row (Settings.System.DefaultRingtoneUri)

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 29


Mobile Application Development
MODULE – 4: Creating the Activity, working with views & Multimedia 22MCA263

The following program illustrates how to play back audio using each of these four techniques. First,
create a new default project using SimpleAudioPlayback as the project name and solution name.
After creating the new project, edit the strings resources as follows:

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


<resources>
<string name="PlayFromId">Play Music with Resource Id</string>
<string name="PlayFromNet">Play Music from Internet</string>
<string name="PlayFromFile">Play Music from File</string>
<string name="PlayFromProvider"> Play Music from Content Provider</string>
<string name="ApplicationName">SimpleAudioPlayback</string>
</resources>

Another point is that instead of using the static MediaPlayer.Create function to instantiate the media
player, you could use the new operator to create a new MediaPlayer object and then assign the related
values to the MediaPlayer object. The following snippet shows this methodology:

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 30


Mobile Application Development
MODULE – 4: Creating the Activity, working with views & Multimedia 22MCA263

Capturing audio

Listing 11.16. Setting up recording of audio and video

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 31

You might also like