0% found this document useful (0 votes)
20 views53 pages

III B.tech II Sem Mad Unit-4 Lecture Notes

This document provides a detailed guide on using ListView and Spinner controls in Android mobile application development, focusing on selection widgets and debugging. It outlines how to create and populate ListView using string resources and ArrayAdapters, including examples of code implementation. Additionally, it describes how to extend ListActivity for easier ListView management and introduces Spinner controls for dropdown selections.

Uploaded by

Vits21 3504
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views53 pages

III B.tech II Sem Mad Unit-4 Lecture Notes

This document provides a detailed guide on using ListView and Spinner controls in Android mobile application development, focusing on selection widgets and debugging. It outlines how to create and populate ListView using string resources and ArrayAdapters, including examples of code implementation. Additionally, it describes how to extend ListActivity for easier ListView management and introduces Spinner controls for dropdown selections.

Uploaded by

Vits21 3504
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

III.

BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

UNIT- IV(A)

USING SELECTION WIDGETS AND DEBUGGING

Using ListView:
 ListView is used to display a list of vertically scrolling items, allowing user to select one or more of
them. Several attributes can be used to configure this control. Some of them are listed below.
Attribute Description
android:entries Used to refer to an array resource for displaying options in ListView.
Used to define the number of items that are selectable from ListView.
Valid values are
none – Doesn’t allow selection of any option from the ListView
android:choiceMode
singleChoice – Allows selection of a single option from the ListView
multipleChoice – Allows selection of more than one option from the
ListView
Used to allow selection of more than one item in a custom selection
multipleChoiceModal
mode
When set to true, selector (an orange bar) is drawn over selected item.
android:drawSelectorOnTop Otherwise, selector is drawn behind selected item. Default value is
false.
Used to set the transcript mode for the list. The transcript mode helps
in deciding whether we want the list to automatically scroll to bottom.
The valid values are
android:transcriptMode disabled – Disables the transcript mode(default value). The ListView
does not scroll automatically.
normal – ListView automatically scrolls to the bottom when a new
item is added to the adapter and a notification is generated.
alwaysScroll – 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"/>

1
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
 Above sample defines a ListView with ID list, whose items are populated by the string array fruits.
Only one item is selectable from the ListView. No selector appears on the top of the ListView, and it
also scrolls to the bottom when a new item is added to the data source.
 For creating ListView controls, we can use either of the following methods:
1. The regular Activity base class
2. An activity that extends android.app.ListActivity

Creating a ListView with an 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:
1. By ListView through a string resource
2. By ListView through Adapter

Populating ListView through String Resource


 To understand ListView, create a new Android project called ListViewApp with two controls:
ListView and TextView. ListView is populated through string resources to display a list of items for
user to select from. The item or option selected from ListView is displayed via TextView control.
 Open the String resource file /res/values/strings.xml, and add a string-array structure called fruits
that list various fruits that we want to display via the ListView control. After we add a string-array,
the strings.xml file appears as shown below.
<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>Orange</item>
<item>Grapes</item>
<item>Banana</item>
</string-array>
</resources>
 After we define fruits, Open the layout file main.xml and define ListView and TextView in
activity_iist_view_app.xml as shown below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"

2
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
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>
 We see that ListView and TextView controls are assigned resource IDs fruits_list and selectedopt.
To populate ListView, string-array fruits are assigned to ListView through android entries attribute.
 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 write the code shown below into the Java activity file ListViewAppActivity.java.
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.OnItemClickListener;
import android.view.View;
public class ListViewAppActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view_app);
final String[] fruitsArray = getResources().getStringArray(R.array.fruits);
final TextView selectedOpt=(TextView)findViewById(R.id.selectedopt);
ListView fruitsList = (ListView)findViewById(R.id.fruits_list);
fruitsList.setOnItemClickListener(new OnItemClickListener() {
@Override

3
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
selectedOpt.setText("You have selected "+fruitsArray[position]);
}
});
}
}
 The String-array fruits from the resource file strings.xml is accessed and assigned to the string array
fruitsArray, TextView selectedopt and the ListView fruits_list are captured from the layout file and
assigned to the objects selectedopt and fruitsList.
 To take an action when an item is selected from ListView, setOnItemClickListener() method is
passed a new AdapterView. OnItemClickListener() anonymous instance implements OnItemClick()
callback method , which is executed when an item is selected from the ListView.
 In the OnItemClick() method, we find the index location(position) of the selected item, use it to
access the array element from the string array fruitsArray, and display it through the TextView
object selectedOpt. When the application is run, we see outputs as shown below.

Adapters:
 Android provides a framework of adapters (also known as data adapter) that are used to provide a
data source of displaying content in the form of choice in selection widgets. The data source refers
to the content, including elements in arrays and data in database tables.
 The adapters serve two purposes.
1. First, they provide the data source for selection widgets
2. Second, they convert individual elements of data into specific views to be displayed inside
the selection widget.
 Android provides many basic adapters such as ListAdapter, ArrayAdapter and CursorAdapter. We
can also create our own adapter.

4
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
Population ListView through the ArrayAdapter:
 The ArrayAdapter is one of the Adapters provided by android that provides data source to selection
widgets and also casts the data into specific view(s) to be displayed inside the selection widgets.
 To understand ArrayAdapter to populate the ListView control, Create a new android project called
ListViewdemo1 with two controls TextView and ListView by writing the code shown below
<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:drawSelectorOnTop="false"/>
<TextView
android:id="@+id/selectedopt"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
 Next, we need to write code into the java activity file ListViewDemo1Activity.java as shown below
to serve the following purpose:
1. Create an arrayadapter through a string array and assign it to the ListView for displaying items
2. Display the item selected from the ListView in the TextView
packge com.androidunleashed.ListViewdemo1;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.ListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.view.View;
import android.widget.ArrayAdapter;
public class ListViewDemo1Activity extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

5
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
setContentView(R.layout.activity_list_view_demo1);
final String[] fruits={"Apple", "Mango", "Orange", "Grapes" , "Banana"};
final TextView selectedOpt=(TextView)findViewById(R.id.selectedopt);
ListView fruitsList = (ListView)findViewById(R.id.fruits_list);
final ArrayAdapter<String> arrayAdpt=new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_1,fruits);
fruitsList.setAdapter(arrayAdpt);
fruitsList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
selectedOpt.setText("You have selected "+fruits[position]);
}
});
}
}
 An ArrayAdapter is the simplest of the adapters and acts as the data source for the selection widgets
ListView, GridView and so on. AarrayAdapter makes use of the TextView control to represent the
child Views in a View. An ArrayAdapter is created through the following code:
ArrayAdapter<String> arrayAdpt=new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_1,fruits);
 It create an ArrayAdapter called arrayadpt that can display the elements of the specified array,
