III B.tech II Sem Mad Unit-4 Lecture Notes
III B.tech II Sem Mad Unit-4 Lecture Notes
UNIT- IV(A)
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
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
<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>
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
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
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
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
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
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
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.
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.
30
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
UNIT- IV(B)
DISPLAYING AND FETCHING INFORMATION USING DIALOGS AND FRAGMENTS
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);
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.
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.
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.
17
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
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