III B.tech II Sem Mad Unit-5 Lecture Notes
III B.tech II Sem Mad Unit-5 Lecture Notes
UNIT- V(A)
CREATING INTERACTIVE MENUS AND ACTIONBARS
is clicked. In an options Menu, the menu items are displayed in the form of text, check box, or
radio buttons. there were two types of Options Menus:
1. Icon Menu — The icon Menu appears when the user presses the MENU button on the device.
The menu items in the icon Menu can display icons as well as text. The icon Menu does not
display check boxes, radio buttons, or the shortcut keys for menu items.
2. Expanded Menu — If the menu has more than six menu items, the first five items are displayed
as an icon Menu and the sixth option appears as a More button. Clicking the More buttons
displays the Expanded Menu. The Expanded Menu can display menu items in the form of text,
check boxes, or radio buttons.
Submenu — Submenu refers to the menu that displays more detailed or specific menu options
when a menu item is selected. Each menu option is displayed with its full text, check box, radio
button, and shortcut key. Icons are not displayed in the submenu options. Android does not
support nested submenus.
Context Menu — The context Menu is displayed when we tap-and-hold on the concerned view
or when a user holds the middle D-pad button. Context Menus support submenus, check boxes,
radio buttons, and shortcuts, but we cannot display icons in a Context Menu.
1
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu_settings"
android:title="@string/menu_settings"
android:orderInCategory="100"
android:showAsAction="never" />
</menu>
We see that the root node of our menu in the XML file is <menu>. The default menu item with the ID
menu_settings shows text that is defined in the strings.xml file. Let's define certain <item> nodes to
display certain menu items. The code written in activity_menu_app.xml file is as shown below
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/create_datab"
android:title="Create Database"
android:icon="@drawable/ic_launcher" />
<item android:id="@+id/insert_rows"
android:title="Insert Rows"
android:icon="@drawable/ic_launcher" />
<item android:id="@+id/list_rows"
android:title="List Rows" />
<item android:id= "@+id/search_row"
android:title="Search"
android:icon="@drawable/ic_launcher"/>
<item android:id="@+id/delete_row"
android:title="Delete" />
<item android:id="@+id/update_row"
android:title="Update"
android:icon="@drawable/ic_launcher" />
</menu>
We see that we have defined six menu items in the preceding menu, and a unique ID is assigned to
each of them. The android:titie and android:icon attribute defines text and icon for the menu item.
The menu items defined in our menu file are create Database, Insert Rows, List Rows, Search, Delete,
and Update. The Six menu items are assigned the IDs as create_database, insert_rows, list_rows,
search_row, delete_row, and update_row.
In the application, we want to display a message that asks the user to select the MENU button on the
device or emulator for displaying the icon Menu. We use the TextView control to display messages.
To define TextView, we write the code as shown below in the layout file activity_menu_app.xml.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
2
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/selectedopt" />
</LinearLayout>
We added a TextView with the ID selectedopt, we use that to display desired text messages to user.
The TextView also is used to inform which menu item is selected by the user.
To inflate or merge the menu that we defined in the mymenu.xml file in our application and also to
inform which menu item is selected by user, we write Java code as shown below in java activity file.
package com.androidunleashed.menuapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuInflater;
import android.widget.TextView;
public class MenuAppActivity extends Activity {
private TextView selectedOpt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_app);
selectedOpt=(TextView)findViewById(R.id.selectedopt);
selectedOpt.setText("Please select MENU button to display menu");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_menu_app, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.create_datab:
3
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
selectedOpt.setText("You have selected Create Database option");
break;
case R.id.insert_rows:
selectedOpt.setText("You have selected Insert Rows option");
break;
case R.id.list_rows:
selectedOpt.setText("You have selected List Rows option");
break;
case R.id.search_row:
selectedOpt.setText("You have selected Search Row option");
break;
case R.id.delete_row:
selectedOpt.setText("You have selected Delete Row option");
break;
case R.id.update_row:
selectedOpt.setText("You have selected Update Row option");
break;
}
return true;
}
}
We capture TextView defined in layout and assign it to a TextView object named selectedOpt and use
TextView for displaying initial message and for informing which menu item is selected by user.
The onCreateOptionsMenu() method of the Activity is called when the user clicks the MENU button
of the device. So, we override this method to display our icon Menu.
To display our icon Menu, we need to inflate or merge our menu that we defined in the
activity_menu_app.xml file in the menu provided as a parameter to this method.
To inflate menu in activity_menu_app.xml file, we get MenuInflater from Activity class. An object,
inflater, is created of MenuInflater class and inflater's inflate method is called to inflate, or merge, our
own menu defined in activity_menu_app.xml file to menu given as a parameter to this method.
The onCreateOptionsMenu() method is set to return Boolean value true to allow Android to display
menu. The next step for us is to define action to take place when the user selects any of menu items.
4
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
In method, we extract Menu item ID of the menu item selected for identifying it and then can take
respective action. getItemId() method helps in knowing ID of selected menu item. The following code
explains how action is taken when a menu item is selected:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.create_datab:
selectedOpt.setText("You have selected Create Database option");
break;
………….………………….
……………………………..
}
return true;
}
The preceding method selected menu item is passed to this method and assigned to the Menuitem
object item. getItemId() method is called to know the ID of the selected menu item, and through the
switch statement respective action is taken on the selected menu item.
In this code, we are setting a text message through the TextView object selectedOpt to inform the user
which of the menu items is selected. On running the application, we get output as shown below
5
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
android:icon="@drawable/ic_launcher" />
<item android:id="@+id/insert_rows"
android:title="Insert Rows"
android:icon="@drawable/ic_launcher" />
<item android:id="@+id/list_rows"
android:title="List Rows" />
<item android:id="@+id/search_row"
android:title="Search"
android:icon="@drawable/ic_launcher"/>
<item android:id= "@+id/delete_row"
android:title="Delete" />
<item android:id="@+id/update_row"
android:title ="Update"
android:icon="@drawable/ic_launcher" />
<item android:id="@+id/sort_rows"
android:title="Sort Table"
android:checkable="true"
android:checked="true" />
<item android:id="@+id/merge_row"
android:title="Merge Rows"
android:alphabeticShortcut="m"
android:numericShortcut="4"/>
</menu>
We see that the code now has eight menu items. The seventh menu item, sort_rows, is set to appear in
the form of a check box via the android:checkable attribute. When we set the value of the android
checkable property to true, the menu item appears as a check box.
The check box can be initially set to appear in either a checked or unchecked state by the
android:checked attribute, when we set android:checked="true", the menu item appears as checked by
default.
Shortcut keys are assigned to the last menu item, Merge ROWS (merge_row). When we set the
android:aiphabeticshortcut="m" attribute, shortcut key m for full keyboard is assigned to menu item.
Similarly, the android:numericshortcut="4" attribute assigns the shortcut key 4 from the numeric
keypad. The shortcut keys are displayed below the menu item text.
When the menu is open (or while holding the MENU key), if we press the m key from the full keyboard
or 4 from the numeric keypad, the menu item Merge Rows is selected.On running the application, we
get output as shown below
6
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
Adding Submenus:
A submenu is a collection of menu items invoked when a regular menu item is selected. Usually, a
submenu represents more detailed options for the selected menu item. The submenu can be associated
with any menu item.
A submenu is created by enclosing <item> nodes within the <menu> node, where <item> nodes
represent the submenu options and the <menu> node acts as the root node of the submenu.
To associate a submenu with any menu item, just put the <menu> node of the submenu along with its
nested <item> nodes inside <item> node of menu item to which we want to assign the submenu.
Let's add a submenu consisting of three menu items—search on code, search on Name, and search on
Price to the Search menu. To add a submenu modify activity_menu_app.xml as shown below.
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/create_datab"
android:title="Create Database"
android:icon="@drawable/ic_launcher" />
<item android:id="@+id/insert_rows"
android:title="Insert Rows"
android:icon="@drawable/ic_launcher" />
<item android:id="@+id/list_rows"
android:title="List Rows" />
<item android:id="@+id/search_row"
android:title="Search"
android:icon="@drawable/ic_launcher">
<menu>
<group android:checkableBehavior="single">
<item android:id="@+id/search_code"
7
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
android:title="Search on Code"
android:checked="true" />
<item android:id="@+id/search_name"
android:title="Search on Name"
android:alphabeticShortcut="n"
android:numericShortcut="6" />
<item android:id="@+id/search_price"
android:title="Search on Price" />
</group>
</menu>
</item>
<item android:id= "@+id/delete_row"
android:title="Delete" />
<item android:id="@+id/update_row"
android:title ="Update"
android:icon="@drawable/ic_launcher" />
<item android:id="@+id/sort_rows"
android:title="Sort Table"
android:checkable="true"
android:checked="true" />
<item android:id="@+id/merge_row"
android:title="Merge Rows"
android:alphabeticShortcut="m"
android:numericShortcut="4"/>
</menu>
We can see that a submenu has been created, consisting of three menu items, search on Code, Search
on Name, and Search on Price, With IDs search_code, search_name, and search_price. Submenu is
assigned to search menu item by nesting <menu> node within <item> node of the search menu item.
If we want menu items to appear as radio buttons, we need to nest them within <group> node. The
<group> node is used to collect certain nodes and for applying attributes to all the nested nodes.
The android:checkableBehavior attribute determines whether to make menu items nested within the
<group> node appear as radio buttons, check boxes, or simple menu items. The attribute can take three
values:
1. single — Only one item can be checked at a time, producing radio buttons.
2. All — Any item can be checked, producing check boxes.
3. None — The item appears as simple text, without a check box or radio button.
8
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
We have defined an Expanded Menu and a submenu for the search menu item of our icon Menu
with the menu file mymenu.xml. Next, we add statements to onOptionsItemSelected() method.
These statements display messages showing which menu item from the Expanded Menu or submenu
has been selected. The Activity file appears as shown below.
package com.androidunieashed.menuapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuInflater;
import android.widget.TextView;
public class MenuAppActivity extends Activity {
private TextView selectedOpt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
selectedOpt=(TextView)findViewById(R.id.selectedopt);
selectedOpt.setText("Please select MENU button to display menu");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater ();
inflater.inflate(R.menu.mymenu, menu);
return true;
}
©Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId() ) {
case R.id.create_datab:
selectedOpt.setText("You have selected Create Database option");
break;
case R. id. insert_rows :
selectedOpt.setText("You have selected Insert Rows option");
break;
case R.id.list_rows:
selectedOpt.setText("You have selected List Rows option");
9
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
break;
case R. id. search_row:
selectedOpt. setText ("You have selected Search Row option");
break;
case R.id.delete_row:
selectedOpt.setText("You have selected Delete Row option");
break;
case R.id.update_row:
selectedOpt.setText("You have selected Update Row option");
break;
case R.id.sort_rows:
selectedOpt.setText("You have selected Sort Table option");
item.setChecked(!item.isChecked());
break;
case R.id.merge_row:
selectedOpt.setText("You have selected Merge Rows option");
break;
case R.id.search_code:
selectedOpt.setText ("You have selected Search on Code option");
break;
case R.id.search_name:
selectedOpt.setText("You have selected search on Name option");
break;
case R.id.search_price:
selectedOpt.setText("You have selected Search on Price option");
break;
}
return true;
}
}
When the application is run, we see a TextView prompting us to select a MENU button, after which the
icon Menu is displayed. After we select the search menu item from the icon Menu, the search submenu
is displayed.
We can select a menu item from the submenu by either clicking it or using its shortcut key (if any).
For example, if we select search on code as shown, the TextView responds showing the message, You
have selected Search on Code option, as shown below.
10
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
11
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
The first two items are are set to appear as check boxes by nesting them within the <group> node and
applying the android: checkabieBehavior attribute to them. A submenu consisting of a single menu
item, Find Next (Find), is attached to the third menu item.
Let's define two menu items in the second context menu. The menu file of the second context menu,
mycontext_menu2 .xml, appears as shown below.
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/open_item"
android:title="Open"
android:alphabeticShortcut="o"
android:numericShortcut="5" />
<item android:id="@+id/close_item"
android:title="Close"
android:checkable="true" />
</menu>
This context menu consists of two menu items titled open and close. To invoke the open menu item,
the shortcut keys O (full keyboard) and 5 (numeric keypad) can be used.
The second menu item, close, is set to appear as a check box by setting the android:checkable attribute
to true. If we want to assign 2 context menus to 2 TextView controls so that the respective context
menu appears when we press and hold a TextView control, we have to write some code.
Let's modify layout file activity_menu_app.xml to add these 2 TextView controls, as shown below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/selectedopt" />
<TextView
android:text="View to invoke first context menu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/contxtl_view" />
<Textview
android:text="view to invoke second context menu"
android:layout_width="match_parent"
android:layout_height="wrapcontent"
12
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
android:id="@+id/contxt2_view"/>
</LinearLayout>
We see that two TextView controls were initialized to two views to invoke first and second context
menu.The IDs assigned to these TextView controls are contxt1_view and contxt2_view.
Next, we need to write some Java code into MenuAppActivity.java. To create context menus, we need
to override the oncreateContextMenu method for registering views that are supposed to use it.
The option to register a context menu to view(s) enables us to associate context menus for certain
selected views. A context menu is registered to a view through registerForContextMenuO method as
shown in the following code:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
selectedOpt=(TextView)findViewById(R.id.selectedopt);
selectedOpt.setText("Please select MENU button to display menu");
TextView contxt1View=(TextView)findViewById(R.id.contxtl_view);
TextView contxt2View=(TextView)findViewById(R.id.contxt2_view);
registerForContextMenu(contxt1View);
registerForContextMenu(contxt2View);
}
We see that two TextView controls with the contxt1_view and contxt2_view IDs are captured from
layout file and mapped to the TextView objects contxt1view and contxt2View.
The two TextView objects are passed to the registerForContextMenu () method, as we want to
associate them with the two context menus. Once a view is registered, onCreatecontextMenu() method
is invoked whenever we tap and hold on the registered view.
The method also receives a Menu object as a parameter that we use to add menu items to it. To add
menu items to a menu, the add() method is used. We need to override the onCreateContextMenu ()
method for displaying the context menu.
The method receives the menu object as a parameter to which we add the menu items for the context
menu. Besides the menu object, the method also receives the view object that initiated the context
menu and a contextMenuInfo object.
ContextMenuInfo is an interface that belongs to ContextMenu and acts as an adapter for passing any
other information about menu inflation. onCreateContextMenu() method appears as shown here:
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
13
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
if (v.getId()==R.id.contxtl_view) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mycontext_menu1, menu);
menu.setHeaderTitle("Sample Context Menul");
menu.setHeaderIcon(R.drawable.ic_launcher);
}
if (v.getId()==R.id.contxt2_view) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mycontext_menu2, menu);
menu.setHeaderTitle("Sample Context Menu2");
menu.setHeaderIcon(R.drawable.ic_launcher);
}
}
We see that we first identify which view has initiated the context menu, and accordingly we inflate
or merge the menu that we defined in mycontext_menu1.xml or mycontext_menu2.xml in the menu
provided as the parameter to the onCreateContextMenu () method.
A MenuInflater class object, inflater, is created and its inflate method is invoked to inflate, or merge,
our own menu, defined in the respective XML file, with the menu parameter of this method.
Two context menus are being created then title and icon are set to appear in the context menu's header
bar via setHeaderTitle and setHeaderIcon.
14
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
The Menu item ID of the selected menu item is extracted through the getItemId() method, and
accordingly message is displayed through TextView to display which context menu item is selected.
We toggle the state of the checkable item through the MenuItem.isChecked() method. The method
returns true if the menu item is checked; otherwise it returns false.
We change the state of menu item by passing a Boolean value that represents reverse of existing
state. The MenuAppActivity.java appears as shown below.
package com.androidunleashed.MenuApp;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuInflater;
import android.widget.TextView;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import android.view.ContextMenu;
public class MenuAppActivity extends Activity {
private TextView selectedOpt;
@Override
public void onCreate(Bundle savedlnstanceState) {
super.onCreate(savedlnstanceState);
setContentView(R.layout.main);
selectedOpt=(TextView)findViewById(R.id.selectedopt);
selectedOpt.setText("Please select MENU button to display menu");
TextView contxt1View=(TextView)findViewById(R.id.contxtl_view);
TextView contxt2View=(TextView)findViewById(R.id.contxt2_view);
registerForContextMenu(contxt1View);
registerForContextMenu(contxt2View);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mymenu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
15
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
switch (item.getItemId()) {
case R.id.create_datab:
selectedOpt.setText("You have selected Create Database option");
break;
case R.id.insert_rows:
selectedOpt.setText("You have selected Insert Rows option");
break;
case R.id.list_rows:
selectedOpt.setText("You have selected List Rows option");
break;
case R. id.search_row:
selectedOpt.setText("You have selected Search Row option");
break;
case R.id.delete_row:
selectedOpt.setText("You have selected Delete Row option");
break;
case R. id.update_row:
selectedOpt.setText("You have selected Update Row option");
break;
case R.id.sort_rows:
selectedOpt.setText("You have selected Sort Table option");
item.setChecked(!item.isChecked());
break;
case R.id.merge_row:
selectedOpt.setText("You have selected Merge Rows option");
break;
case R.id.search_code:
selectedOpt.setText("You have selected Search on Code option");
break;
case R.id.search_name:
selectedOpt.setText("You have selected Search on Name option");
break;
case R.id.search_price:
selectedOpt.setText("You have selected Search on Price option");
break;
}
return true;
16
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo
menulnfo)
{
super.onCreateContextMenu(menu, v, menulnfo);
if (v.getId()==R.id.contxtl_view)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mycontext_menul, menu);
menu.setHeaderTitle("Sample Context Menul");
menu.setHeaderIcon(R.drawable.ic_launcher);
}
if (v.getId()==R.id.contxt2_view)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mycontext_menu2, menu);
menu.setHeaderTitle("Sample Context Menu2");
menu.setHeaderIcon(R.drawable.ic_launcher);
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.cut_item:
selectedOpt.setText("You have selected the Cut option");
item.setChecked(!item.isChecked());
break;
case R.id.copy_item:
selectedOpt.setText("You have selected the Copy option");
item.setChecked(!item.isChecked());
break;
case R.id.find_item:
selectedOpt.setText("You have selected the Find Submenu");
break;
case R.id.findnext:
selectedOpt.setText("You have selected the Find Next option");
17
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
break;
case R.id.openitem:
selectedOpt.setText("You have selected the Open option");
break;
case R.id.close_item:
selectedOpt.setText("You have selected the Close option");
item.setChecked(!item.isChecked());
break;
}
return true;
}
}
On running the application, we get outputs as shown below.
18
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
Creating Menus through Coding:
In this section, we learn to create the three types of menus, options Menu, Submenu, and Context
Menu, with Java coding.
Assigning Icons:
We can assign icons to the menu items in the Icon Menu using setIcon() method. Where icon file
name is a drawable resource identifier for the icon to be assigned to the menu item.
syntax: menuitem.setIcon(R.drawable.icon_filename);
Creating Submenus
Submenus appear as single floating windows displaying all of their menu items. A submenu is attached
to a regular menu item that, when selected, invokes the submenu, hence displaying all the menu items
in it.
19
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
A submenu is added through addSubMenu0 method. It supports same parameters as add() method
used to add menu items in Options Menu: Group ID, Menu Item ID, Sort order ID, and Menu Text.
We can also use the setHeadericon method to specify an icon to display in the submenu's header bar
and the seticon () method to display the icon for the menu item to which this submenu is associated.
The following code adds a submenu to a regular menu item, search:
We see that a submenu called searchSub is created for the regular menu item search. The menu item
search to which the submenu searchSub is associated is assigned a group ID of 0.
SEARCH_ROW, which is assigned the value of the static constant Menu.FiRST+3, is assigned as the
Menu item ID; 3 is assigned as the sort order ID; and Search is assigned as the menu item text.
The ic_iauncher.png file in Resources is set to display in the submenu's header bar. The image
ic_iauncher.png is set to display as an icon in the search menu item, to which the submenu searchsub
is associated. A menu item, search on code, is added to submenu through add() method.
By default, the check box is unchecked. To make the check box checked by default, we use the
setchecked() method. By passing the Boolean value true to the setchecked() method, we can make the
check box appear checked by default.
The following code makes a menu item appear as a checked check box by default:
Radio buttons are mutually exclusive menu items displayed as a circles; only one menu item can be
selected in a group at any time. To create radio buttons, we need to make them part of the same group.
We assign the same group identifier to all of them; then we call setGroupcheckable() method. syntax:
setGroupCheckabie(int GroupID, boolean Checkable, boolean Exclusive)
20
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
Where the GroupID refers to the group whose menu items we want to appear as radio buttons or check
boxes. The second parameter, checkable, should be set to true to make the check box or radio button
appear as checkable. If we pass a false value to the checkable parameter, then the menu items appear
neither as check boxes nor radio buttons.
The third parameter, Exclusive, determines whether we want the menu items to be mutually exclusive.
If the Exclusive parameter is set to true, only one can be selected at a time. So we set the parameter
Exclusive to true if we want the menu items to appear as radio buttons. Passing the value false to the
Exclusive parameter makes all the menu items in the group appear as check boxes.
The following code makes all the menu items of a submenu appear as radio buttons:
We see that submenu called searchSub is created and associated with menu item, search. searchSub
submenu contains three menu items: search on code, Search on Name, and Search on Price.
All three menu items are assigned the Group ID 1. All the menu items appear as checkable radio
buttons, because the checkable and Exclusive parameters in the setGroupCheckable () method are
passed as true.
The first menu item in the group, search on Code, is set to appear as checked by default by passing
the value true to the setchecked() method.
21
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
Trying It Out
Create a new Android project called MenuAppCode. We want to display three Text view controls in
the menu The first TextView directs the user to click the MENU button to display the menu. The second
and third TextView controls are used for displaying context Menus.
When user taps and holds on either TextView control, a context Menu appears on screen. To display
three TextView controls, modify layout file activity_menu_app_code.xml to appear as shown below
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="®+id/selectedopt"/>
<TextView
android:text="View to invoke first context menu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="®+id/contxtl_view" />
<TextView
android:text="View to invoke second context menu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/contxt2_view"/>
</LinearLayout>
In the code, we can see that three TextView controls are assigned the IDs seiectedopt, contxti_view,
and contxt2_view. To tell user which views are meant for displaying context Menus, the TextView
controls are set to display text Views to invoke first and second context menu.
To display the menu items in the Options menu, submenu, and context Menu, the Activity file
MenuAppcodeActivity.java is modified as shown below.
package com.androidunleashed.menuappcode;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.view.SubMenu;
22
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
import android.view.View;
import android.view.ContextMenu;
public class MenuAppCodeActivity extends Activity {
private static final int CREATE_DATAB= Menu.FIRST;
private static final int INSERT_ROWS = Menu.FIRST+1;
private static final int LIST_R0WS = Menu.FIRST+2 ;
private static final int SEARCH_ROW =Menu.FIRST+3;
private static final int DELETE_R0W =Menu.FIRST+4;
private static final int UPDATE_ROW =Menu.FIRST+5;
private static final int S0RT_R0WS = Menu.FIRST+6;
private static final int MERGE_R0W = Menu.FIRST+7;
private static final int SEARCH_C0DE = Menu.FIRST+8;
private static final int SEARCH_NAME = Menu.FIRST+9;
private static final int SEARCH_PRICE = Menu.FIRST+10;
private static final int CUT_ITEM = Menu.FIRST+11;
private static final int COPY_ITEM = Menu.FIRST+12;
private static final int OPEN_ITEM = Menu.FIRST+13;
private static final int CLOSE_ITEM = Menu.FIRST+14;
private static final int FIND_ITEM = Menu.FIRST+15;
private static final int FIND_NEXT = Menu.FIRST+16;
private TextView selectedOpt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_app_code);
selectedOpt=(TextView)findViewById(R.id.selectedopt);
selectedOpt.setText("Please select MENU button to display menu");
TextView contxt1View=(TextView)findViewById(R.id.contxt1_view);
TextView contxt2View=(TextView)findViewById(R.id.contxt2_view);
registerForContextMenu(contxt1View);
registerForContextMenu(contxt2View);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0,CREATE_DATAB,0,"Create
Database").setIcon(R.drawable.ic_launcher);
menu.add(0,INSERT_ROWS,1, "Insert Rows").setIcon(R.drawable.ic_launcher);
23
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
menu.add(0,LIST_ROWS,2,"List Rows");
SubMenu searchSub = menu.addSubMenu(0, SEARCH_ROW, 3, "Search");
menu.add(0,DELETE_ROW,4,"Delete"); menu. add (0, UPDATE_ROW, 5,
"Update") ;
menu.add(0,SORT_ROWS,S,"Sort Table").setCheckable(true).setChecked(true);
menu.add(0,MERGE_ROW,7,"Merge
Rows").setAlphabeticShortcut('m').setNumericShortcut ('4') ;
searchSub.setHeaderIcon(R.drawable.ic_launcher);
searchSub.setIcon(R.drawable.ic_launcher);
searchSub.add(1, SEARCH_CODE, Menu.NONE, "Search on
Code").setChecked(true);
searchSub.add(1, SEARCH_NAME, Menu.NONE, "Search on
Name").setShortcut('6','n');
searchSub.add(1, SEARCH_PRICE, Menu.NONE, "Search on Price");
searchSub.setGroupCheckable(1, true, true);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId() ) {
case CREATE_DATAB:
selectedOpt.setText("You have selected Create Database option");
break;
case INSERT_ROWS:
selectedOpt.setText("You have selected Insert Rows option");
break;
case LIST_ROWS:
selectedOpt.setText("You have selected List Rows option");
break;
case SEARCH_ROW:
selectedOpt.setText("You have selected Search Submenu option");
break;
case DELETE_ROW:
selectedOpt.setText("You have selected Delete Row option");
break;
case UPDATE_ROW:
selectedOpt.setText("You have selected Update Row option");
24
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
break;
case SORT_ROWS:
selectedOpt.setText("You have selected Sort Table option");
item.setChecked(!item.isChecked());
break;
case MERGE_ROW:
selectedOpt.setText("You have selected Merge Rows option");
break;
case SEARCH_CODE:
selectedOpt.setText("You have selected Search on Code option");
break;
case SEARCH_NAME:
selectedOpt.setText("You have selected Search on Name option");
break;
case SEARCH_PRICE:
selectedOpt.setText("You have selected Search on Price option");
}
return true;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId()==R.id.contxt1_view) {
menu.setHeaderTitle("Sample Context Menul");
menu.setHeaderIcon(R.drawable.ic_launcher);
menu. add (2, CUT_ITEM, Menu.NONE, "Cut") ;
menu.add(2, COPY_ITEM, Menu.NONE, "Copy");
menu.setGroupCheckable(2, true, false);
SubMenu subcont = menu.addSubMenu(2, FIND_ITEM, Menu.NONE, "Find");
subcont.add(3, FIND_NEXT, Menu.NONE, "Find Next");
}
if (v.getId()==R.id.contxt2_view) {
menu.setHeaderTitle("Sample Context Menu2");
menu.setHeaderIcon(R.drawable.ic_launcher);
menu.add(3, OPEN_ITEM, Menu.NONE, "Open").setShortcut('S’,'o');
menu.add(3, CLOSE_ITEM, Menu.NONE, "Close").setCheckable(true);
25
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case CUT_ITEM:
selectedOpt.setText("You have selected the Cut option");
item.setChecked(!item.isChecked() ) ;
break;
case COPY_ITEM:
selectedOpt.setText("You have selected the Copy option");
item.setChecked(!item.isChecked()) ;
break;
case FIND_ITEM:
selectedOpt.setText("You have selected the Find Submenu");
break;
case FIND_NEXT:
selectedOpt.setText("You have selected the Find Next option");
break;
case OPEN_ITEM:
selectedOpt.setText("You have selected the Open option");
break;
case CLOSE_ITEM:
selectedOpt.setText("You have selected the Close option");
item.setChecked (!item.isChecked()) ;
break;
}
return true;
}}
We see that the TextView with the ID seiectedopt is accessed from the layout file and is mapped to
TextView object seiectedopt. It is set to display text Please select MENU button to display menu.
Two TextView controls with IDS context1_ view and contxt2_view are registered for displaying a
context Menu. The onCreateOptionsMenu() method defines the menu items for the options Menu as
well as for the search subMenu.
The menu items defined for the options Menu are create Database, Insert Rows, List Rows, Delete,
Update, Sort Table, and Merge Rows. The menu items defined for the Search SubMenu are Search on
Code, Search on Name, and search on price.
26
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
Shortcut keys are assigned for the Merge ROWS menu item and the Search on Name menu item of the
Search SubMenu. The Sort Table menu item is set as a checkable menu item. All the menu items of
the search SubMenu are set to appear as radio buttons.
The onOptionsitemSelected () method informs the menu item that is selected by the user. It displays
text message through TextView seiectedopt to inform which of menu options is selected by user.
The onCreateContextMenu() method displays the two context Menus. When the user taps and holds
on any of the TextView controls with the IDs context1_view and contxt2_view the method displays
the corresponding context Menu on the screen.
The onContextItemSeiected() method does the job of informing us which menu item of the context
Menu is selected by the user. The output of this application is the same as above application
27
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
The ListView control is used to display different items on the screen, which the user can tap and hold
to invoke the related context Menu. To display the TextView and ListView in Our application, modify
activity_context_menu_app.xml to appear as shown below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/selectedopt" />
<ListView
android:id="@+id/listvw"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="false"/>
</LinearLayout>
To display the related context Menu and information about the selected item, let's add the code
shown below to the ContextMenuAppAct ivity. java.
package com.androidunleashed.contextmenuapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.MenuInflater;
import android.widget.TextView;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import android.view.ContextMenu;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ArrayAdapter;
public class ContextMenuAppActivity extends Activity {
private TextView selectedOpt;
String[] fruits={"Apple","Mango","Orange","Grapes","Banana"};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
28
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
setContentView(R.layout.activity_context_menu_app);
selectedOpt = (TextView) findViewById(R.id.selectedopt);
selectedOpt.setText("Tap and hold a menu item to display its context menu");
ListView myListView = (ListView) findViewById(R.id.listvw);
final ArrayAdapter<String> arrayAdpt = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, fruits);
myListView.setAdapter(arrayAdpt);
registerForContextMenu(myListView);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo
menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId() == R.id.listvw) {
AdapterView.AdapterContextMenuInfo info =
(AdapterView.AdapterContextMenuInfo) menuInfo;
if (fruits[info.position] == "Apple") {
menu.setHeaderTitle(fruits[info.position]);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mycontext_menul, menu);
}
if (fruits[info.position] == "Mango") {
menu.setHeaderTitle(fruits[info.position]);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mycontext_menu2, menu);
}} }
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo
info=(AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
switch (item.getItemId()) {
case R.id.cut_item:
selectedOpt.setText("You have selected the Cut option of " +
fruits[info.position]+" menu");
break;
case R.id.copy_item:
selectedOpt.setText("You have selected the Copy option of " +
29
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
fruits[info.position]+" menu");
break;
case R.id.open_item:
selectedOpt.setText("You have selected the Open option of " +
fruits[info.position]+" menu");
break;
case R.id.close_item:
selectedOpt.setText("You have selected the Close option of the"+
fruits[info.position]+" menu");
break;
}
return true;
}}
When we run the application, we see output as shown below
30
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
Using the ActionBar:
The ActionBar is a widget that replace title bar at top of every Activity displaying navigation and
important functionality of an application. By default, the ActionBar includes the application logo on
the left side, followed by the Activity title, and menu items (if any) on the right side.
The ActionBar helps in displaying key actions commonly used in an application that we want to be
visible on the screen while running the application. The application's logo acts as a link to the
application's home.
On Android 3.0 and higher, items from Options Menu are presented by ActionBar. The ActionBar
provides the following features:
1. Customizes the title bar of an Activity.
2. Follows its own life cycle.
3. Consistently displays frequently used actions of an application. The menu items from options Menu
are displayed in the ActionBar. The menu items displayed in the ActionBar are also called action
items. The menu items of the Overflow Menu can be seen by selecting the Menu button on the
device or the Overflow Menu button in the ActionBar.
4. Appears in three forms: standard, tabbed, and list.
5. Makes it possible to use the application's icon or logo for navigation.
6. Through the ActionBar we can even display Action Views, that is, custom views in theActivity's
title bar. For example, we can display the search widget in the ActionBar.
The ActionBar includes the components are
1. Application's Icon/Logo—Displayed at the upper left on the ActionBar.
2. Activity Title—Displays the title for the ActionBar.
3. Tabs—Displays the tabs of the ActionBar if the navigation mode set is tabs.
4. Drop-Down List—Displays the action items in the form of a drop-down list if the
navigationmode set is list navigation. We learn about navigation mode soon.
5. Actionltems—Displays the menu items of the Options menu in the ActionBar.
6. Action Views—Displays Custom Views in the ActionBar.
7. Overflow Menu—Displays menu items that could not be accommodated in the ActionBar.
31
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
In the preceding code, the getActionBar () method is called to get an ActionBar object, and its hide0
and show() methods are for hiding and showing the ActionBar.
To hide the ActionBar in an Activity, we can also apply a theme that doesn't support it. In the
AndroidManifest.xml file, set the theme for the Activity to Theme.Holo.NoActionBar as shown in the
following code:
<activity android:label="@string/app_name"
android:name=".ActionBarApp"
android:theme="@android:style/Theme.Holo.NoActionBar" >
The icon or logo displayed in the ActionBar can be modified through the android: icon attribute in
configuration file AndroidManifest.xml. We can use android: logo attribute for the same purpose.
The visibility of the icon or logo in the ActionBar is controlled by passing a Boolean value to the
setDisplayShowHomeEnabled () method.
The following statement hides the logo or icon in the ActionBar:
actionBar.setDisplayShowHomeEnabled(false);
The following statement makes the logo or icon visible in the ActionBar:
actionBar.setDisplayShowHomeEnabled(true);
Similarly, the visibility of the title in the ActionBar can be controlled by passing a Boolean value to
the setDisplayShowTitleEnabledO method.
The following statement hides the title in the ActionBar:
actionBar.setDisplayShowTitleEnabled(false);
The following statement shows the title in the ActionBar:
actionBar.setDisplayShowTitleEnabled(true);
32
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
33
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/hide_action"
android:text="Hide ActionBar"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/show_title"
android:text="Show Title"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/hide_title"
android:text="Hide Title"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/show_logo"
android:text="Show Logo"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/hide_logout"
android:text="Hide Logo"/>
</LinearLayout>
We see that the Button controls are assigned the IDs show action, hide_action, show_titie, hide_titie,
show_logo, and hide_logo. Also, the caption assigned to the Button controls signifies the task they are
supposed to perform.
The captions assigned to the Button controls are Show ActionBar, Hide ActionBar, Show Title, Hide
Title, Show Logo, and Hide Logo.
Next, we need to define an action item, create, in our application. This action item when selected
navigates us to the new Activity in the application. The action item is nothing but the menu item from
the options Menu that is displayed in the ActionBar to be accessed instantly.
We can define action items in the menu file activity_demo_action_bar.xml that is provided by default
in the res/menu folder of our application.
34
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
In the menu file, we define two menu items, create and search, where create is displayed in ActionBar
as action item, and Search is used to display a search widget in the form of ActionView. The
activity_demo_action_bar.xml file, after defining the two menu items shown below.
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/create_datab"
android:title="Create"
android:icon="@drawable/create"
android:orderlnCategory="0"
android:showAsAction="ifRoom|withText"/>
<item android:id="@+id/menu_search"
android:title="Search"
android:showAsAction="always"
android:actionViewClass="android.widget.SearchView"/>
</menu>
Because we want to represent the action item create via an icon, an image file, create. png, should be
copied to the res/drawable folders of the application.
On selecting the create action item, we want to navigate to a new Activity. To define views for the
new Activity, we need to add an XML file to the res/layout folder. So, right-click the layout folder in
the Package Explorer window and select the New, Android XML file option.
When we navigate to the new Activity, we want to display a text message informing that we have
navigated to the new Activity. For displaying a text message, we define a TextView control in the new
Activity's layout file, create.xml as shown below.
<?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:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="This is Create Activity"
android:textStyle="bold"/>
</LinearLayout>
We see that the preceding layout file defines a TextView control with the initial text, "This is create
Activity". The text message is displayed when we navigate to the new Activity.
After that we need a Java class file to load the views defined in the layout file. So, add a Java class
file called CreateActivity.java to package com.androidunleashed.demoactionbar of our application.
35
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
In the CreateActivity. java file, we need to write code to perform the following tasks:
1. Load the views defined in the create.xml file.
2. Make the application's logo clickable. Remember, we want the user to be taken to the main
Activity of the application on selecting the application's logo.
3. Navigate to the main Activity file, DemoActionBarActivity.class, of the application.
For performing all these tasks, we write the code as shown below in the file CreateActivity.java.
package com.androidunleashed.demoactionbar;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
public class CreateActivity extends Activity {
@Override
protected void onCreate(Bundle savedlnstanceState){
super.onCreate(savedlnstanceState);
setContentView(R.layout.create);
ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case (android.R.id.home) :
Intent intent = new Intent(this, DemoActionBarActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
}
In the preceding code, we can see that an ActionBar object, actionBar, is accessed by calling the
getActionBar() method and then the Boolean value true is passed to the setHomeButtonEnabled()
method to make the application's logo clickable.
36
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
Clicking application's logo generates a click event on a menu item with the ID android. R.id.home. In
handler method onOptionsItemSelected(), we check whether menu item with ID android. R.id.home
is clicked, that is, whether the application's logo is clicked.
If application's logo is found to be clicked, we navigate back to the main Activity of the application,
DemoActionBarActivity .class, by clearing all the activities on the top of the stack. For clearing all
the top activities, we use an intent flag,FLAG_ACTIVITY_CLEAR_TOP.
We know that no Activity is visible to Android application until it is mentioned in the configuration
file AndroidManifest.xml. To make the newly added Activity createActivity. java visible to the
Android project, a statement is written in the AndroidManifest.xml file.
Also, to replace the default application's logo with a new logo, we need to write code as shown
below in AndroidManifest.xml file. Only statements in bold are added; the rest is the default code.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidunleashed.DemoActionBar"
android:versionCode="1"
android:versionName="l.0">
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/home"
android:label= "@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name=".DemoActionBarActivity"
android:label="@string/title_activity_demo_action_bar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".CreateActivity" android:label="@string/app_name" />
</application>
</manifest>
To display our application's logo, we need to copy an image, home.png, to the res/drawable folders of
our application. The statements added to the AndroidManifest.xml file replace the default application's
logo with the image home .png supplied by us.
37
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
code makes the newly added Activity, CreateActivity. class, visible to the rest of the application. To
enable the ActionBar, the minimum SDK version, that is, the value of the android:minsdkversion
attribute, is set to 11 or higher.
Finally, it's time to write code in DemoActionBarActivity.java. We need to perform the following
tasks through the main Activity file:
1. Access the six Button controls from the layout file activity_demo_action_bar.xml and map them
to the respective Button objects.
2. Make the three Button controls hide the ActionBar, Activity's title, and application's logo. Also
make the hidden components visible through the rest of the three Button controls.
3. When the user selects the Actionview, search widget in the ActionBar, a text box should pop up
prompting for the text to search for.
4. Navigate to new Activity CreateActivity.class when action item create is select from ActionBar.
To perform all these tasks, the codes as shown below in Activity file DemoActionBarActivity. java.
package com. androidunleashed. demoactionbar;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.app.ActionBar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.content.Intent;
public class DemoActionBarActivity extends Activity {
Intent intent;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo_action_bar);
final ActionBar actionBar = getActionBar();
Button showAction = (Button) this.findViewById(R.id.show_action);
Button hideAction = (Button)this.findViewById(R.id.hide_action);
Button showTitle = (Button) this.findViewById(R.id.show_title);
Button hideTitle = (Button) this.findViewById(R.id.hide_title);
Button showLogo=(Button) this.findViewById(R.id.show_logo);
Button hideLogo = (Button) this.findViewById(R.id.hide_logo);
showAction.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
38
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
actionBar.show();
}
});
hideAction.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
actionBar.hide();
}
});
showTitle.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
actionBar.setDisplayShowTitleEnabled(true);
}
});
hideTitle.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
actionBar.setDisplayShowTitleEnabled(false);
}
});
showLogo.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
actionBar.setDisplayShowHomeEnabled(true);
}
});
hideLogo.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
actionBar.setDisplayShowHomeEnabled(false);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mymenu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
39
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
switch (item.getItemId()) {
case R.id.create_datab:
intent = new Intent(this, CreateActivity.class);
startActivity(intent);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}}
On running the application, we see output as shown below.
40
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
After copying the images, define the menu items in the menu file activity_action_bar_app.xml as
shown below.
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/create_datab"
android:title="CreateDatabase"
android:icon="@drawable/create"
android:orderlnCategory="0"
android:showAsAction="ifRoom|withText" />
<item android:id="@+id/insert_rows"
android:title="InsertRows"
android:icon="@drawable/insert"
android:showAsAction="ifRoom"/>
<item android:id="@+id/list_rows"
android:title="ListRows"
android:showAsAction="ifRoom"/>
<item android:id="@+id/search_row"
android:title="Search"
android:icon="@drawable/search"
android:showAsAction="ifRoom|withText"/>
<item android:id="@+id/delete_row"
android:title="Delete"
android:showAsAction="never"/ >
<item android:id="@+id/update_row"
android:title="Update"
android:icon="@drawable/update"
android:showAsAction="always" / >
</menu>
In the preceding code, we see that the showAsAction attribute is applied to different menu items to
determine whether they should appear in the ActionBar or in the Overflow menu.
To inflate or merge the menu that we defined in the activity_action_bar_app.xml file in our
application, we write the Java code as shown below in our Activity file ActionBarAppActivity.java.
package com. androidunleashed.actionbarapp;
import android.app.Activity ;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
public class ActionBarAppActivity extends Activity {
41
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_action_bar_app);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_action_bar_app, menu);
return true;
}
}
To display the menu or menu items in the ActionBar, we need to inflate or merge our menu defined
in the mymenu.xml file in the menu provided as a parameter to the onCreateoptionsMenu() method.
Initially, there is no menu item defined in the menu parameter. To inflate the menu that we defined
in the activity_action_bar_app.xml file, we get the MenuInflater from the Activity class. An object,
inflater, is Created Of the MenuInflater class, and its inflate method is called to inflate, or merge, our
own menu defined in the activity_action_bar_app.xmi file with menu parameter of this method.
On running the application, we get outout as shown below .
42
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
To display checkable menu items and submenus, and to apply shortcuts to the menu items in the same
way as we did in the MenuApp application, we write the code as shown below in the
activity_action_bar_app.xml.
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/create_datab"
android:title="CreateDatabase"
android:icon="@drawable/create"
android:showAsAction="ifRoom|withText" />
<item android:id="@+id/insert_rows"
android:title="InsertRows"
android:icon="@drawable/insert"
android:showAsAction="ifRoom"/>
<item android:id="@+id/list_rows"
android:title="List Rows"
android:showAsAction="ifRoom"/>
<item android:id="@+id/search_row"
android:title="Search"
android:icon="@drawable/search"
android:showAsAction="ifRoom|withText" >
<menu>
<group android:checkableBehavior="single">
<item android:id="@+id/search_code"
android:title="Search on Code"
android:checked="true"/>
<item android:id="@+id/search_name"
android:title="Search on Name"
android:alphabeticShortcut="n"
android:numericShortcut="6"/>
<item android:id="@+id/search_price"
android:title="Search on Price" />
</group>
</menu>
</item>
<item android:id="@+id/delete_row"
android:title="Delete"
android:showAsAction="never"
android:alphabeticShortcut="d"
43
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
android:checkable="true" />
<item android:id="@+id/update_row"
android:title="Update"
android:icon="@drawable/update"
android:showAsAction="always"
android:alphabeticShortcut="u"
android:numericShortcut="4" />
<menu>
We see that preceding code includes the android:showAsAction attribute to display menu items in
ActionBar if space permits. Also the <menu> element defined inside the search menu item defines the
submenu consisting of three menu items: Search on Code, Search on Name, and Search on Price.
The Delete menu item appears as a checkable menu item, as the android:checkable attribute is set to
the Boolean value true for this menu item. The android:alphabeticShortcut and the
android:numericShortcut define shortcut keys of the menu items.
The android:alphabeticshortcut attribute defines the shortcut key for the full keyboard, whereas the
android:numericShortcut attribute defines the shortcut key from the numeric keypad.
To show a response when a menu item is selected, we need to define a TextView control in the layout
file activity_action_bar_app.xmlas shown below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/selectedopt" />
</LinearLayout>
To identify the TextView in Java code, it is assigned the ID selectedopt. To display the response
when a menu item is selected, modify file ActionBarAppActivity .java to appear as shown below
package com. androidunleashed.actionbarapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
public class ActionBarAppActivity extends Activity {
44
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
private TextView selectedOpt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_action_bar_app);
selectedOpt=(TextView)findViewById(R.id.selectedopt);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.activity_action_bar_app, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.create_datab:
selectedOpt.setText("You have selected Create Database option");
break;
case R.id.insert_rows:
selectedOpt.setText("You have selected Insert Rows option");
break;
case R.id.list_rows:
selectedOpt.setText("You have selected List Rows option");
break;
case R.id.search_row:
selectedOpt.setText("You have selected Search Row option");
break;
case R.id.delete_row:
selectedOpt.setText("You have selected Delete Row option");
break;
case R.id.update_row:
selectedOpt.setText("You have selected Update Row option");
break;
case R.id.search_code:
selectedOpt.setText("You have selected Search on Code option");
break;
45
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
case R.id.search_name:
selectedOpt.setText("You have selected Search on Name option");
break;
case R.id.search_price:
selectedOpt.setText("You have selected Search on Price option");
break;
}
return true;
}
}
46
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
Just as the setText () method used in the preceding code sets the text of the tab, we can also call the
setIcon() method to define an image for the tab. Besides this, we can also call the
setcontentDescription() method to supply more detailed information of the tab.
Example:
Tab tab1 = actionBar.newTab();
tabOne.setText("Create")
.setIcon(R.drawable.ic_launcher)
.setContentDescription('Creating the Database")
.setTabListener(this));
actionBar.addTab(tab1);
The preceding code adds a tab with the text create to the tabbed ActionBar. The icon assigned to the
tab is the default icon ic_launcher, and a detailed description assigned is "creating the Database" to
inform the user about the purpose of the tab.
We can better understand the concept of the tabbed ActionBar by a running example. So, create a new
Android project called TabbedActionBarApp. In this application, we create two tabs, create and
update. When either tab is selected, a respective log message is displayed.
In the Java Activity file of the application, TabbedActionBarAppActivity.java, write the code as
shown in below.
package com.androidunleashed.tabbedactionbarapp;
import android.app.Activity;
import android.os.Bundle;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.util.Log;
public class TabbedActionBarAppActivity extends Activity implements
ActionBar.TabListener {
@Override
public void onCreate(Bundle savedlnstanceState) {
super.onCreate(savedlnstanceState);
final ActionBar actionBar=getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.addTab(actionBar.newTab().setText("Create").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Update").setTabListener(this));
}
@Override
47
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
public void onTabReselected(Tab tab, FragmentTransaction ft) {
Log.d("Tab", String. valueOf (tab. getPosition ()) + "re-selected");
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
Log.d("Tab", String.valueOf (tab.getPosition() ) + "selected");
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
Log.d("Tab", String.valueOf (tab.getPosition() ) + " Unselected");
}
}
In the preceding code, we can see that an ActionBar object, actionBar, is created by calling the
getActionBar() method. To make the ActionBar appear in the form of tabs, its navigation mode isset
to ActionBar .NAVIGATION_MODE_TABS.
The Activity title is made invisible by passing the Boolean value false to the
setDispiayshowTitieEnabled() method. Thereafter, two tabs with the text create and update are created
and added to the ActionBar.
The event listener TabListener is associated with both the tabs. When either tab is selected, the
onTabSelected() method is invoked, and the selected tab is passed to it as a parameter. The
onTabSelected() method displays the log message informing the position of the selected tab.
The position of tab is zero numbered; that is, first tab is considered to have the position 0, second tab
has position 1, and so on. When a tab is selected, onTabunselected() method is also called, and other
tab that is not selected is passed to it as the parameter. The onTabunselected()method displays the
position of the other tab that is not selected.
On running the application, we get output as shown below.
48
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
Creating a Drop-Down List ActionBar:
In a drop-down list ActionBar, the menu items are displayed in the form of a drop-down list. It is
popularly used for displaying the content within an Activity on basis of selection made by the user.
To display a drop-down list in an ActionBar, its setNavigationMode() method is called, passing the
value ActionBar.NAVIGATION_MODE_LIST as a parameter to it as shown here:
actionBar. setNavigationMode (ActionBar.NAVIGATI0N_M0DE_LIST) ;
The drop-down list as expected appears like a spinner, displaying a list of available options, allowing
us to select one of them. For displaying options in the drop-down list, we use the Adapter that
implements the SpinnerAdapter interface, like an ArrayAdapter or simpleCursorAdapter.
We use an ArrayAdapter in this application. First, we define a string array containing the strings that
we want to be displayed in the drop-down list. Thereafter, we create an ArrayAdapter that displays
the elements of the array in the form of drop-down items.
Finally, ArrayAdapter is assigned to ActionBar for displaying menu items. To assign ArrayAdapter
to the ActionBar and to attach the event listener to the drop-down items that are displayed,
setListNavigationCallbacks() method is called, passing adapter and onNavigationListener to it as
parameters as shown in the following code:
String[] items = new String[] { "Create", "Insert", "Update", "Search" };
ArrayAdapter<String> adapter = new
ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item, items);
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actionBar.setListNavigationCallbacks(adapter, onNavigationltemSelected);
In the preceding code, the string array items are defined consisting of the strings that we want to
display in the drop-down list ActionBar. An ArrayAdapter called adapter is created comprising the
string array items and casting the array elements in the spinner drop-down items.
An ActionBar object actionBar is created and its navigation mode is set to
ActionBar,NAVIGATION_MODE_LIST. The setListNavigationCallbacks() method is called on the
actionBar passing the ArrayAdapter, adapter, and listener, onNavigationselected, to it as parameters.
When a user selects an item from the drop-down list, the onNavigationItemSelected handler is called
where we can write the code to perform the desired action.
Let's create a new Android project called ListActionBarApp. In this application, we display a few
menu items in form of drop-down list, and when any menu item is selected, respective log message
is displayed. Write the code as shown below in ListActionBarAppActivity. java
package com. androidunleashed.listactionbarapp;
import android.app.Activity;
import android.os.Bundle;
import android.app.ActionBar.OnNavigationListener;
49
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
import android.app.ActionBar;
import android.widget .ArrayAdapter;
import android.util.Log;
public class ListActionBarAppActivity extends Activity {
public void onCreate(Bundle savedlnstanceState) {
super.onCreate(savedlnstanceState);
String[] items = new String[] { "Create", "Insert", "Update", "Search" };
ArrayAdapter<String>adapter=new
ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item, items);
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actionBar.setListNavigationCallbacks(adapter, onNavigationltemSelected);
}
OnNavigationListener onNavigationltemSelected = new OnNavigationListener() {
@Override
public boolean onNavigationItemSelected(int itemPosition, long itemld) {
Log.d("Option ", String.valueOf(itemld) + " is selected");
return true;
}
}; }
In the preceding code, we notice that when an item from the drop-down list is selected, the
onNavigationItemSelected () method is called. The parameters itemPosition and itemId in the
onNavigationItemSelected() method contain information about the position and ID of selected item.
A log message is displayed in this method displaying ID of selected item. The IDs are sequentially
assigned to the items in the dropdown list beginning with 0. To enable the ActionBar, don't forget to
set the value of android :minSdkVersion attribute to 11 or higher in the AndroidManifest.xml file.
On running the application, we get output as shown below
50
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
UNIT- V(B)
USING DATABASES
Using the SQLiteOpenHelper Class:
Android databases are stored in the /data/data/<package_ name>/databases folder on
devices or emulators.
To create an Android application that stores, accesses, and manipulates user information in a
SQLite-relational database, we use the SQLiteOpenHelper class.
The SQLiteOpenHelper class is an abstract class that provides a way to get read or write access
to a database and used to create, open, and upgrade databases.
SQLiteOpenHelper class provides several methods including getWritableDatabase(),
getReadableDatabase(), and close().
The SQLiteDatabase class also provides methods including insert() and query(), which are
used to insert rows in database table and execute different SQLite queries on database table.
The query() method accepts several parameters such as the database table to query, columns,
and criteria, and returns a cursor representing the rows that satisfy the supplied criteria.
The cursor class provides several methods to traverse the result set and move to the desired
row and column position in the result set.
To understand how the information in an Android application can be stored and accessed from
an SQLite database, let's create a new Android application.
1
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
2
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
return this;
}
public void close(){
helper.close();
}
public void addRow(Integer c, String n, Float p) {
ContentValues newProduct = new ContentValues();
newProduct.put("code", c);
newProduct.put("product_name", n);
newProduct.put("price", p);
try {
db.insertOrThrow(DB_TABLE, null, newProduct);
} catch (Exception e) {
Log.e("Error in inserting rows", e.toString());
e.printStackTrace();
}
}
public String retrieveRows(){
String[] columns = new String[]{"code", "product_name", "price"};
Cursor cursor = db.query(DB_TABLE, columns, null, null, null, null, null);
String tablerows = "";
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
tablerows = tablerows + cursor.getInt(0) + ", "+cursor.getString(1)+", " +
cursor.getFloat(2)+ "\n";
cursor.moveToNext();
}
if (cursor != null && !cursor. isClosed() ) {
cursor.close();
}
return tablerows;
}
public class SQLHelper extends SQLiteOpenHelper {
public SQLHelper(Context c){
super(c, DB_NAME, null, DB_VERSION);
}
3
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
@Override
public void onCreate(SQLiteDatabase db) {
db . execSQL (CREATE_TABLE) ;
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("Products table","Upgrading database i.e. dropping table and recreating it");
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
onCreate(db);
}
}
}
The DatabaseManager is a class where we write all the methods related to database
maintenance such as creating databases and tables, upgrading tables, and adding and retrieving
rows to and from the database table.
To make our task easier, the DatabaseManager Class includes a SQLHelper class, which inherits
the SQLiteOpenHelper class.
The SQLHelper class instance, helper, is created by passing the context to its constructor. The
SQLHeiper's constructor in turn invokes the constructor of the SQLiteOpenHelper class passing
the context database name (shopping) and its version number (1) to it.
The SQLiteOpenHelper class provides two methods,getWritableDatabase() and getReadable
Database() are used to open and return writable and readable instance of referred database.
We can see that the getWritableDatabase() method is called on by the helper instance to get an
SQLiteDatabase object called db. The SQLiteDatabase object, db, now refers to the shopping
database that is opened in write mode, and we can perform write operations on the database.
The SQLiteOpenHelper onCreate and onUpgrade class methods are overridden in the SQLHelper
class to create a new database and to upgrade it to a new version.
The onCreate() method creates a products table in the shopping database by calling the
execSQL() SQLiteDatabase method through its object, db.
The products database table consists of three columns: code, product_name, and price, where
code is the primary key in the products table. In the onUpgrade method, the existing table,
products, is dropped and re-created.
The openReadable () method Calls the getReadableDatabase () on the helper Object to get the
SQLiteDatabase object db that refers to the readable instance of the shopping database. The
close () method calls the close () method on the helper class to close it.
4
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
The addRow() method accepts the values for the new row of the products table as parameters
and inserts them in the products table by calling the SQLiteDatabase insertOrThrow() method
through its object db.
The content values is used to insert rows in the products table. Each ContentValues object
represents a single table row as a map of column names to values.
A ContentValues object, newProduct, is created, and through its put() methods, we supply the
code, product_name, and price columns' values.
Thereafter, the insertOrThrow () method is called, and the ContentValues object, newProduct,
is passed to it to insert a new row in the table, supplying the content specified in the
ContentValues object.
The retrieveRows() method fetches all the rows from the products table by executing the
query() method of the SQLiteDatabase object and returns in the form of a cursor object.
The query() method helps in running the query with the specified criteria to get the desired
number of rows.
Parameter Usage
bool_uniq Optional Boolean value to determine whether the result set should contain only
unique values. A True value confirms the unique values in the result set.
db_table The database table to be queried.
array_columns A string array containing the list of columns we want in the result set.
where_clause Defines the criteria for the rows to be returned. For specifying values in the
clause, ? wildcard(s) are used, which are then replaced by the values stored in
the select_arg parameter.
select_arg An array of strings that provide values for the ? wildcards used in the
where_clause parameter.
group_by Defines the condition for grouping the returned result set.
having_clause Defines the conditions to be applied to the groups defined in group_ by clause.
order Defines the order of the returned rows.
5
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
Examples:
The following two queries return all the products table rows for the code, product_name, and
price columns. The first query confirms that only unique rows should be fetched:
String whereClause="product_name=Camera";
String order="code";
Cursor cursor = db.query(DB_TABLE, columns, whereClause, null, null, null, order);
The returned rows from the query() method are in the form of Cursor objects. A Cursor object
does not create a separate result set of the extracted rows, but points at the result set that is
part of a database table.
When we call the moveToFirst() method on the cursor object, the cursor is moved to the first
row in the result set. Thereafter, all the products table rows that exist in the cursor object are
fetched one by one by calling the moveToNext() method and returned.
The cursor is closed when all the rows pointed at in its result set are traversed.
Using Cursors
Cursors are pointers pointing at the result set of the underlying data and can be set to traverse
the rows and retrieve column data of the result set.
The Cursor class provides several methods that can be used to set the pointer at the desired
row and column position of the result set.
Method Usage
moveToFirst Moves the cursor to the first row in the result set
moveToNext Moves the cursor to the next row
moveToPrevious Moves the cursor to the previous row
getCount Returns the count of the rows in the result set
getColumn Returns the index for the column with the specified name. It throws
IndexOrThrow an exception if no column exists with that name
getColumnName Returns the column name with the specified column index
getColumnNames Returns a string array that contains all the column names in the
current cursor
moveToPosition Moves the cursor to the specified row
getPosition Returns the current cursor position
6
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
The DatabaseManager class is accessed through an instance created in our Activity file. Let's
write the code for it. Modify the DatabaseAppActivity.java file to appear as shown below
package com.androidunleashed.databaseapp;
import android.app.Activity;
import android.os.Bundle;
import android. widget.TextView ;
public class DatabaseAppActivity extends Activity {
private DatabaseManager mydManager;
private TextView response;
private TextView productRec;
@Override
public void onCreate(Bundle savedlnstanceState) {
super.onCreate(savedlnstanceState);
setContentView(R.layout.activity_database_app);
response = (TextView) findViewById(R.id.response);
productRec = (TextView) findViewById(R.id.prodrec);
mydManager = new DatabaseManager(this);
mydManager.addRow(101, "Camera", Float.parseFloat("15"));
mydManager.addRow(102, "Laptop", Float.parseFloat("1005.99"));
mydManager.close();
mydManager = new DatabaseManager(this);
mydManager.openReadable();
String tableContent = mydManager.retrieveRows();
response.setText("The rows in the products table are:");
productRec.setText(tableContent);
mydManager.close();
}
}
We can see that Textview controls with the response and prodrec IDs are captured from the
layout file activity_database_app.xml and mapped to the Textview objects, response and
productRec, respectively.
To access different methods defined in the DatabaseManager Java class that we just created
above, its instance is created called mydManager.
Through the mydManager instance, we access the addRow() method Of DatabaseManager to
add two rows to the products table of our shopping database.
7
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
After we insert the rows in the products table, mydManager is closed so that it can be re-
created to open the database in read mode.
The readable database instance is obtained by calling the openReadable() method of the
DatabaseManager class through its instance mydManager.
The text in response Textview control is Set to “The rows in products table are:” . The text is a
header for the products rows that are displayed through another Textview control.
All the rows in the products table are accessed by calling the retrieveRows() method and
displayed via the Textview object productRec.
To define two Textview controls in activity_database_app.xml, use the code shown below.
LISTING 8.3 Code Written into the Layout File activity_database_app.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height= "match_parent" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/response"/>
<TextView
android:id="@+id/prodrec"
android:layout_width="match_parent"
android:layout_height= "wrap_content" />
</LinearLayout>
After running application, rows in the products database table are displayed, as shown below.
8
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
The ls /data/data command shows the list of files and directories in the subdirectory of the
data directory. We see the list of all installed applications in the emulator. The installed
application's package names are also displayed:
# ls /data/data
ls /data/data
com.android.mms
com.android.googlesearch
9
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
com.android.launcher
:::::::::::
:::::::::::
com.androidunleashed.databaseapp
The following command shows the content of the application package's databases
directory:
#ls/data/data/com.androidunleashed.databaseapp/databases
ls/da ta/data/com.androidunleashed.databaseapp/databases shopping
The output, shopping, confirms that the shopping database has been created in our
application package com.androidunleashed.databaseapp.
Let's go into the databases directory of our application package:
#cd /data/data/com.androidunleashed.databaseapp/databases
cd /data/data/com.androidunleashed.databaseapp/databases
On executing the ls command, we see the list of files and directories in the databases
subdirectory. As expected, the name of our shopping database is displayed:
#ls
ls
shopping
we make the shopping database active by using the sqlite3 shopping command:
#sqlite3 shopping
sqlite3 shopping
SQLite version 3.5.9
Enter ".help" for instructions
The SQLite version information is displayed with the directive to type the .help command
to see help instructions. We also see an sqlite>prompt to issue database related commands.
The .tables command displays the tables that exist in the currently active database:
sqlite> .tables
.tables
Android_metadata products
The .schema command displays the structure (field names, their types, width, and so on)
of all the tables that exist in the currently active database:
sqlite> .schema
.schema
CREATE TABLE android_metadata (locale TEXT);
10
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
CREATE TABLE products (code INTEGER PRIMARY KEY, product_name TEXT, price
FLOAT);
The SQL SELECT command can be used to see the number of rows in the products table of
our shopping database:
sqlite> select * from products;
select * from products;
101|Camera|15.0
102|Laptop|1005.98999023438
This output confirms that our DatabaseApp application successfully inserted two rows
into the products table.
We can also issue an SQL DELETE command to delete a row. The following command deletes
a row from the products table that has a product code equal to 102.
sqlite> delete from products where code=102;
delete from products where code=102;
To confirm that the row was really deleted, we can give a SQL SELECT command as shown
here:
sqlite> select * from products;
select * from products;
101|Camera|15.0
This output shows only one row in the products table, confirming that one of the two rows
was deleted. Similarly we can give an SQL UPDATE command to update or modify the
information of any row.
The following SQL UPDATE command updates the product name to Handy cam, whose code
is equal to 101.
sqlite> update products set product_name='Handy Cam' where code=101;
update products set product_name='Handy Cam' where code=101;
We can confirm whether the row was successfully updated by issuing an SQL SELECT
command:
sqlite> select * from products;
select * from products;
101|Handy Cam|15.0
The preceding output confirms that the product name was updated. se. When finished, we
can leave the sqlite> prompt by giving an .exit command:
sqlite>.exit
11
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
12
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_database_app);
response = (TextView) findViewById(R.id.response);
productRec = (TextView) findViewById(R.id.prodrec);
response.setText("Press MENU button to display menu");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_database_app, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.insert_rows:
insertRec();
break;
case R.id.list_rows:
showRec();
break;
}
return true;
}
public boolean insertRec() {
mydManager = new DatabaseManager(this);
mydManager.addRow(101, "Camera", Float.parseFloat("15"));
13
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
14
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
15
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
android:padding="3dip" />
<EditText
android:id="@+id/prod_code"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</TableRow>
<TableRow>
<TextView
android:text="Product Name:"
android:padding="3dip" />
<EditText
android:id="@+id/prod_name"
android:layout_width="wrap_content"
android:1ayout_height="wrap_content"
android:minwidth="150dip"/>
</TableRow>
<TableRow >
<TextView
android:text="Product Price:"
android:padding="3dip" />
<EditText
android:id="@+id/prod_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minwidth="5Odip" />
</TableRow>
<TableRow >
<Button
android:id="@+id/add_button"
android:text="Add Product"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="3dip" />
<Button
android:id="@+id/cancel_button"
android:text="Cancel"
16
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="3dip" />
</TableRow>
</TableLayout>
</LinearLayout>
We can see that the three TextView controls are set to display the text Product code:, product
Name:, and Product Price:. The captions in the two Button controls are set to Add Product and
Cancel.
The IDs assigned to the three EditText controls are prod code, prod_name, and prod_price. The
Button controls are assigned the IDs add_button and cancel_button.
package com. Androidunleashed.databaseapp ;
import android.database.sqlite.SQLiteDatabase;
import android.content.Context;
import android.content.ContentValues;
import android.database .Cursor;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseManager{
public static final String DB_NAME = "shopping";
public static final String DB_TABLE = "products";
public static final int DB_VERSION =1;
private static final String CREATE_TABLE = "CREATE TABLE " + DB_TABLE + " (code
INTEGER PRIMARY KEY, product_name TEXT, price FLOAT);";
private SQLHelper helper;
private SQLiteDatabase db;
private Context context ;
public DatabaseManager(Context c){
this.context = c;
helper=new SQLHelper(c);
this.db = helper.getWritableDatabase();
}
public DatabaseManager openReadable() throws android.database.SQLException {
helper=new SQLHelper(context);
db = helper.getReadableDatabase();
return this;
17
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
}
public void close(){
helper.close();
}
public boolean addRow(Integer c, String n, Float p) {
ContentValues newProduct = new ContentValues();
newProduct.put("code", c);
newProduct.put("product_name", n);
newProduct.put("price", p);
try {
db.insertOrThrow(DB_TABLE, null, newProduct);
} catch (Exception e) {
Log.e("Error in inserting rows", e.toString());
e.printStackTrace();
return false;
}
db.close();
return true;
}
public String retrieveRows(){
String[] columns = new String[]{"code", "product_name", "price"};
Cursor cursor = db.query(DB_TABLE, columns, null, null, null, null, null);
String tablerows = "";
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
tablerows = tablerows + cursor.getInt(0) + ", "+cursor.getString(1)+", " +
cursor.getFloat(2)+ "\n";
cursor.moveToNext();
}
if (cursor != null && !cursor. isClosed() ) {
cursor.close();
}
return tablerows;
}
public class SQLHelper extends SQLiteOpenHelper {
public SQLHelper(Context c){
18
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
19
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
public class DatabaseAppActivity extends Activity {
private DatabaseManager mydManager;
private TextView response;
private TextView productRec;
EditText pcode, pname, price;
Button addButton;
private TableLayout addLayout;
private boolean recInserted;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_database_app);
response=(TextView)findViewById(R.id.response);
productRec=(TextView)findViewById(R.id.prodrec);
addLayout=(TableLayout)findViewById(R.id.add_table);
addLayout.setVisibility(View.GONE);
response.setText("Press MENU button to display menu");
Button addButton = (Button) findViewById(R.id.add_button);
addButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mydManager = new DatabaseManager(DatabaseAppActivity.this);
pcode=(EditText)findViewById(R.id.prod_code);
pname=(EditText)findViewById(R.id.prod_name);
price=(EditText)findViewById(R.id prod_price);
recInserted=mydManager.addRow(Integer.parseInt(pcode.getText(). toString()),
pname.getText().toString(), Float.parseFloat (price.getText().toString()));
addLayout.setVisibility(View.GONE);
if(recInserted)
response.setText("The row in the products table is inserted");
20
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
else
response.setText("Sorry, some errors occurred while inserting row in products table");
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(price.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
mydManager.close();
pcode.setText("");
pname.setText("");
price.setText("");
productRec.setText("");
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater ();
inflater.inflate(R.menu.activity_database_app, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId() ) {
case R.id.insert_rows: addLayout.setVisibility(View.VISIBLE);
response.setText("Enter information of the new product");
productRec.setText("");
break;
case R.id.list_rows: showRec();
break;
}
return true;
}
public boolean showRec(){
addLayout.setVisibility(View.GONE);
mydManager = new DatabaseManager(this);
mydManager.openReadable();
21
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
22
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
After we select the insert Rows menu item, a form is displayed for entering new product
information. A Textview at the top displays the text Enter information of the new product.
The user can enter the new product information then click the Add Product button to add a
new row into the products table. If the row is successfully inserted, the message The row in
the products table is inserted appears on the screen.
After we select the List Rows menu item, the newly added row is displayed on the screen.
23
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
android:layout_height="match_parent"
android:drawSelectorOnTop="false"/>
<TableLayout
android:id="@+id/add_table"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TableRow >
<TextView
android:text="Product Code:"
android:padding="3dip" />
<EditText
android:id="@+id/prod_code"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</TableRow>
<TableRow>
<TextView
android:text="Product Name:"
android:padding="3dip" />
<EditText
android:id="@+id/prod_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow >
<TextView
android:text="Product Price:"
android:padding="3dip" />
<EditText
android:id="@+id/prod_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</TableRow>
<TableRow >
<Button
android:id="@+id/add_button"
24
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
android:text="Add Product"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="3dip" />
<Button
android:id="@+id/cancel_button"
android:text="Cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="3dip" />
</TableRow>
</TableLayout>
</LinearLayout>
In DatabaseManager.java file, we need to modify the retrieveRows( ) method return type to
ArrayList<String> to display data via a ListView control. A productRows of ArrayList<String>
variable data type is defined, and every row fetched from the products table is added to it.
The method returns the variable productRows, containing the products table rows in the
ArrayList format. The Java file DatabaseManager. java is modified to appear as shown below.
package com.androidunieashed.databaseapp;
package com.example.cselab.databaseapp;
import android.database.sqlite.SQLiteDatabase;
import android.content.Context;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
public class DatabaseManager {
public static final String DB_NAME = "shopping";
public static final String DB_TABLE = "products";
public static final int DB_VERSION = 1;
private static final String CREATE_TABLE = "CREATE TABLE " + DB_TABLE + " (code
INTEGER PRIMARY KEY, product_name TEXT, price FLOAT);";
private SQLHelper helper;
private SQLiteDatabase db;
private Context context;
25
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
26
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
}
if (cursor != null && !cursor.isClosed( )) {
cursor.close();
}
return productRows;
}
public class SQLHelper extends SQLiteOpenHelper {
public SQLHelper(Context c){
super(c, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("Products table","Upgrading database i.e. dropping table and rec¬reating it");
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
onCreate(db);
}
}
}
Again, In showRec() method, we write the code to access the Listview control from the layout
file and map it to the Listview object, productRec.
The rows returned by calling the retrieveRows() method of DatabaseManager in the
ArrayList<string> format are temporarily stored in the variable tableContent.
An ArrayAdapter called arrayAdpt is created through the tableContent array. Finally, the
ArrayAdapter, arrayAdpt, is set to the Listview control productRec to display the products
table rows in the Listview control. DatabaseAppActivity.java is modified like below.
package com.androidunleashed.databaseapp;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.TextView;
import android.view.Menu;
import android.view.MenuInflater;
27
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import java.util.ArrayList;
public class DatabaseAppActivity extends Activity {
private DatabaseManager mydManager;
private TextView response;
private ListView productRec;
EditText pcode, pname, price;
Button addButton;
private TableLayout addLayout;
private Boolean recInserted;
ArrayList<String> tableContent;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_database_app);
response = (TextView) findViewById(R.id.response);
productRec = (ListView) findViewById(R.id.prodrec);
addLayout = (TableLayout) findViewById(R.id.add_table);
addLayout.setVisibility(View.GONE);
response.setText("Press MENU button to display menu");
Button add_button = (Button) findViewById(R.id.add_button);
add_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mydManager = new DatabaseManager(DatabaseAppActivity.this);
pcode = (EditText) findViewById(R.id.prod_code);
pname = (EditText) findViewById(R.id.prod_name);
price = (EditText) findViewById(R.id.prod_price);
recInserted =
28
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
mydManager.addRow(Integer.parseInt(pcode.getText().toString()),
pname.getText().toString(), Float.parseFloat(price.getText().toString()));
addLayout.setVisibility(View.GONE);
if (recInserted)
response.setText("The row in the products table is inserted");
else
response.setText("Sorry, some errors occurred while inserting the row in
the products table");
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(price.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
mydManager.close();
pcode.setText("");
pname.setText("");
price.setText("");
productRec.setVisibility(View.GONE);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_database_app, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.insert_rows:
addLayout.setVisibility(View.VISIBLE);
response.setText("Enter information of the new product");
productRec.setVisibility(View.GONE);
break;
case R.id.list_rows:
showRec();
29
IV.BTECH I-SEM, CSE: MOBILE APPLICATION DEVELOPMENT
break;
}
return true;
}
public boolean showRec() {
addLayout.setVisibility(View.GONE);
mydManager = new DatabaseManager(this);
mydManager.openReadable();
tableContent = mydManager.retrieveRows();
response.setText("The rows in the products table are:");
productRec = (ListView) findViewById(R.id.prodrec);
ArrayAdapter<String> arrayAdpt = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, tableContent);
productRec.setAdapter(arrayAdpt);
productRec.setVisibility(View.VISIBLE);
mydManager.close();
return true;
}
}
Our application is updated to show the database table rows via a Listview control. After
running the application, we get output as shown below.