fruits,via the text control. The ArrayAdapter constructor consist of the following:
1. this(the current context) – activity is an extention of the context class, We use the current
instance as the context.
2. android.R.layout.simple_list_item_1 – It will be used for displaying each item in the
ListView to TextView. the elements of the array that is specified next needs to be wrappped or
cast in a view before being assigned to any selectoin widget for display.
3. array – the data source – an array of string for the ListView.
 We see that the ListView and TextView controls from the layout files are accessed and mapped to
the objects fruitsList and selectedopt. The arrayAdpt ArrayAdapter containing the elements of the
fruits array in TextView form is assigned to the ListView control for displaying choices to the user.
 The OnItemClickListener interface implements a callback method, onItemClick() . The reference of
an anonymous class is passed to the fruitsList ListView to invoke the callback method
onItemcClick() when any of the items in ListView is clicked.
 In the onItemClick() method, the item selected in the ListView is displayed via the TextView
control selectedopt. When we run the application, we get outputs as shown below.

6
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

Creating ListView by Extending ListActivity:


 ListActivity already contains a ListView and we just need to populate it by calling setListAdapter()
method. Let’s create a new application ListViewDemo2 with ListView and TextView controls to
examine creation of ListView by extending ListActivity class and Write code as shown below in 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="wrap_content">
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="false"/>
<TextView
android:id="@+id/selectedopt"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>

 ID assigned to ListView control defined in xml must be @android:id/list; Otherwise, ListActivity


will not be able to identify it. To populate ListView and to display the item selected from it through
the ListView control, write the code into ListViewDemo2Activity.java as shown below.

7
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
pacakage com.androidunleashed.ListViewdemo2;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.ListView;
import android.view.View;
import android.widget.ArrayAdapter;
public class ListViewDemo2Activity extends ListActivity{
TextView selectedOpt;
final String[] fruits={"Apple", "Mango", "Orange", "Grapes" , "Banana"};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view_demo2);
selectedOpt = (TextView) findViewById(R.id.selectedopt);
final ArrayAdapter<String> arrayAdpt = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_single_choice, fruits);
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
setListAdapter(arrayAdpt);
}
@Override
public void onListItemClick(ListView parent, View v, int position, long id) {
super.onListItemClick(parent,v,position,id);
selectedOpt.setText("You have selected "+fruits[position]+position);
}
}
 We see that an ArrayAdapter, arrayAdpt, is wrapping an array of strings. The ListView is populated
by assigning arrayAdpt to it via setListAdapter() method. onListItemClick() method is overridden to
define the action that we want to take place when any item in the ListView is clicked.
 onListItemClick() method is executed when an item from ListView is selected. In
onListItemClick() method, the item selected by the user from the ListView is displayed through
TextView selectedopt.
 The simple_list_item_single_choice and the ListView.CHOICE_MODE_SINGLE allow us to select
only a single item at a time. The chosen item is displayed through the ListView control.
 To enable users to select multiple items from the ListView, replace simple_list_item_single_choice
with simple_list_multiple_choice and change the choice mode from ListView.CHOICE_MODE_
SINGLE to ListView.CHOICE_MODE_MULTIPLE.

8
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
 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);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
 on running the application, we get outputs as shown below

Using the Spinner Control:


 The Spinner is similar to a drop-down lists that displays a list of items, allowing the user to select
the desire item. 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:


 We 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, we define a string resource. Open the
strings.xml file from the res/values folder and define a string resource in it.
<resources>
<string name="app_name">SpinnerApp</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_spinner_app">SpinnerAppActivity</string>
<string name="choose_msg">Choose a fruit</string>
</resources>
 We see that a string resource called choose_msg is defined to represent the text choose a fruit. Next,
we need to define resource for displaying options in spinner control. We use a string-array to do this.
 To add a new xml file to the res/values folder, right-click on the res/values folder in the package
explorer window and select the new, android xml file option. Call the file arrays and then click the
finish button. The code written in arrays.xml is shown below

9
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
<?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>
 We see that a string-array called fruits is defined, consisting of five elements, Apple, Mango,
Orange, Grapes and Banana. These array elements are used to display options in the spinner control.
To display spinner control, write code in layout file activity_spinner_app.xml, as shown below.
<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">
<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>

 We can see that a spinner control and TextView control are defined. 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 string that appears at the top of the spinner control to guide the user like
choose a fruit. The entries attribute is used to specify the data source to populate the spinner control.
We set the entries attribute to string array fruits that we just defined in arrays.xml.
 We want item string selected from the spinner control by the user to appear in the TextView. To do,
write the code shown below in spinnerAppActivity.java

10
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
package com.androidunleashed.Spinnerapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Spinner;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
public class SpinnerAppActivity extends Activity{
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner_app);
final TextView selectedOpt=(TextView)findViewById(R.id.selectedopt);
Spinner spin=(Spinner)findViewById(R.id.spinner);
final String[] fruitArray=getResources().getStringArray(R.array.fruits);
spin.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent, View v,int position,long id) {
selectedOpt.setText("you have selected" + fruitArray[position]);
}
public void onNothingSelected(AdapterView<?> parent){
selectedOpt.setText("");
}
});
}
}
 Spinner control ID is captured from layout file and is mapped to spinner object spin and TextView is
captured and mapped to TextView object selectedOpt. The selectedOpt object is used to display the
item selected from the spinner control.
 An event listener, setOnItemSelectedListener, is attached to the spinner control. When an item from
the spinner is selected, the onItemSelected() callback method that was specified in the anonymous
class passed to the spinner’s setOnItemSelectedListener .
 The onItemSelected() callback method retrieves the item that was selected in spinner and displays it
through TextView by specifying its index location(position of item selected) from spinner control.
 The onNothingSelected() method is implemented to make the selectedOpt TextView blank; that is, it
removes any previous message being displayed through TextView control.
 When we run the application, we get output as shown below

11
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

Populating a Spinner through ArrayAdapter:


 Before populating the spinner control with arrayadapter, we make it empty by removing the
android:entries attribute from layout file main.xml. After we remove the entries attribute layout file
appears as shown below.
<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">
<Spinner android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:prompt="@string/choose_msg" />
<TextView android:id="@+id/selectedopt"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
 To create an ArrayAdapter and assign it to the spinner control for populating it, the code shown
below is written into the Java activity file spinnerAppActivity.java.
package com.androidunleashed.Spinnerapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Spinner;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
12
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
import android.widget.AdapterView.OnItemSelectedListener;
public class SpinnerAppActivity extends Activity{
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner_app);
final TextView selectedOpt=(TextView)findViewById(R.id.selectedopt);
final String[] fruits={"Apple","Mango","Orange","Grapes","Banana"};
Spinner spin=(Spinner)findViewById(R.id.spinner);
ArrayAdapter<String> arrayAdpt=new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,fruits);
spin.setAdapter(arrayAdpt);
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
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(" ");
}
});
} }
 An ArrayAdapter<string> object called arrayAdpt is created from the string array fruits, and a
standard simpie_spinner_item view is used to display each bound element in the Spinner control.
 The arrayAdpt ArrayAdapter is assigned to the Spinner control for populating it. After we select an
item in the spinner control, the onItemSelected() callback method is executed to display the selected
item through the TextView control. After we run the application, we get output as shown in below

13
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
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
simpie_list_item_1 or simpie_dropdown_item_1.
 To understand AutoCompleteTextView, create a new application called AutoCompleteApp. Define
2 controls, TextView and AutoCompleteTextView, in layout file activity_auto_complete_app.xml,
as shown below.
<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">
<TextView
android:text="Enter product name:"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<AutoCompleteTextView
android:id="@+id/product_name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
 To display a list of suggestions, we need to create an ArrayAdapter and associate it with
AutoCompleteTextView. To do, code shown below is written into AutoCompleteAppActivity.java
package com.androidunleaashed.autocompleteapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.AutoCompleteTextView;
import android.widget.ArrayAdapter;
public class AutoCompleteAppActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto_complete_app);
String[] products={Camera","Handi Cam","Cell phone","Laptop","Car"};

14
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
ArrayAdapter<String> arrayAdapt=new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line,products);
AutoCompleteTextView productNames=(AutoCompleteTextView)
findViewById(R.id.product_name);
productNames.setThreshold(1);
productNames.setAdapter(arrayAdapt);
}
}
 We see that an Arrayadapter called arrayAdapt, is created and the array elements of the product
string array are set to display in it. The array elements are wrapped in a simple_dropdown_
item_1line view to show the suggestions.
 The ArrayAdapter arrayAdapt is then associated with AutoCompleteTextView, using setAdapter()
method. The setThreshold() method is used to indicate minimum number of characters that a user
must enter before suggestions are displayed. On running application, we get output as shown below

Using the GridView Control:


 The GridView is a ViewGroup used to display text and image data in the form of a rectangular,
scrollable grid. To display data in the grid, we first define a GridView control in the xml layout, and
then bind the data that we want to display to it using the ArrayAdapter.
 Let’s create a new android project called GridViewer. In this application, we display certain strings
arranged in a rectangular grid. When a user selects any of string, its name is displayed. We write
code shown in below in activity_grid_viwe_app.xml to define a TextView and GridView 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="wrap_content">

15
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
<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_height="match_parent"
android:verticalSpacing="2dip"
android:horizontalSpacing="5dip"
android:numColumn="auto_fit"
android:stretchMode="columnWidth"
android:gravity="center" />
</LinearLayout>

GridView Attributes:
 The number of rows displayed through GridView is dependent on number of elements supplied by
attached adapter. The size and number of columns is controlled through following attributes:
1. android:numColumn – defines the number of column. if we supply a value, auto_fit, android
computes the number of columns based on available space.
2. android:verticalSpacing and android:horizontalSpacing – defines the amount of whitespace
between the item in the grid.
3. android:columnWidth – defines th width of each column
4. android:stretchMode – the attributes determined whether the column can stretch or expand to
take up the available space. the valid for this attributes are:
 none – does not allow the column to stretch or expand
 columnWidth – makes the column take up all available space
 spacingWidth – makes the whitespace between columns take up all available space.
 Define TextView and GridView controls with the ids selectedopt and grid. The GridView displays
items or data in a rectangular grid and TextView displays items selected by the user from GridView.
 Horizontal and Vertical spacing among items in GridView is set to 5dpi and 2dpi. The width of a
column in GridView is set to 130dpi.The number of columns in the GridView is determined by the
number of columns that can be accommodated in the available space.
 To display content in the GridView and to display the item selected from the GridView in
TextView, write the code shown below into GridViewAppActivity.java.

16
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
package com.androidunleashed.GridViewapp;
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.widget.AdapterView.OnItemClickListener;
import android.view.View;
public class MainActivity extends Activity implements OnItemClickListener{
TextView selectedOpt;
String[] fruits={"Apple","Mango","Banana","Grapes","Orange","Pineapple","
Strawberry","Papaya","Guava","promegranate","watermelon","Chickoo"};
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectedOpt=(TextView)findViewById(R.id.selectedopt);
GridView g=(GridView)findViewById(R.id.grid);
ArrayAdapter<String> arrayAdpt=new ArrayAdapter<String> (this,
android.R.layout.simple_list_item_1, fruits);
g.setAdapter(arrayAdpt);
g.setOnItemClickListener(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 ("");
}
}
 We access the TextView with the selectedopt ID from the layout and map it to the selectedOpt
TextView object. We use selectedOpt object to display item selected by the user in the GridView.
 An array of strings called fruits is created. We create an ArrayAdapter called arrayadpt that makes
elements in string array fruits appear in the TextView form. The ArrayAdapter is set to GridView
via the setAdapter() method to display its content via GridView.

17
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
 By attaching ItemClickListener to GridView, when any item displayed through GridView is clicked,
onItemClick() callback method is invoked. Through onItemClick() method, we display the item
selected by the user in the GridView via the TextView selectedOpt.
 On running the application, we get output as shown below. We can accommodate more columns by
android:coloumnWidth. For example, modifying android:coloumnWidth to accomodates three
coloumns in the GridView: android:coloumnWidth=”100dip.
 After we set the column width to 100dip, three columns appear in the GridView as shown below

Displaying Images in GridView:


 To display content in the GridView control, we use Adapters, which provide the content to display
to controls. The content can be fetched from sources such as arrays, databases, or other data sources.
 In this section, we 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 image filenames that we want to display through the GridView control are prod1.png,
prod2.png, prod3.png and prod4.png, copy them into the four res/drawable folders.
 In this application, we want a message to be displayed showing image number of picture displayed
via GridView control. Our application add two controls: TextView control for displaying selected
image number and GridView controls in activity_grid_image_app.xml as shown below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/selectedopt"

18
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
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>
 We see that TextView and GridView controls are assigned IDs selectedopt and grid. Set width of
GridView columns is 100dip and horizontal and vertical spacing between columns is 2 dip.
 To display images in the GridView control and also tell us which image is selected by the user, write
the code shown below in activity file GridimageAppActivity. java.
com.androidunleashed.gridimageapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.GridView;
import android.view.View;
import android.widget.ImageView;
import android.content.Context;
import android.widget.BaseAdapter;
import android.widget.AdapterView;
import android.widget.TextView;
import android.view.ViewGroup;
public class GridImageAppActivity extends Activity implements
AdapterView.OnItemClickListener{
TextView selectedOpt;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid_image_app);
selectedOpt=(TextView)findViewById(R.id.selectedopt);

19
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
GridView g=(GridView)findViewById(R.id.grid);
g.setAdapter(new ImageAdapter(this));
g.setOnItemClickListener(this);
}
public void onItemClick(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 getItem(int position){
return position;
}
public long getItemId(int position){
return position;
}
public View getView(int position,View convertview,ViewGroup parent){
ImageView ImageView=new ImageView(contxt);
ImageView.setImageResource(images[position]);
ImageView.setLayoutParams(new GridView.LayoutParams(100,120));
return ImageView;
}
}
}

20
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
 The TextView and GridView controls define in layout file with IDs selectdopt and grid are fetched
and mapped to the object selectedOpt and g. To create our customer adapter, ImageAdapter, we
extend the base adapter abstract class that is provided by android.
 To display the adapter images via GridView, ImageAdapter is set to the GridView object, g, via the
setAdapter() method. We instantiate our ImageAdapter, passing it the application context.
 Array called images is defined containing the resource IDs of images that we copied into
res/drawable folders. Images array acts as a data source, providing images that we want to display.
 The adapter method getCount(), getItem(), and getItemId() are used to determine the number of
images to be displayed. In getView() method, member context is used to create a new ImageView.
 The ImageView is assigned an image from images arrays that we defined earlier and the height and
weight of the images are set by settings the GridView.LayoutParams() method.
 An AdapterView.OnItemClickListerner event handler is attached to the GridView, so that when any
images displayed through GridView is clicked, the callback onItemClick() method is invoked.
 In the onItemClick()method we return the position of the clicked view. The position is zero based,
so it is incremented by 1 before displaying the image number via the selectedopt TextView.
 on running the application, we see output as shown below

Creating an Image Gallery Using The ViewPager Control:


 The ViewPager control (android.support.v4.view.viewpager) helps in showing data, which may be
text, image, and so on in the form of page with the horizontal swiping behavior.
 To identify and to keep track of the page being displayed ViewPager, a key object is associated with
each of them. The ViewPager need a data adapter to define and load the data for each page.
 The data adapter that is used to define the data for each page to be displayed through the viewpager
control is the PagerAdapter (android.support.v4.view.PagerAdapter)class.
 While implementing the PagerAdapter , we must override the following methods.

21
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
1. instantiateItem(View container, int position) – used for creating and instantiating the page and
adding it to the container. Using the LayoutInflater service, the method also inflates the
appropriate layout and adds it to the specified container.
Syntax: publilc ObjectInstantiateItem(View container, int position)
2. container – represent the container in which the page has to be displayed
3. position – represents the position of the page to be instantiated
4. destroyItem(View container, int position, Object object) – used for removing the page of the
specified position from container
5. isViewFormObject(View view, Object object) – determined whether the specified page is
associated with a specific key object
6. getCount() – defines the size of the paging range, that is, the count of the number of the page
 The position of the page is zero based by default, the next page to the right is posiotion1,and soon.
we can also set the initial position of the pager through the setCurrentItem() method
 To listen to change in the state of the selected page, we need to define a class that extends
SimpleOnPageChangeListener. When a page from the ViewPager is selected, the call back method
onPageSelected() is called.
 Create application called viewpagerapp that displays a scrollable image gallery, and when an image
is selected from gallery, selected image number id displayed. After copying image, we define two
controls; TextView and ViewPager, in layout file activity_view_pager_app.xml as shown below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical">
<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_width="match_parent"
android:layout_height="100dip"
android:layout_marginTop="25dip"/>
</LinearLayout>

22
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
 We see that the TextView and ViewPager control are assigned that ids sselectedopt and viewpager.
To make the image gallery appear at the distance of 25dip from the top of the liner layout container,
android:layout_marginTop attribute is set to 25dip.
 The height of images being displayed to 100dip, android:layout_height is set to 100dip. To display
images in the viewer control the image number selected by the user ,write the code shown below in
viewpagerappactivity.java

package com.androidunleashed.viewpagerapp;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.PagerAdapter;
import android.widget.TextView;
import android.view.View;
import android.widget.ImageView;
import android.support.v4.view.ViewPager.SimpleOnPageChangeListener;
public class ViewPagerAppActivity extends AppCompatActivity{
public TextView selectedOpt;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_pager_app);
selectedOpt=(TextView)findViewById(R.id.selectedopt);
ViewPager viewPager=(ViewPager)findViewById(R.id.viewpager);
viewPager.setAdapter(new ImageAdapter());
viewPager.setOnPageChangeListener(new PageListener());
}
public class ImageAdapter extends PagerAdapter{
Integer[] images={
R.drawable.prod1,
R.drawable.prod2,
R.drawable.prod3,
R.drawable.prod4,
R.drawable.prod5
};
public Object instantiateItem(View container,int position){
ImageView view=new ImageView(MainActivity.this);

23
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
view.setImageResource(images[position]);
((ViewPager)container).addView(view,0);
return view;
}
@Override
public int getCount(){
return images.length;
}
@Override
public void destroyItem(View arg0,int arg1,Object arg2){
((ViewPager)arg0).removeView((View)arg2);
}
@Override
public boolean isViewFromObject(View arg0,Object arg1){
return arg0==((View) arg1);
}
}
private class PageListener extends SimpleOnPageChangeListener {
public void onPageSelected(int position) {
selectedOpt.setText("you have selected the page number " + position);
}
}
}

 The TextView and PageViewer controls defined in layout file with IDs selectedopt and viewpager
are fetched and mapped to objects selectedOpt and viewPager. We create our custom adaptor,
ImageAdaptor, by extending the PageAdaptor class.
 The ImageAdaptor is set to the ViewPager object, viewPager to display adaptors content (images via
the ViewPager control).An array called images is defined, containing the resource IDs of the images
that we copied into the res/drawable folders.
 The images array acts as a source of images that we want to display. The instantiateItem(),
getCount(), destroyItem(), and isViewFromObject() methods define the pages, determine the
number of images to be displayed via ViewPager,
 A setOnPageChangeListener is attached to the ViewPager so that when any image is selected from
it, the onPageSelected() callback method is invoked, which in turns displays the position of the
clicked image through the TextView control.
 On running the application, we find that all images are displayed the viewpager, as shown below.

24
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

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


 The DDMS is a powerful debugging tool that can be run either by selecting DDMS icon on top-right
corner of Eclipse IDE or by selecting window, open perspective, DDMS option.
 When we run DDMS, automatically connects to the attached Android device or any running
emulator. DDMS helps with a variety of tasks, including
1. Finding bugs in applications running either on an emulator or on the physical device.
2. Providing several services such as port forwarding, on-device screen capture, incoming call,
SMS and location data spoofing.
3. 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.
4. 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 errors(s) occurred.
5. Simulating different types of networks, such as GPRS and EDGE.

25
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
 In the upper-left pane of the DDMS window, we see a devices tab that displays the list of the
Android devices connected to your pc, along with running AVDS. Selecting a VM displays its
information in the right pane. In the devices tab, you see some icons, described here:
1. Debug – used to debug the selected process.
2. Update Heap – Enables heap information of the process. After clicking this icon, use the
Heap icon on the right pane to get heap information.
3. Dump HPROF file – shows the HPROF file that can be used for debugging memory leaks.
4. Cause GC – invokes Garbage Collection.
5. 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.
6. 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.
7. Stop process – stops the selected process.
8. 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 below. Once the image is captured,
it is displayed as shown below.

 The meaning of the buttons shown at the top in the device screen capture dialog box is shown here:
1. Refresh – updates the captured image.
2. Rotate – with each click of this button, captured image rotates 90 degrees in counterclockwise
direction.

26
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
3. Save – saves the captured images as a .png file
4. Copy – copies the captured images to the clipboard
5. Done – closes the device screen capture dialog
 Back to DDMS, on the right pane, we find the following tabs
1. Threads – displays information about the threads within each process, .the following information
about threads is displayed:
 Thread ID – displays the unique ID assigned to each thread
 Status – displays the current status of the thread-whether it is 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
2. Heap – displays the heap information of the process. Select the cause GC button to begin the
garbage collection process. The object type 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.

3. Allocation Tracker – tracks the object allocated to an application. Click the start tracking button,
interact with the application and then click get allocation to see the list of objects allocated to the
application. After we get 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.
4. Network Statistics – helps us in getting information regarding network usage of our application,
that is, when our app made network request, speed of data transfer and other related information
5. File Explore – display the file system on device, as shown below. we can view and delete files
on the device/emulator through the tab. even we can push or pull files from the device using the
two icons, pull a file from the device, and push a file on to the device, that are shown at the top.
To copy the file from the device, select the file in the file explores and clicks the pull a file from

27
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
the device button. the get device file button up prompting us to specify the path and filename
where we want to store the pulled device file. Similarly, to copy a file to the device, click the
push file on to the device button in the file explorer tab. the put file on device dialog box opens
up letting us browse the local disk drive. select the file that we want to copy to the device and
click open button to copy it to the device.

 Right of the file explore tab is the emulator control tab that can be used to simulate incoming phone
calls, SMS messages, or GPS coordinates. To simulate an incoming phone call, select the voice
option, provide the incoming phone number, and click the call button, as shown below. In the
emulator an incoming call appear, prompting the user to answer the call in below. The incoming call
can be ended either by clicking the end button in the emulator or by clicking the hang up button in
the emulator control tab.

 To simulate an SMS message, select the SMS option in the emulator control tab, provide the phone
number, write the message and click the send button, as shown below. In the emulator an incoming
SMS notification appears at the top. we can simulate GPS coordinates manually, via the GPX file or
KML file through the emulator control tab. remember, only GPX1.1 files are supported

28
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

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.
 Place as many breakpoints as you want in our HelloWorldApp application by add a few statements
to its activity file. The statements just perform simple multiplication and display log messages.
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);
setContentView(R.layout.activity_hello_world_app);
TextView mesg = (TextView)findViewById(R.id.message);
mesg.setText("Hello World!");
int a,b,c;
a=10;

29
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
b=5;
c=a*b;
Log.v("CheckValue1","a="+a);
Log.v("CheckValue2","b="+b);
Log.v("CheckValue3","c="+c);
Log.v("Infotag"," program is working correctly up till here");
Log.v("ErrorTag"," error—some error has occurred here");
}
}
 Let’s place breakpoints at the following three statements in the activity file:
c=a*b;
Log.v("CheckValue1","a="+a);
Log.v("CheckValue3","c="+c);
When we place these breakpoint, a blue dot appears on the left, indicating that the breakpoints were
successfully inserted.

 To stop execution at breakpoints, don’t run application; inserted debug it by either pressing F11,
selecting Run, Debug, or right-clicking the project in package Explorer and selecting Debug As,
Android Application.
 During debugging, the application pauses when the first breakpoint is reached. At the breakpoints,
we can highlight variables to see their values and execute certain expression.
 When the application reaches a breakpoint for the first time, a window pops up asking whether we
want to switch to the Debug perspective or not.

Using Debug Perspective:


Read this topic in Textbook Xerox

30
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
UNIT- IV(B)
DISPLAYING AND FETCHING INFORMATION USING DIALOGS AND FRAGMENTS

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:
1. Dialog — The basic class for all dialog types.
2. AlertDialog — A dialog with one, two, or three Button controls.
3. CharacterPickerDialog — A dialog that enables you to select an accented character associated
with a regular character source.
4. DatePickerDiaiog — A dialog that enables you to set and select date with a DatePicker control.
5. ProgressDialog — A dialog that displays a ProgressBar control showing the progress of a
designated operation.
6. TimePickerDialog— A dialog that enables you to set and select 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.
 If the dialog is open, users can interact only with the options and controls in the dialog until it is
closed. Each dialog window is defined within the activity where it will be used. A dialog window
can be created once and displayed several times. It can also be updated dynamically.
 The following is a list of the Activity class dialog methods:
1. 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.
2. onCreateDialog() — The callback method that executes when the dialog is created for the first
time. It returns the dialog of the specified type.
3. onPrepareDialog() — The callback method used for updating a dialog.
4. dismissDialog() — Closes the dialog whose dialog identifier is supplied to this method. The
dialog can be displayed again through the showDialog() method.
5. 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. Older platforms should use the compatibility library to use DialogFragment
and the FragmentManager.

1
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
 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.
 Several dialog window types are available in Android SDK, such as AlertDialog, DatePickerDialog,
and TimePickerDialog.

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 it 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.
example: AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);

Methods of the AlertDialog.Builder Subclass:


 The methods of theAlertDialog.Builder subclass that we can use to configure AlertDialog box are
1. setTitle() and setIcon() — For specifying the text and icon to appear in the title bar of dialog box.
2. setMessage() — For displaying a text message in the dialog box.
3. setPositiveButton(), setNegtiveButton( ) and setNegativeButton() — For configuring 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.

 Let's create an Android application AlertDialogApp to see how AlertDialog is displayed. In this
application, we want to display AlertDialog by clicking Button control, for that write code as shown
below in the layout file activity alert_dialog_app.xml.
<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>

2
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
 To display an AlertDialog, we use theAlertDialog.Builder subclass to create a Builder object. There
after, we configure the dialog with a title, message, and buttons with the Builder object to display on
Screen. To do all this, write code into the AlertDialogAppActivity.java file is as shown below.
package com.androidunleashed.alertdialogapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.view.View;
import android.app.AlertDialog;
import android.content.DialogInterface;
public class AlertDialogAppActivity extends Activity implements OnClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alert_dialog_app);
Button b = (Button)this.findViewById(R.id.click_btn);
b.setOnClickListener(this);
}
@Override
public void onClick(View v) {
AlertDialog.Builder alertDialog=new AlertDialog.Builder(this);
alertDialog.setTitle("Alert window");
alertDialog.setIcon(R.drawable.ic_launcher);
alertDialog.setMessage("This is an alert");
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int buttonId) {
return;
}
});
alertDialog.show();
}
}
 Here we see that the click_btn Button control in the layout file is assigned the caption click for Alert
Dialog. The Button control is captured from the layout file and is mapped to the Button object, b.
 We want the AlertDialog to appear when the click_btn button is clicked; hence an event listener
setOnClickListener, is associated with it. When click_btn is clicked, onClick() method is executed.

3
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
 In onClick() a Builder called alertDialog is created. To display the alert dialog on the screen, we
provide the Context to the builder object. We then set the icon and title for the dialog box.
 A positive button is configured in the dialog with the caption OK. In the button's click handler, we
simply return. The AlertDialog is made visible on the screen through the show() method.
 After running the application, we see output as shown below.

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:
1. Dynamically create an EditText control and set it as part of AlertDialog to prompt user for
input.
2. Add a TextView control to the layout file to display data entered by user in AlertDialog.
 To make it more specific, our application asks the user to input a name through AlertDialog, and
when the user selects the OK button after entering a name, a welcome message is displayed through
the TextView control.
 We also add a cancel button to the AlertDialog, allowing the user to cancel the operation, which
terminates the dialog. The code shown below is added to layout file for defining 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:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/click_btn"
android:text="Click for Alert Dialog"/>

4
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/response"/>
</LinearLayout>
 We can see that the newly added code defines a response TextView control in the layout file. Next
we add code to the AlertDialogAppActivity.java to do the following tasks:
1. Dynamically create an EditText control and set it as the content of the AlertDialog.
2. Access the TextView control from the layout file main.xml and map it to a TextView object.
3. Fetch the name entered by the user in the EditText control and assign it to the TextView object
for displaying a welcome message.
4. 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 below is added to AlertDialogAppActivity.java.
package com.androidunleashed.alertdialogapp;
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.DialogInterface;
public class AlertDialogAppActivity extends Activity implements OnClickListener {
TextView resp;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_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);

5
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
alertDialog.setTitle("Alert window");
alertDialog.setIcon(R.drawable.ic_launcher);
alertDialog.setMessage("Enter your name ");
final EditText username = new EditText(this);
alertDialog.setView(username);
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();
}}
 We see that the TextView control from the layout file is mapped to the TextView object resp. The
message set in the AlertDialog is Enter your name. The dynamically created EditText control
username is set to appear as content in the AlertDialog, allowing users to enter a name.
 When a user selects the OK button after entering a name, a welcome message is displayed, along
with the entered name via the TextView object resp. No action is performed when Cancel is clicked;
we simply terminate the AlertDialog by returning back to the main activity.
 After running the application, we see output as shown below.

6
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
DatePickerDialog:
 DatePickerDialog is used to see and modify the date. We can supply the day, month, and year values
to its constructor to initialize the date initially displayed through this dialog.
 The constructor includes a callback listener to inform the current context when the date has been set
or changed. To initialize the current date to the dialog, we use a calendar instance.
 To try DatePickerDialog, let's create a new Android project DatePickerApp. It contains a TextView
and a Button control. When clicked, the Button control displays the DatePickerDialog, and the
TextView control displays the date set by the user.
 To define the Button and TextView control, let's write the code shown below in the layout file
activity_date_picker_app.xml.
<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/datevw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/date_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set the Date" />
</LinearLayout>
 We see that a TextView and a Button control with the IDs datevw and date_button are defined in the
layout file. The caption set the Date is set to display in the Button control.
 To add action to the application, we need to write some Java code into the activity file
DatePickerAppActivity.java. The code in the activity file does the following:
1. Access the system's current date through the Calendar instance.
2. Display the current system date in the TextView control.
3. Display the DatePickerDialog, initialized to display the current system date when the Button
control is clicked.
4. Access the date set by the user in the DatePickerDialog when its Set button is clicked and
display it through the TextView control.
 To perform all the preceding tasks, the code shown below is written into the Java activity file
DatePickerAppActivity.java.

7
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
packagecom.androidunleashed.datepickerapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Button;
import java.util.Calendar;
import android.app.DatePickerDialog;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.DatePicker;
public class DatePickerAppActivity extends Activity {
private TextView dispDate;
private int yr, mon, dy;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_date_picker_app);
dispDate=(TextView)findViewById(R.id.datevw);
Button dateButton=(Button)findViewById(R.id.date_button);
final Calendar c=Calendar.getInstance();
yr=c.get(Calendar.YEAR);
mon = c.get(Calendar.MONTH);
dy = c.get(Calendar.DAY_OF_MONTH);
dispDate.setText("Current date is: "+(mon+1)+"-"+dy+"-"+yr);
dateButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new DatePickerDialog(DatePickerAppActivity.this, dateListener, yr,mon, dy).show();
}
});
}
private DatePickerDialog.OnDateSetListener dateListener = new
DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth){
yr = year;
mon = monthOfYear;
dy = dayOfMonth;
dispDate.setText("Current date is: "+(mon+1)+"-"+dy+"-"+yr);

8
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
}
};
}
 When a user clicks a button, we want the DatePickerDialog to be invoked so date can be selected. A
date_button Button is captured from the layout and mapped to a Button object dateButton.
 A setOnClickListener event listener is associated with Button so that when it is clicked, callback
method, onClick() is invoked. In onClick() method, a new instance of a DatePickerDialog is created
using the DatePickerDialog constructor and is displayed on the screen.
 We want to initialize the DatePickerDialog to today's date, we use the calendar class to set the
DatePickerDialog control to today's date each time the dialog is shown. An instance of calendar is
then created, initially set to the current date.
 The current year, month, and day are fetched from the calendar instance and passed to the
DatePickerDialog constructor to initialize it to display the current date. The constructor also includes
a callback listener to inform the current context when the date is set or changed.
 The DatePickerDialog provides a callback listener, OnDateChangedListener or OnDateSetListener
that listens for when the user has finished setting the date. This occurs when the user clicks the Set
button in the DatePickerDialog.
 The onDateSet() method is called when the date is set or changed, and we use it to display the set
date through the TextView. After running the application, we see outputs as shown below.

TimePickerDialog:
 TimePickerDialog allows us to set or select time through the built-in Android TimePicker view. We
can set the values of hour and minute with values of hour ranging from 0 through 23 and minutes
from 0 through 59.
 The dialog provides a callback listener, OnTimeChangedListener or OnTimeSetListener,which tells
us when a time is changed or set by the user.

9
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
 We create a new Android project TimePickerApp with two controls, TextView and Button, where
the TextView control displays the current system time and the new time set by the user.
 The Button control is used to invoke TimePickerDialog; when Button control is clicked.To define
TextView and Button, write code shown below into the layout file activity_time_picker_app.xml.
<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/timevw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/time_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set the Time" />
</LinearLayout>
 We see that TextView and Button controls are defined with IDs timevw and time_button. The
caption on the Button control is Set the Time.
 Next, we need to write the code in TimePickerAppActivity.java to perform the following tasks:
1. Invoke the TimePickerDialog when the Button control is clicked.
2. Display the current system time in the TextView control.
3. Use the Calendar instance to initialize TimePickerDialog to display the current system time.
4. Display the newly set time in the TextView control.
 To perform these tasks, write code shown below into the TimePickerAppActivity.java file.
packagecom.androidunleashed.timepickerapp;
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.view.View.OnClickListener;
import android.view.View;
import android.widget.TimePicker;

10
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
public class TimePickerAppActivity extends Activity {
private TextView dispTime;
private int h,m;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate (savedInstanceState);
setContentView(R.layout.activity_time_picker_app);
dispTime=(TextView)findViewById(R.id.timevw);
Button timeButton=(Button)findViewById(R.id.time_button);
final Calendar c=Calendar.getInstance();
h=c.get(Calendar.HOUR_OF_DAY);
m = c.get(Calendar.MINUTE);
dispTime.setText("Current time is: "+h+":"+m);
timeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new TimePickerDialog(TimePickerAppActivity.this, timeListener, h,m,true).show();
}
});
}
private TimePickerDialog.OnTimeSetListener timeListener = new
TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hour, int minute){
h=hour;
m=minute;
dispTime.setText("Current time is: "+h+":"+m);
}
};
}

 In this application, thetimePickerDialog is displayed when Button is selected. The Button with text
set the Time and ID time_button is captured from layout and mapped to a Button object timeButton.
 A setOnClickListener event listener is attached to the button so that when it is clicked, the event
handler callback method onClick() is invoked. In onClick(), a new instance of a TimePickerDialog
is created using the TimePickerDialog constructor and is displayed on the screen.
 We want to initialize the TimePickerDialog to current system time. An instance of calendar class is
created that is initially set to be the current system time. The current hour and minute values are
fetched from calendar instance and passed to the TimePickerDialog to display current system time.

11
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
 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 when the time is set or changed in the TimePickerDialog.
 TimePickerDialog provides callback listener, OnTimeChangedListener or OnTimeSetListener that
listens for when user is finished setting time by selecting Done button. The onTimeSet() method is
called when time is set or changed and we use it to display the selected time through the TextView.
 After running the application, we see outputs as shown below.

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 DateTimePickerApp with a TextView and two Button controls.
 The TextView control displays current system date and time, and two Button controls, set Date and
set Time, are used to invoke respective dialogs. When set Date button is selected, DatePickerDialog
is invoked, and when the set Time button is selected, the TimePickerDialog is invoked.
 Let's write the code shown below into the activity_date_time_ picker_app. xml to define a TextView
and two Button 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="match_parent">
<TextView
android:id="@+id/datetimevw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

12
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
<Button
android:id="@+id/date_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set the Date" />
<Button
android:id="@+id/time_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set the Time" />
</LinearLayout>
 We see that TextView and two Button controls are defined with the IDs datetimevw, date_button,
and time button. The captions for the two Button controls are set Date and set Time.
 After defining controls in layout file, we write Java code into the DateTimePickerAppActivity.java
to perform the following tasks:
1. Display the current system date and time in the TextView control.
2. Invoke DatePickerDialog and TimePickerDialog when the Set Date and Set Time Button
controls are clicked.
3. Initialize DatePickerDialog and TimePickerDialog to display the current system date and time
via the calendar instance.
4. Display modified date and time set by the user via the DatePickerDialog and TimePickerDialog
through the TextView control.
 To perform these tasks, the code shown below is written in DateTimePickerAppActivity.java.
packagecom.androidunleashed.datetimepickerapp;
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;

13
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
private Calendar c;
private int h, m,yr,mon,dy;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_date_time_picker_app);
dateTimeView = (TextView) findViewById(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;

14
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
dateTimeView.setText("Current date is "+ (mon+1)+"-"+dy+"-"+yr+"and
current time is:"+h+":"+m) ;
}
};
private TimePickerDialog.OnTimeSetListener timeListener = new
TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hour, int minute) {
h = hour;
m = minute;
dateTimeView.setText("Current date is "+ (mon+1)+"-"+dy+"-"+yr+" and
current time is: "+h+":"+m);
}
}; }
 The respective listeners, OnDateSetListener and OnTimeSetListener, invoke their callback methods,
onDateSet() and onTimeSet(), when the Done button in the DatePickerDialog or TimePickerDialog
is selected by the user.
 The two callback methods access the newly set date and time and display them through the
TextView control.After we run the application, we see outputs as shown below.

 We can also format date and time. Let's modify DateTimePickerAppActivity.java file shown below.
package com.androidunleashed.datetimepickerapp;
import android.app.Activity;
import android.os.Bundle ;
import android.widget.TextView;
import android.widget.Button;
import java.util.Calendar;
import android.app.TimePickerDialog;
15
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
import android.app.DatePickerDialog;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.TimePicker;
import android.widget.DatePicker;
import java.text.DateFormat;
public class DateTimePickerAppActivity extends Activity {
private TextView dateTimeView;
private Calendar c;
DateFormat DateTimeFormat = DateFormat.getDateTimeInstance();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_date_time_picker_app);
dateTimeView = (TextView) findViewById(R.id.datetimevw);
Button timeButton = (Button) findViewById(R.id.time_button);
Button dateButton = (Button) findViewById(R.id.date_button);
c = Calendar.getInstance();
dateTimeView.setText(DateTimeFormat.format(c.getTime()));
dateButton.setOnClickListener(new OnClickListener() {
public void onClick(View v){
new DatePickerDialog(DateTimePickerAppActivity.this,dateListener,
c.get(Calendar.YEAR),c.get(Calendar.MONTH),c.get(Calendar.DAY_OF_MONTH)).show();
}
});
timeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new TimePickerDialog(DateTimePickerAppActivity.this, timeListener,
c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE),true).show();
}
});
}
private DatePickerDialog.OnDateSetListener dateListener=new
DatePickerDialog.OnDateSetListener(){
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
c.set(Calendar.YEAR,year);
c.set(Calendar.MONTH,monthOfYear);
16
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
c.set(Calendar.DAY_OF_MONTH,dayOfMonth);
dateTimeView.setText(DateTimeFormat.format(c.getTime()));
}
};
private TimePickerDialog.OnTimeSetListener timeListener=new
TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hour, int minute) {
c.set(Calendar.HOUR_OF_DAY, hour);
c.set(Calendar.MINUTE, minute);
dateTimeView.setText(DateTimeFormat.format(c.getTime()));
}
}; }
 After we run the application, the formatted date and time are displayed, as shown below.

Fragments:
 When developing an application, we need to arrange Views in both landscape and portrait mode. If
we don't organize Views with this in mind, problems arise if user switches modes while running an
application. One solution is implementing fragments in the application.

The Structure of a Fragment:


 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
activity to fill up blank space that appears on right when switching from portrait to landscape.
 Similarly, the fragments can be dynamically removed if the screen size is unable to accommodate
the Views. A fragment is like a subactivity with its own life cycle and view hierarchy. We can add or
remove fragments while the activity is running.
 To create a fragment, we need to extend the Fragment class and implement several life cycle
callback methods, similar to an activity.

17
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

The Life Cycle of a Fragment:


 The life cycle of a fragment is affected by the activity's life cycle in which it is embedded. That is,
when the activity is paused, all the fragments in it are paused. Similarly, if an activity is destroyed,
all of its fragments are destroyed, as well.
 The life cycle of a fragment includes several callback methods, as listed here:
1. onAttach() — Called when the fragment is attached to the activity.
2. 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.
3. onCreateView() — Called to create the view for the fragment.
4. onActivityCreated() — Called when the activity's onCreate() method is returned
5. onStart() — Called when the fragment is visible to the user. This method is associated with the
activity's onStart().
6. onResume() — Called when the fragment is visible and is running. The method is associated
with the activity's onResume ().
7. onPause() — Called when the fragment is visible but does not have focus. The method is
attached to the activity's onPause ().
8. Onstop() — Called when fragment is not visible. The method is associated with the activity's
onStop().
9. onDestroyView() — Called when the fragment is supposed to be saved or destroyed. The view
hierarchy is removed from the fragment.
10. 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.
11. OnDetach() — Called when the fragment is detached from the activity and resources allocated to
the fragment are released.
 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 understand the concept of fragments, let's create an Android project called FragmentsApp. In this
application, we are going to create two fragments: Fragment1 and Fragment2.
 Fragment1 contains a selection widget, ListView that displays a couple of fruits to choose.
Fragment2 contains a TextView control to display fruit selected from the ListView of Fragment1.
 The fragments use individual XML layout files to define their Views, so for the two fragments, let's
add two XML files called fragment1.xml and fragment2.xml to the res/layout folder.
 To define a ListView control in the first fragment, the code shown below is written into the XML
file, fragment1.xml

18
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
<?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"
android:background="#0000FF">
<ListView
android:id="@+id/fruits_list"
android:layout_width= "match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="false" />
</LinearLayout>
 We see that a ListView selection widget is defined with the ID fruits_list. 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 shown below is written into the XML file fragment2.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">
<TextView
android:id="@+id/selectedopt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Please select a fruit" />
</LinearLayout>
 We see that a selectedopt TextView control is defined and is set to display Please select a fruit. Each
fragment has a Java class that loads its UI from the XML file, so for the two fragments, we need to
add two Java classes to our application.
 Add Fragment1Activity.java and Fragment2Activity.java to the com.androidunleashed.fragmentsapp
package of the application. The code shown below is written into the Java class file of the first
fragment, Fragment1Activity.java.
package com.androidunleashed.fragmentsapp;
import android.app.Fragment;
import android.os.Bundle;
import android.view.ViewGroup;
import android.view.View;

19
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
import android.view.LayoutInflater;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.content.Context;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
public class Fragment1Activity extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
Context c = getActivity().getApplicationContext();
View vw=inflater.inflate(R.layout.fragment1,container, false);
final String[] fruits={"Apple", "Mango", "Orange", "Grapes", "Banana"};
ListView fruitsList = (ListView)vw.findViewById(R.id.fruits_list);
ArrayAdapter<String> arrayAdpt=new ArrayAdapter<String>(c,
android.R.layout.simple_list_item_1, fruits);
fruitsList.setAdapter(arrayAdpt);
fruitsList.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View v, int position,long id) {
TextView selectedOpt = (TextView)
getActivity().findViewById(R.id.selectedopt);
selectedOpt.setText("You have selected "+((TextView) v).getText().toString() );
}
});
return vw;
}
}
 We see that the Java class for the fragment extends the Fragment base class. To access and draw the
UI for the fragment, the onCreateView() method is overridden. In the onCreateView() method, a
LayoutInflater object is used to inflate UI—the ListView control we defined in fragment1.xml file.
 The ListView and TextView controls are accessed from the layout files and mapped to the objects
fruitsList and selectedOpt. The arrayAdpt Array Adapter containing the elements of the array, fruits
in TextView form, is assigned to the ListView control for displaying choices to the user.

20
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
 The OnItemClickListener interface is implemented via an anonymous class that implements a
callback method, onItemClick(). The reference to the anonymous class is passed to the ListView,
fruitsList, to invoke the callback method onItemClick() when any item in the ListView is clicked.
 In onItemClick() method, item selected in ListView is displayed via TextView control selectedOpt.
 To load the UI of the second fragment from the XML file fragment2.xml, write the code shown
below into the Java class file of the second fragment Fragment2Activity.java.
package com.androidunleashed.fragmentsapp;
import android.app.Fragment;
import android.os.Bundle;
import android.view.ViewGroup;
import android.view.View;
import android.view.LayoutInflater;
public class Fragment2Activity extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
return inflater.inflate(R.layout.fragment2, container, false);
}
}
 Like the Java class of the first fragment, this class also extends the Fragment base class. The
onCreateView() method is overridden where a LayoutInflater object is used to inflate the TextView
control we defined in the fragment2.xml file.
 To accommodate both the fragments in the application, the code shown below is written into the
layout file activity_fragments_app.xml.
<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= "horizontal">
<fragment
android:name="com.androidunleashed.fragmentsapp.Fragment1Activity"
android:id="@+id/fragment1"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height = "match_parent" />
<fragment
android:name="com.androidunleashed.fragmentsapp.Fragment2Activity"

21
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
android:id="@+id/fragment2"
android:layout_weight="0"
android:layout_width="wrap_content"
android:layout_height="match_parent"/>
</LinearLayout>
 We see that the two fragments are added to the activity through the <fragment> elements. The
fragments are assigned the IDs fragment1 and fragment2. The fragments are set to refer to their
respective Java class through the android:name attribute.
 The first fragment refers to its Java class file Fragment1Activity, which was placed in the
com.androidunleashed.fragmentsapp package. The orientation of the container LinearLayout, was set
to horizontal, so both the fragments appear beside each other.
 We don't have to write any code into FragmentsAppActivity.java. We can leave the default code
unchanged, as shown below.
package com.androidunleashed.fragmentsapp;
import android.app.Activity;
import android.os.Bundle;
public class FragmentsAppActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragments_app);
}
}
 After we run application, the two UIs defined in Fragment1 and Fragment2 appear side by side. We
get output as shown below.

22
IV.BTECH I-SEM, CSE: MOBILE APPLICATION DEVELOPMENT

You might also like