0% found this document useful (0 votes)
9 views90 pages

UNIT II MobileAppDevelopment

The document contains notes on Mobile Application Development, focusing on working with the user interface using views, understanding components of a screen, and adapting to display orientation. It covers various topics including views, viewgroups, action bars, and UI creation programmatically, as well as specialized fragments and data management techniques. The notes serve as a comprehensive guide for developing mobile applications with a strong emphasis on user interface design and functionality.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views90 pages

UNIT II MobileAppDevelopment

The document contains notes on Mobile Application Development, focusing on working with the user interface using views, understanding components of a screen, and adapting to display orientation. It covers various topics including views, viewgroups, action bars, and UI creation programmatically, as well as specialized fragments and data management techniques. The notes serve as a comprehensive guide for developing mobile applications with a strong emphasis on user interface design and functionality.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Dr.

Geetha Lakshmi
Department of Computer Applications
Dayananda Sagar College of Arts, Science and Commerce

Mobile Application Development


Unit II Notes
Mobile Application Development Unit II Notes Dr. Geetha

Contents
1 Working with the User Interface Using Views 4
1.1 Understanding the Components of a Screen . . . . . . . . . . . . 4
1.1.1 Views and Viewgroups . . . . . . . . . . . . . . . . . . . . 4
1.1.2 Common Attributes Used in Views and ViewGroups . . . 8
1.2 Adapting to Display Orientation . . . . . . . . . . . . . . . . . . 9
1.3 Managing Changes to screen orientation . . . . . . . . . . . . . . 9
1.3.1 Inside ⟨activity⟩ . . . . . . . . . . . . . . . . . . . . . . . 10
1.3.2 Inside [Link] . . . . . . . . . . . . . . . . . . . 10
1.4 Utilizing the action bar . . . . . . . . . . . . . . . . . . . . . . . 10
1.4.1 Changing the ActionBar Title . . . . . . . . . . . . . . . . 11
1.4.2 Displaying ActionBar Icon . . . . . . . . . . . . . . . . . . 12
1.4.3 Adding Action Items . . . . . . . . . . . . . . . . . . . . . 12
1.5 Creating the user interface programmatically . . . . . . . . . . . 13
1.5.1 Creating the UI via Code ([Link]) . . . . . . . . . . 14
1.5.2 How It Works . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.6 Listening for UI notifications . . . . . . . . . . . . . . . . . . . . 16
1.6.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.6.2 Designing Your User Interface with Views . . . . . . . . . 17

2 Using Basic Views 17


2.1 TextView View . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.2 Button, imageButton, edittext, CheckBox, toggleButton, radioBut-
ton, and radiogroup Views . . . . . . . . . . . . . . . . . . . . . . 19
2.3 Using the Basic Views ([Link]) . . . . . . . . . . . . . . 20
2.4 Using picker Views . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.4.1 Timepicker View . . . . . . . . . . . . . . . . . . . . . . . 22
2.4.2 Datepicker View . . . . . . . . . . . . . . . . . . . . . . . 25
2.5 Using list Views to Display long lists . . . . . . . . . . . . . . . . 27
2.5.1 ListView Attributes . . . . . . . . . . . . . . . . . . . . . 28
2.5.2 Example of list view using Array Adapter . . . . . . . . . 29
2.5.3 Spinner View . . . . . . . . . . . . . . . . . . . . . . . . . 32

3 Understanding specialized Fragments 33


3.1 Using a ListFragment . . . . . . . . . . . . . . . . . . . . . . . . 33
3.2 Creating and Using a List Fragment . . . . . . . . . . . . . . . . 33
3.3 Using a DialogFragment . . . . . . . . . . . . . . . . . . . . . . . 35
3.4 Creating and Using a Dialog Fragment . . . . . . . . . . . . . . . 35
3.5 Using a preferenceFragment . . . . . . . . . . . . . . . . . . . . . 37
3.5.1 Creating and Using a preference Fragment . . . . . . . . . 38
3.5.2 How it works? . . . . . . . . . . . . . . . . . . . . . . . . 40
Mobile Application Development Unit II Notes Dr. Geetha

4 ImageView in Android 41
4.0.1 Adding an ImageView to an Activity . . . . . . . . . . . . 42
4.0.2 XML Attributes of ImageView . . . . . . . . . . . . . . . 44
4.0.3 Step by Step Implementation . . . . . . . . . . . . . . . . 44
4.0.4 Android - Image Switcher . . . . . . . . . . . . . . . . . . 45
4.0.5 GridView . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
4.0.6 How It Works . . . . . . . . . . . . . . . . . . . . . . . . . 48

5 Using menus With Views 49


5.0.1 Creating the helper methods . . . . . . . . . . . . . . . . 49
5.1 Creating the Menu helper Methods . . . . . . . . . . . . . . . . . 49
5.2 How It Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
5.3 Options Menu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
5.4 How It Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
5.5 Context menu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

6 Android - WebView 56
6.1 Saving and loading user preferences . . . . . . . . . . . . . . . . . 61
6.2 Android - Shared Preferences . . . . . . . . . . . . . . . . . . . . 62

7 Android - Internal Storage 67


7.1 Writing file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
7.2 Reading file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
7.3 Persisting Data to Files . . . . . . . . . . . . . . . . . . . . . . . 74
7.4 How It Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
7.5 Choosing the Best storage option . . . . . . . . . . . . . . . . . . 81
7.6 Creating and using dataBases . . . . . . . . . . . . . . . . . . . . 81
7.7 Creating the dBadapter helper Class . . . . . . . . . . . . . . . . 82
7.8 How it works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84

8 Using the Database Programmatically 86


8.0.1 Adding Contacts . . . . . . . . . . . . . . . . . . . . . . . 86
8.1 How It Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
8.2 Retrieving all the Contacts . . . . . . . . . . . . . . . . . . . . . 86
8.3 How It Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
8.4 Retrieving a Single Contact . . . . . . . . . . . . . . . . . . . . . 88
8.5 How It Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
8.6 Updating a Contact in a table . . . . . . . . . . . . . . . . . . . . 89
8.7 How It Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
8.8 Deleting a Contact . . . . . . . . . . . . . . . . . . . . . . . . . . 89
8.9 How It Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
8.10 Upgrading the Database . . . . . . . . . . . . . . . . . . . . . . . 90
Mobile Application Development Unit II Notes Dr. Geetha

Unit II: Working with the User Interface Using views Understanding
the Components of a Screen - Adapting to Display Orientation - Managing
changes to Screen Orientation - Utilizing the Action Bar - Creating the User
Interface Programmatically Listening for UI Notification.
Using Basic Views Using Picker Views - Using List Views to Display Long
Lists - Understanding Specialized fragments - Using Image Views to Display
Pictures - Using Menus with Views using WebView - Saving and Loading User
Preferences - Persisting Data to Files - Creating and Using Databases.

1 Working with the User Interface Using Views


1.1 Understanding the Components of a Screen
• The basic unit of an Android application is an activity, which displays the
UI of your application.
• You define your UI using an XML file (for example, the activity [Link]
file located in the res/layout folder of your project)
• During runtime, you load the XML UI in the onCreate() method handler
in your Activity class, using the setContentView() method of the Activity
class:

@Override
public void onCreate ( Bundle s a v e d I n s t a n c e S t a t e ) {
super . onCreate ( s a v e d I n s t a n c e S t a t e ) ; setCont entView ( R . layout . main ) ;
}

1.1.1 Views and Viewgroups


• An activity contains views and ViewGroups.
• A view is a widget that has an appearance on screen. Examples of views
are buttons, labels, and text boxes.
• A view derives from the base class [Link]
• One or more views can be grouped into a ViewGroup.
• A ViewGroup (which is itself a special type of view) provides the layout
in which you can order the appearance and sequence of views.
• Examples of ViewGroups include RadioGroup and ScrollView. A View-
Group derives from the base class [Link].
• Another type of ViewGroup is a Layout
• A Layout is another container that derives from android .[Link]
and is used as a container for other views.
Mobile Application Development Unit II Notes Dr. Geetha

• However, whereas the purpose of a ViewGroup is to group views logi-


cally— such as a group of buttons with a similar purpose—a Layout is
used to group and arrange views visually on the screen.

ss

Following are common attributes and will be applied to all the layouts
1. android:id
This is the ID which uniquely identifies the view
2. android:layout width
This is the width of the layout.
3. android:layout height
This is the height of the layout
4. android:layout marginTop
This is the extra space on the top side of the layout.
5. android:layout marginBottom
This is the extra space on the bottom side of the layout.
6. android:layout marginLeft
This is the extra space on the left side of the layout.
7. android:layout marginRight
This is the extra space on the right side of the layout.
8. android:layout gravity
This specifies how child Views are positioned from top bottom left and
write from the window.
9. android:layout weight
This specifies how much of the extra space in the layout should be allocated
to the [Link] distributes the available space among the child views.
10. android:layout x
This specifies the x-coordinate of the layout.
11. android:layout y
This specifies the y-coordinate of the layout.
Mobile Application Development Unit II Notes Dr. Geetha

12. android:layout width


This is the width of the layout.
13. android:paddingLeft
This is the left padding filled for the layout.

14. android:paddingRight
This is the right padding filled for the layout.
15. android:paddingTop
This is the top padding filled for the layout.
16. android:paddingBottom
This is the bottom padding filled for the layout.
The Layouts available to you in Android are as follows:
• ConstraintLayout
• FrameLayout

• LinearLayout (Horizontal) and LinearLayout (Vertical)


• TableLayout
• RelativeLayout

• ScrollView
• Grid view
ConstraintLayout
• ConstraintLayout is a ViewGroup subclass,Whenever you open the an-
droid studio framework the application will be present in the constraint
layout.
• In this we have to set the constraint in all four sides.
• This is the default layout.

Framelayout
• FrameLayout is a ViewGroup subclass, The FrameLayout is the most basic
of the Android layouts. FrameLayouts are built to hold one view.
• You can add multiple views to a FrameLayout, but each is stacked on top
of the previous one. This is when you want to animate a series of images,
with only one visible at a time.
Mobile Application Development Unit II Notes Dr. Geetha

Linearlayout (horizontal) and linearlayout (Vertical)


• LinearLayout is a ViewGroup subclass,The LinearLayout arranges views
in a single column or a single row. Child views can be arranged either
horizontally or vertically, which explains the need for two different lay-
outs—one for horizontal rows of views and one for vertical columns of
views.
• LinearLayout(Horizontal) and LinearLayout(Vertical)
• the android:orientation property of the LinearLayout controls if the appli-
cation has a horizontal or vertical flow.

Tablelayout
• TableLayout is a ViewGroup subclass,The TableLayout Layout groups
views into rows and columns. You use the ¡TableRow¿ element to desig-
nate a row in the table. Each row can contain one or more views.

• Each view you place within a row forms a cell. The width of each column
is determined by the largest width of each cell in that column.
Relativelayout
• RelativeLayout is a ViewGroup subclass,The RelativeLayout layout en-
ables you to specify how child views are positioned relative to each other.

• Each view embedded within the RelativeLayout has attributes that enable
it to align with another view.
• These attributes are as follows:
– layout alignParentTop
– layout alignParentStart
– layout alignStart
– layout alignEnd
– layout below
– layout centerHorizontal
ScrollView
• A ScrollView is a special type of FrameLayout in that it enables users to
scroll through a list of views that occupy more space than the physical
display.

• The ScrollView can contain only one child view or ViewGroup, which
normally is a LinearLayout.
Mobile Application Development Unit II Notes Dr. Geetha

GridView
• GridView is a ViewGroup that displays items in a two-dimensional, scrol-
lable grid.
ListView
• ListView is a view group that displays a list of scrollable items.
• android:layout width=wrap content tells your view to size itself to
the dimensions required by its content.
This attribute tells the view to size itself to fit the content of its children.
For example, if you have a TextView with wrap content, the view will be
sized to fit the text it contains.
• android:layout width=fill parent tells your view to become as big as
its parent view.
This attribute instructs the view to expand to fill the entire available space
in its parent layout.
When you set a view’s width or height to match parent, it will expand to
fill the available space in its parent.
These attributes are important for controlling the layout and appearance of
views within your Android app’s user interface.

1.1.2 Common Attributes Used in Views and ViewGroups


1. layout width
Specifies the width of the view or ViewGroup
2. layout height
Specifies the height of the view or ViewGroup
3. layout marginTop
Specifies extra space on the top side of the view or ViewGroup
4. layout marginBottom
Specifies extra space on the bottom side of the view or ViewGroup
5. layout marginLeft
Specifies extra space on the left side of the view or ViewGroup
6. layout marginRight
Specifies extra space on the right side of the view or ViewGroup
7. layout gravity
Specifies how child views are positioned
8. layout weight
Specifies how much of the extra space in the layout should be allocated to
the view
Mobile Application Development Unit II Notes Dr. Geetha

9. layout x
Specifies the xcoordinate of the view or ViewGroup
10. layout y
Specifies the ycoordinate of the view or ViewGroup

1.2 Adapting to Display Orientation


• One of the key features of modern smartphones is their ability to switch
screen orientation, and Android is no exception.
• Android supports two screen orientations: portrait and landscape.

• By default, when you change the display orientation of your Android de-
vice, the current activity automatically redraws its content in the new
orientation.
• This is because the onCreate() method of the activity is fired whenever
there is a change in display orientation.
• Note: When you change the orientation of your Android device, your
current activity is actually destroyed and then re-created.
• when the views are redrawn, they may be drawn in their original locations
(depending on the layout selected).

In general, you can employ two techniques to handle changes in screen orienta-
tion:
Anchoring —The easiest way is to “anchor” your views to the four edges of
the screen. When the screen orientation changes, the views can anchor neatly
to the edges.
Resizing and repositioning —Whereas anchoring and centralizing are sim-
ple techniques to ensure that views can handle changes in screen orientation,
the ultimate technique is resizing each and every view according to the current
screen orientation

1.3 Managing Changes to screen orientation


Creating an application that displays message base on the screen
orientation
Create a Project
App → manif ests → AndroidM anif [Link]
Mobile Application Development Unit II Notes Dr. Geetha

1.3.1 Inside ⟨activity⟩

< activity
android : name = " . MainActivity "
android : configChanges = " orientation | screenSize " // Include this
line
android : exported = " true " >
< intent - filter >
< action android : name = " android . intent . action . MAIN " / >
< category android : name = " android . intent . category . LAUNCHER " / >
</ intent - filter >
</ activity >

1.3.2 Inside [Link]


Enter Ctrl+O select onConfigurationChanged
The following will be displayed

@Override
public void o n C o n f i g u r a t i o n C h a n g e d ( @NonNull Configuration
newConfig ) {
super . o n C o n f i g u r a t i o n C h a n g e d ( newConfig ) ;
\\ Include the code which is in BOLD
If ( newConfig . orientation == Configuration . O R I E N T A T I O N _ L A N D S C A P E )
{
Toast
toast = Toast . makeText ( this , " o r i e n t a t i o n _ l a n d s c a p e " ,
Toast . LENGTH_SHORT ) ;
toast . show () ;
}
else if ( newConfig . orientation ==
Configuration . O R I E N T A T I O N _ P O R T R A I T ) {
Toast toast = Toast . makeText ( this , " o r i e n t a t i o n _ P o r t r a i t " ,
Toast . LENGTH_SHORT ) ;
toast . show () ;
}
}

Run the Program

1.4 Utilizing the action bar


• In Android applications, ActionBar is the element present at the top of
the activity screen.

• Besides fragments, another feature of Android is the Action Bar.


• In place of the traditional title bar located at the top of the device’s screen,
the Action Bar displays the application icon and the activity title.
• Optionally, on the right side of the Action Bar are action items.
Mobile Application Development Unit II Notes Dr. Geetha

• The setSupportActionBar() method writes your Action Bar to the screen.


The Action Bar can be an instance of a Tool Bar.

Components included in the ActionBar are:


1. App Icon: Display the branding logo/icon of the application.
2. View Controls: Section that displays the name of the application or
current activity. Developers can also include spinner or tabbed navigation
for switching between views.
3. Action Button: Contains some important actions/elements of the app
that may be required to the users frequently.
4. Action Overflow:Include other actions that will be displayed as a menu.
Move less often used actions to the action overflow.

ss

1.4.1 Changing the ActionBar Title


• The ActionBar title displayed at the top of the screen is governed by the
[Link] file within the activity nodes.
• In the example below, the activity ”FirstActivity” will have an ActionBar
with the string value of the resource identified by @string/activity name.
• If the value of that resource is ”Foo,” the string displayed in the ActionBar
for this activity will be ”Foo.”

< application
android : icon = " @drawable / ic_launcher "
android : label = " @string / app_name "
android : theme = " @style / AppTheme " >
< activity
android : name = " com . codepath . example . simpleapp . FirstActivity "
android : label = " @string / activity_name " >
</ activity >
</ application >

• Change the android:label or android:icon to modify the ActionBar title or


icon for a given activity or for the application as a whole.

• In any Java activity, you can also call getSupportActionBar() to retrieve


a reference to the ActionBar and modify or access any properties of the
ActionBar at runtime
Mobile Application Development Unit II Notes Dr. Geetha

ActionBar actionBar = g e t S u p p o r t A c t i o n B a r () ; // or getActionBar () ;


g e t S u p p o r t A c t i o n B a r () . setTitle ( " My new title " ) ; // set the top
title
String title = actionBar . getTitle () . toString () ; // get the title
actionBar . hide () ; // or even hide the actionbar

1.4.2 Displaying ActionBar Icon


The icon can be added with:
g e t S u p p o r t A c t i o n B a r () . s e t D i s p l a y S h o w H o m e E n a b l e d ( true ) ;
g e t S u p p o r t A c t i o n B a r () . setLogo ( R . mipmap . ic_launcher ) ;
g e t S u p p o r t A c t i o n B a r () . s e t D i s p l a y U s e L o g o E n a b l e d ( true ) ;

Output of the above code

ss

1.4.3 Adding Action Items


When you want to add primary actions to the ActionBar, you add the items
to the activity context menu and if properly specified, they will automatically
appear at the top right as icons in the ActionBar.
An activity populates the ActionBar from within the onCreateOptionsMenu()
method:
public class MainActivity extends A p p C o m p a t A c t i v i t y {
@Override
public boolean o n C r e a t e O p t i o n s M e n u ( Menu menu ) {
// Inflate the menu ; this adds items to the action bar if it is
present .
g et Me nu I nf la t er () . inflate ( R . menu . menu_main , menu ) ;
return true ;
}
}

Entries in the action bar are typically called actions. Use this method to in-
flate a menu resource that defines all the action items within a res/menu/-
menu [Link] file, for example
<! - - Menu file for ‘ ac t iv it y_ m ov ie s . xml ‘ is located in a file
such as ‘ res / menu / menu_movies . xml ‘ -->
< menu xmlns : android = " http :// schemas . android . com / apk / res / android "
xmlns : app = " http :// schemas . android . com / apk / res - auto " >
< item
android : id = " @ + id / miCompose "
android : icon = " @drawable / ic_compose "
app : showAsAction = " ifRoom "
android : title = " Compose " >
</ item >
Mobile Application Development Unit II Notes Dr. Geetha

< item
android : id = " @ + id / miProfile "
android : icon = " @drawable / ic_profile "
app : showAsAction = " ifRoom | withText "
android : title = " Profile " >
</ item >
</ menu >

You also should note that the xmlns:app namespace must be defined in order to
leverage the showAsAction option. The reason is that a compatibility library is
used to support the showAsAction=”ifRoom” option. This option is needed to
show the item directly in the action bar as an icon. If there’s not enough room
for the item in the action bar, it will appear in the action overflow. If withText
is pecified as well (as in the second item), the text will be displayed with the
[Link] above code results in two action icons being displayed:

ss

1.5 Creating the user interface programmatically


• All the UIs are created using XML.
• Besides using XML you can also create the UI using code.
• This approach is useful if your UI needs to be dynamically generated
during runtime.
• For example, suppose you are building a cinema ticket reservation system
and your application displays the seats of each cinema using buttons. In
this case, you need to dynamically generate the UI based on the cinema
selected by the user.

• The following Try It Out demonstrates the code needed to dynamically


build the UI in your activity.
• To create a user interface programmatically in Android Studio, you typi-
cally follow these steps:

– Create a Layout Container*: You’ll need a layout container to hold


your UI elements programmatically. This can be a LinearLayout, Rel-
ativeLayout, ConstraintLayout, etc. You can create it directly in your
activity’s XML layout file or programmatically in your Java/Kotlin
code.
– Instantiate UI Elements*: Create instances of the UI elements you
want to include in your layout. For example, TextView, Button,
EditText, etc.
Mobile Application Development Unit II Notes Dr. Geetha

– Set Layout Parameters*: For each UI element, create layout param-


eters specifying how it should be positioned and sized within the
layout container.
– Add UI Elements to Layout*: Add the UI elements to the layout
container using the addView() method.
– Set Content View*: If you created the layout container programmat-
ically, set it as the content view of your activity using the setCon-
tentView() method.

1.5.1 Creating the UI via Code ([Link])


1. Using Android Studio, create a new Android project and name it UICode.

2. In the [Link] file, add the bold statements in the following


code:
import android . support . v7 . app . A p p C o m p a t A c t i v i t y ; import
android . os . Bundle ;
import android . support . v7 . widget . L i n e a r L a y o u t C o m p a t ;
import android . widget . Button ;
import android . widget . LinearLayout ;
import android . widget . TextView ;
public class MainActivity extends A p p C o m p a t A c t i v i t y {
@Override
protected void onCreate ( Bundle s a v e d I n s t a n c e S t a t e ) {
super .
OnCreate ( s a v e d I n s t a n c e S t a t e ) ;
L i n e a r L a y o u t C o m p a t . LayoutParams params = new
L i n e a r L a y o u t C o m p a t . LayoutParams (
L i n e a r L a y o u t C o m p a t . LayoutParams . WRAP_CONTENT ,
L i n e a r L a y o u t C o m p a t . LayoutParams . WRAP_CONTENT ) ;
// - - - create a layout - - -
LinearLayout layout = new LinearLayout ( this ) ;
layout . setOrie ntation ( LinearLayout . VERTICAL ) ;
// - - - create a text view - - -
TextView tv = new TextView ( this ) ;
tv . setText ( " This is a TextView " ) ;
tv . s e tL ay ou t Pa ra ms ( params ) ;
// - - - create a button - - -
Button btn = new Button ( this ) ;
btn . setText ( " This is a Button " ) ;
btn . se t La yo ut P ar am s ( params ) ;
// - - - adds the textview - - -
layout . addView ( tv ) ;
// - - - adds the button - - - layout . addView ( btn ) ;
// - - - create a layout param for the layout - - -
L i n e a r L a y o u t C o m p a t . LayoutParams layoutParam = new
L i n e a r L a y o u t C o m p a t . LayoutParams (
L i n e a r L a y o u t C o m p a t . LayoutParams . WRAP_CONTENT ,
L i n e a r L a y o u t C o m p a t . LayoutParams . WRAP_CONTENT ) ;
this . add Content View ( layout , layoutParam ) ;
}
}
Mobile Application Development Unit II Notes Dr. Geetha

3. Press Shift+F9 to debug the application on the Android emulator.

1.5.2 How It Works


In this example, you first commented out the setContentView() statement so
that it does not load the UI from the activity [Link] file.
You then created a LayoutParams object to specify the layout parameter that
can be used by other views (which you will create next):
//—create a layout param for the layout—

L i n e a r L a y o u t C o m p a t . LayoutParams layoutParam = new


L i n e a r L a y o u t C o m p a t . LayoutParams (
L i n e a r L a y o u t C o m p a t . LayoutParams . WRAP_CONTENT ,
L i n e a r L a y o u t C o m p a t . LayoutParams . WRAP_CONTENT ) ;

You also created a LinearLayout object to contain all the views in your activity:
//—create a layout—

LinearLayout layout = new LinearLayout ( this ) ;


layout . setOrie ntation ( LinearLayout . VERTICAL ) ;
Next , you created a TextView and a Button view :

//—create a textview—

TextView tv = new TextView ( this ) ;


tv . setText ( " This is a TextView " ) ; tv . se t La yo ut P ar am s ( params ) ;

//—create a button—

Button btn = new Button ( this ) ; btn . setText ( " This is a Button " ) ;
btn . se tL a yo ut Pa r am s ( params ) ;

You then added them to the LinearLayout object:


//—adds the textview—

layout . addView ( tv ) ;

//—adds the button—

layout . addView ( btn ) ;

You also created a LayoutParams object to be used by the LinearLayout object:


//—create a layout param for the layout—
LinearLayout . LayoutParams layoutParam =
new LinearLayout . LayoutParams ( LayoutParams . FILL_PARENT ,
LayoutParams . WRAP_CONTENT ) ;
Mobile Application Development Unit II Notes Dr. Geetha

Finally, you added the LinearLayout object to the activity:


this . add Content View ( layout , layoutParam ) ;

As you can see, using code to create the UI is quite a laborious affair. Hence,
you should dynamically generate your UI using code only when necessary.

1.6 Listening for UI notifications


1.6.1 Introduction
There are two levels of Android user interface with which users interact and
they are as follows:
1. Activity level
2. View level
Activity Level
At activity level, there are certain methods in Activity class which we can
override. Some of the genuine methods are as follow.
It’s often used to detect when a user releases a key on a hardware keyboard or a
software keyboard on the screen. This method is useful for handling input from
keyboard events, such as responding to specific keys being pressed or released.
• onKeyUp(): This is called when a key was released. This is not handled
by any of the views inside the activity.
• onKeyDown(): This is called when a key was pressed. This is not
handled by any of the views inside the activity.
• onMenuItemSelected(): This is called when any item of the menu panel
is pressed by user.
• onMenuOpened(): This method is called when user opens the panel’s
menu.
The following code snippet is an instance of such an implementation:
public boolean onKeyDown ( int keyCode , keyEvent event )
{
// TODO Auto - generated method stub
switch ( keyCode ) {
case KeyEvent . K E Y C O D E _ D P A D _ C E N T E R :
Toast . makeText ( getBa seContex t () , " Center of Dpad was pressed " ,
Toast . LENGTH_SHORT ) . show () ;
return true ;
case KeyEvent . K E Y C O D E _ DP A D _ D O W N :
Toast . makeText ( getBa seContex t () , " Down arrow was pressed " ,
Toast . LENGTH_SHORT ) . show () ;
return true ;
}
return false ;
}
Mobile Application Development Unit II Notes Dr. Geetha

View Level
• When any user interacts with a view, the corresponding view fires event.
• When a user touches a button or an image button or any such view we have
to service the related service so that appropriate action can be performed.

• For this, events need to be registered. For a button we will have code like
this:

private On Cl i ck Li st e ne r SaveListener = new On C li ck Li s te ne r () {


@Override
public void onClick ( View v ) {
// TODO Auto - generated method stub
Toast . makeText ( getBa seContex t () ," Save button was clicked " ,
Toast . LENGTH_SHORT ) . show () ;
}
};

// getBaseContext() – this method is used to retrieve the base context of an


activity or application.
This context provides access to application-specific resources and operations
such as accessing files, launching activities or accessing system services.

1.6.2 Designing Your User Interface with Views


View is the basic building block of UI(User Interface) in android. View refers
to the [Link] class, which is the super class for all the GUI
components like TextView, ImageView, Button etc.
• Basic views— Commonly used views, such as the TextView, EditText,
and Button views.

• Picker views— Views that enable users to select from a list, such as the
TimePicker and DatePicker views.
• List views— Views that display a long list of items, such as the ListView
and the SpinnerView views.

• Specialized fragments— Special fragments that perform specific func-


tions.

2 Using Basic Views


• TextView

• EditText
• Button
• ImageButton
Mobile Application Development Unit II Notes Dr. Geetha

• CheckBox
• ToggleButton
• RadioButton
• RadioGroup

ss

• These basic views enable you to display text information, as well as per-
form some basic selection.
• View class extends Object class and implements [Link],[Link]
and AccessibilityEventSource.
• match parent means it will occupy the complete space available on the
display of the device. Whereas, wrap content means it will occupy only
that much space as required for its content to display.
Mobile Application Development Unit II Notes Dr. Geetha

ss

2.1 TextView View


When you create a new Android project, Android Studio always creates the ac-
tivity [Link] file(located in the res/layout folder), which contains a ¡TextView¿
element:
<? xml version = " 1.0 " encoding = " utf -8 " ? >
< LinearLayout
xmlns : android = " http :// schemas . android . com / apk / res / android "
android : layout_width = " fill_parent "
android : layout_height = " fill_parent "
android : orientation = " vertical " >
< TextView
android : layout_width = " fill_parent "
android : layout_height = " wrap_content "
android : text = " @string / hello " / >
</ LinearLayout >

You use the TextView view to display text to the user. This is the most basic
view and one that you will frequently use when you develop Android applica-
tions. If you need to allow users to edit the text displayed, you should use the
subclass of TextView—EditText.

2.2 Button, imageButton, edittext, CheckBox, toggleBut-


ton, radioButton, and radiogroup Views
Besides the TextView view, which you will likely use the most often, there are
some other basic views that you will find yourself frequently using:
• Button— Represents a push-button widget.
Mobile Application Development Unit II Notes Dr. Geetha

• ImageButton— Similar to the Button view, except that it also displays


an image.
• EditText— A subclass of the TextView view, which allows users to edit
its text content.

• CheckBox— A special type of button that has two states: checked or


unchecked.
• RadioGroup and RadioButton— The RadioButton has two states:
either checked or unchecked. A RadioGroup is used to group one or more
RadioButton views, thereby allowing only one RadioButton to be checked
within the RadioGroup.
• ToggleButton— Displays checked/unchecked states using a light indi-
cator.

2.3 Using the Basic Views ([Link])


1. Using Android Studio, create an Android project and name it BasicViews1.
2. Modify the activity [Link] file located in the res/layout folder by adding
the following elements shown in bold:
<? xml version = " 1.0 " encoding = " utf -8 " ?
< LinearLayout xmlns :
android = " http :// schema . android . com / apk / res / android "
android : Layout_width = " fill_parent "
android : Layout_height = " fill_parent "
android : orientation = " vertical " >

< Button android : id = " @ + id / btnSave "


android : layout_width = " fill_parent "
android : layout_height = " wrap_content "
android : text = " save " / >
< Button android : id = " @ + id / btnOpen "
android : layout_width = " wrap_content "

android : layout_height = " wrap_content "


android : text = " Open " / >
< ImageButton android : id = " @ + id / btnImg1 "
android : layout_width = " fill_parent "
android : layout_height = " wrap_content "
android : src = " @mipmap / ic_launcher " / >
< EditText android : id = " @ + id / txtName "
android : layout_width = " fill_parent "
android : layout_height = " wrap_content " / >
< Checkbox android : id = " @ + id / chkAutosave "
android : layout_width = " fill_parent "
android : layout_height = " wrap_content "
android : text = " Autosave " / >
< Checkbox android : id = " @ + id / star "
style = " ? android : attr / starStyle
android : layout_width = " wrap_content "
Mobile Application Development Unit II Notes Dr. Geetha

android : layout_height = " wrap_content " / >


< RadioGroup android : id = " @ + id / rdbGpl "
android : layout_width = " fill_parent "
android : layout_height = " wrap_content "
android : orientation = " vertical " >

3. To see the views in action, debug the project in Android Studio by pressing
Shift+F9. shows the various views displayed in the Android emulator.
4. Click each of the views and note how they vary in look and feel. The
image below shows the following changes to the view:
• The first CheckBox view (Autosave) is checked.
• The second CheckBox View (star) is selected.
• The second RadioButton (Option 2) is selected.
• The ToggleButton is turned on.

ss
• set the image through the src attribute.
• layout height has been set to wrap content so that the text entry location
automatically adjusts to fit the amount of text entered by the user.
• If you do not like the default look of the CheckBox, you can apply a style
attribute so that the check mark is replaced by another image, such as a
star
style = " ? android : attr / starStyle

2.4 Using picker Views


Selecting a date and time is one of the common tasks you need to perform in a
mobile application. Android supports this functionality through the TimePicker
and DatePicker views.
Mobile Application Development Unit II Notes Dr. Geetha

2.4.1 Timepicker View


• The TimePicker view enables users to select a time of the day, in either
24- hour mode or AM/PM mode. The following Try It Out shows you
how to use the TimePicker in the latest version of the Android SDK.

• When you are creating the project for this sample, be sure that you choose
an SDK that is level 23 or greater.
• The [Link] is the subclass of FrameLayout class.

Using the timepicker View


• Using Android Studio, create an Android project and name it BasicViews4.
• Modify the activity [Link] file located in the res/layout folder by adding
the following bolded lines:
<? xml version = " 1.0 " encoding = " utf -8 " ? >
< LinearLayout xmlns : android = " http :// schema . android . com
/ apk / res / android "
android : layout_width = " fill_parent "
android : layout_height = " fill_parent "
android : orientation = " vertical " >
< TimePicker android : id = " @ + id / timePicker "
android : layout_width = " wrap_content "

a n d r o i d L l a y o u t _ h e i g h t = " wrap_content "


< Button android : id = " @ + id / btnSet "
android : layout_width = " wrap_content "
android : layout_height = " wrap_content "
android : text = " I am all set ! "
android : onClick = " onClick " / >
</ LinearLayout >

• Press Shift+F9 to debug the application on the Android emulator. the


image below shows the TimePicker in action. You can use the numeric
keypad or the time widget on the screen to change the hour and minute.
Mobile Application Development Unit II Notes Dr. Geetha

ss

• Back in Android Studio, add the following bolded statements to the Main-
[Link] file:
Mobile Application Development Unit II Notes Dr. Geetha

ss

• Press Shift+F9 to debug the application on the Android emulator. This


time, the TimePicker is displayed in the 24-hour format. Clicking the
Button displays the time that you have set in the TimePicker

ss

How It Works
Mobile Application Development Unit II Notes Dr. Geetha

• The TimePicker displays a standard UI to enable users to set a time. By


default, it displays the time in the AM/PM format.
• If you want to display the time in the 24-hour format, you can use the
setIs24HourView() method.

2.4.2 Datepicker View


Another view that is similar to the TimePicker is the DatePicker. Using the
DatePicker, you can enable users to select a particular date on the activity. The
following Try It Out shows you how to use the DatePicker.

Using the Datepicker View


1. Using the BasicViews4 project created earlier, modify the activity [Link]
file as shown here
<? xml version = " 1.0 " encoding = " utf -8 " ? >
< LinearLayout xmlns : android = " http :// schemas .
android . com / apk / res / android "
android . layout_width = " fill_parent "
android . layout_length = " fill_parent "
android : orientation = " vertical " >
< Button android : id = " @ + id / btnSet "
android . layout_width = " Wrap_content "
android . layout_height = " wrap_content "
android . text = " I am all set ! "
android : onClick = " onClick " / >
< DatePicker android : id = " @ + id / datePicker "
android . layout_width = " Wrap_content "
android . layout_height = " wrap_content " / >
< TimePicker android : id = " @ + id / timePicker "
android . layout_width = " Wrap_content "
android . layout_height = " wrap_content " / >
</ LinearLayout >

2. Add the following bolded statements to the [Link] file:

ss
Mobile Application Development Unit II Notes Dr. Geetha

ss

ss

3. Press Shift+F9 to debug the application on the Android emulator. After


the date is set, clicking the Button displays the date set.
Mobile Application Development Unit II Notes Dr. Geetha

ss

How It Works As with the TimePicker, you call the getMonth(), getDayOf-
Month(), and getYear() methods to get the month, day, and year, respectively:
" Date selected : " + ( datePicker . getMonth () + 1) +
" / " + datePicker . getDayOfMonth () + " / " +
datePicker . getYear () +
"\n" +

Note that the getMonth()method returns 0 for January, 1 for February, and so
on. This means you need to increment the result of this method by one to get
the corresponding month number.
Like the TimePicker, you can also display the DatePicker in a dialog window.

2.5 Using list Views to Display long lists


• List of scrollable items can be displayed in Android using ListView.
• It helps you to displaying the data in the form of a scrollable list.

• Users can then select any list item by clicking on it.


Mobile Application Development Unit II Notes Dr. Geetha

• ListView is default scrollable so we do not need to use scroll View or any-


thing else with ListView. ListView is widely used in android applications.
• In Android, there are two types of list views:ListView and SpinnerView.
• A very common example of ListView is your phone contact book, where
you have a list of your contacts displayed in a ListView and if you click
on it then user information is displayed.
• A ListView is a type of AdapterView.
• In Android, AdapterView is an abstract class that acts as a parent for
several view classes like ListView, GridView, and Spinner. It’s used
to display data in a scrollable format by connecting data to the respective
view.
• Using adapter, items are inserted into the list from an array or database.
For displaying the items in the list method setAdaptor() is used.
• The main purpose of the adapter is to fetch data from an array or database
and insert each item that placed into the list for the desired result.
• The ListView and GridView are subclasses of AdapterView
• Android provides several subclasses of Adapter that are useful for retriev-
ing different kinds of data and building views for an AdapterView ( i.e.
ListView or GridView). The common adapters are ArrayAdapter,Base
Adapter, CursorAdapter, SimpleCursorAdapter,SpinnerAdapter
and WrapperListAdapter. We will see separate examples for both the
adapters.
• To display a list, you can include a list view in your layout XML file:
< ListView
android : id = " @ + id / list_view "
android : layout_width = " match_parent "
android : layout_height = " match_parent " / >

2.5.1 ListView Attributes


Following are the important attributes specific to GridView (attribute and de-
scription)
• android:id: This is the ID which uniquely identifies the layout.
• android:divider: This is drawable or color to draw between list items.
• android:dividerHeight: This specifies height of the divider. This could
be in px, dp, sp, in, or mm.
• android:entries: Specifies the reference to an array resource that will
populate the ListView.
Mobile Application Development Unit II Notes Dr. Geetha

• android:footerDividersEnabled: When set to false, the ListView will


not draw the divider before each footer view. The default value is true.
• android:headerDividersEnabled When set to false, the ListView will
not draw the divider after each header view. The default value is true.
In android commonly used adapters are:
1. Array Adapter
2. Base Adapter
Array Adapter:
Whenever you have a list of single items which is backed by an array, you can
use ArrayAdapter. For instance, list of phone contacts, countries or names.
ArrayAdapter adapter = new
ArrayAdapter < String >( this , R . layout . ListView , R . id . textView ,
StringArray ) ;

2.5.2 Example of list view using Array Adapter

ss
Base Adapter:
Whenever you need a customized list you create your own adapter and extend
base adapter in that. Base Adapter can be extended to create a custom Adapter
for displaying a custom list item.
Mobile Application Development Unit II Notes Dr. Geetha

public class CustomAdapter extends BaseAdapter {


@Override
public int getCount () {
return 0;
}
@Override
public Object getItem ( int i ) {
return null ;
}
@Override
public long getItemId ( int i ) {
return 0;
}
@Override
public View getView ( int i , View view , ViewGroup viewGroup ) {
return null ;
}

1. getCount(): The getCount() function returns the total number of items


to be displayed in a list.
public int getCount () {
int count = arrayList . size () ; // counts the total number
of elements from the arrayList
return count ;// returns the total count to adapter
}

2. getView(int i, View view, ViewGroup viewGroup): This function


is automatically called when the list item view is ready to be displayed or
about to be displayed.
public View getView ( int i , View view , ViewGroup
viewGroup ) {
view = inflter . inflate ( R . layout . activity_gridview ,
null ) ;// set layout for displaying i
tems
ImageView icon = ( ImageView )
view . findViewById ( R . id . icon ) ;// get id for image
view
icon . s e t I m a g e R e s o u r c e ( flags [ i ]) ;// set image of the
i t e m s
return view ;
}

3. getItem(int i): This function is used to Get the data item associated
with the specified position in the data set to obtain the corresponding
data of the specific location in the collection of data items.
@Override
public Object getItem ( int i ) {
return arrayList . get ( i ) ;
}
Mobile Application Development Unit II Notes Dr. Geetha

4. getItemId(int i): As for the getItemId (int position), it returns the


corresponding to the position item ID. The function returns a long value
of item position to the adapter.
@Override
public long getItemId ( int i ) {
return i ;
}

Below is the final output and code with explanation:

ss

Example of list view using Custom adapter(Base adapter):


In this example we display a list of countries with flags. For this, we have to
use custom adapter.
Mobile Application Development Unit II Notes Dr. Geetha

ss

2.5.3 Spinner View


In Android, Spinner provides a quick way to select one value from a set of
values. Android spinners are nothing but the drop down-list. In a default state,
a spinner shows its currently selected value. It provides a easy way to select a
value from a list of values.

ss
Here is the XML basic code for Spinner:
< Spinner
android : id = " @ + id / simpleSpinner "
android : layout_width = " fill_parent "
android : layout_height = " wrap_content " / >

Important Note: To fill the data in a spinner we need to implement an


adapter class. A spinner is mainly used to display only text field so we can
implement Array Adapter for that. We can also use Base Adapter and other
custom adapters to display a spinner with more customize list. Suppose if we
need to display a textview and a imageview in spinner item list then array
adapter is not enough for that. Here we have to implement custom adapter in
our class. Below image of Spinner and Custom Spinner will make it more clear
Mobile Application Development Unit II Notes Dr. Geetha

ss

3 Understanding specialized Fragments


As you have learned, fragments are really “mini-activities” that have their own
life cycles. To create a fragment, you need a class that extends the Fragment
base class. In addition to the Fragment base class, you can also extend from
some other subclasses of the Fragment base class to create more specialized
fragments. The following sections discuss the three subclasses of Fragment:
• ListFragment

• DialogFragment
• PreferenceFragment

3.1 Using a ListFragment


• A list fragment is a fragment that contains a ListView, which displays a
list of items from a data source, such as an array or a Cursor.
• A list fragment is useful because it’s common to have one fragment that
contains a list of items, and another fragment that displays details about
the selected posting.

• In the chat application, a ListFragment could be used to display a list of


messages exchanged between users in a chat conversation. Each item in
the list represents a message, showing the sender’s name, message content,
timestamp, and possibly other metadata such as profile pictures.

• To create a list fragment, you need to extend the ListFragment base class.

3.2 Creating and Using a List Fragment


1. Using Android Studio, create an Android project and name it ListFrag-
mentExample.
2. Modify the activity [Link] file as shown in bold.
Mobile Application Development Unit II Notes Dr. Geetha

ss

3. Add an XML file to the res/layout folder and name it [Link].

4. Populate the [Link] as follows

ss

5. Add a Java Class file to the package and name it Fragment1.

6. Populate the [Link] file as follows

ss
Mobile Application Development Unit II Notes Dr. Geetha

ss

7. Press Shift+F9 to debug the application on the Android emulator. The


first figure in the below diagram shows the two list fragments displaying
the two lists of presidents’ names.
8. Click any of the items in the two ListView views, and you see a message

ss

3.3 Using a DialogFragment


• A dialog fragment floats on top of an activity and is displayed modally.
• Dialog fragments are useful when you need to obtain the user’s response
before continuing with execution.
• To create a dialog fragment, you must extend the DialogFragment base
class.

3.4 Creating and Using a Dialog Fragment


1. Using Android Studio, create an Android project and name it DialogFrag-
mentExample.
Mobile Application Development Unit II Notes Dr. Geetha

2. Add a Java Class file under the package and name it Fragment1.
3. Populate the [Link] file as follows:

ss

ss

4. Populate the [Link] file as shown here in bold:

ss

5. Press Shift+F9 to debug the application on the Android emulator. The


diagram below shows the fragment displayed as an alert dialog. Click
either OK or Cancel and observe the message displayed.
Mobile Application Development Unit II Notes Dr. Geetha

ss

3.5 Using a preferenceFragment


• In your Android applications you provide preferences for users to person-
alize the application.
• For example, you might allow users to save the login credentials that they
use to access their web resources.

• Also, you could save information, such as how often the feeds must be
refreshed and so on.
• In the social media app, a PreferenceFragment could be used to display
Mobile Application Development Unit II Notes Dr. Geetha

the app’s settings screen, These XML files define preferences such as no-
tification settings, privacy settings, theme preferences, etc.
• In Android, you can use the PreferenceActivity base class to display an
activity for the user to edit the preferences. In Android 3.0 and later, you
can use the PreferenceFragment class to do the same thing.

• In preferences there are different types of preferences which are listed


below :
– EditTextPreference: this is used to get the text from the user.
– ListPreference: this option is used to display a dialog with the list
of options to choose from.
– CheckBoxPreference: this option is used to display a checkbox to
toggle a setting.
– SwitchPreference: this option is used to turn the switch on and
off.
– RingtonePreference: this option is used to open the ringtone page
of your device.
– Preference with an Intent action [Link] – to
open an external browser navigating to an URL.

3.5.1 Creating and Using a preference Fragment


1. Using Android Studio, create an Android project and name it Preference-
FragmentExample.
2. Create a new xml directory under the res folder and then add a new XML
resource file to it. Name the XML file [Link].
3. Populate the [Link] file as follows:

ss
Mobile Application Development Unit II Notes Dr. Geetha

ss

4. Add a Java Class file to the package and name it Fragment1.


5. Populate the [Link] file as follows:
import android . os . Bundle ;
import android . preference . P r e f e r e n c e F r a g m e n t ;
public class Fragment1 extends P r e f e r e n c e F r a g m e n t {
@Override
public void onCreate ( Bundle s a v e d I n s t a n c e S t a t e ) {
super . onCreate ( s a v e d I n s t a n c e S t a t e ) ;
// - - - load the preferences from an XML file - - -
a d d P r e f e r e n c e s F r o m R e s o u r c e ( R . xml . preferences ) ;
}
}

6. Modify the [Link] file as shown in bold:

ss

7. Press Shift+F9 to debug the application on the Android emulator. The


first diagram below shows the preference fragment displaying the list of
preferences that the user can modify.
Mobile Application Development Unit II Notes Dr. Geetha

8. When the Edit Text preference is clicked, a pop-up is displayed (The


second image)
9. Clicking Edit Text (Second Screen) causes a second preference screen to
be displayed (The third screen below)
10. To dismiss the preference fragment, click the Back button on the emulator.

ss

3.5.2 How it works?


To create a list of preferences in your Android application, you first need to
create the preferences .xml file and populate it with the various XML elements.
This XML file defines the various items that you want to persist in your appli-
cation.
To create the preference fragment, you must extend the PreferenceFragment
base class:
public class Fragment1 extends P r e f e r e n c e F r a g m e n t {
}

% To load the preferences file in the preference % fragment , use the


a d d P r e f e r e n c e s F r o m R e s o u r c e () method :

@Override
public void onCreate ( Bundle s a v e d I n s t a n c e S t a t e ) {
super . onCreate ( s a v e d I n s t a n c e S t a t e ) ;
// - - - load the preferences from an XML file - - -
a d d P r e f e r e n c e s F r o m R e s o u r c e ( R . xml . preferences ) ;
}
Mobile Application Development Unit II Notes Dr. Geetha

ss

To display the preference fragment in your activity, you can make use of the
FragmentManager and the FragmentTransaction classes:
F ra gm en t Ma na ge r fr ag m en tM a na ge r = g e t F r a g m e n t M a n a g e r () ;
FragmentTransaction fragmentTransaction =
f ra gm en t Ma na ge r . b e g i n T r a n s ac t i o n () ;
Fragment1 fragment1 = new Fragment1 () ;
f r a g m e n t T r a n s a c t i o n . replace ( android . R . id . content , fragment1 ) ;
f r a g m e n t T r a n s a c t i o n . a ddToBac kStack ( null ) ;
f r a g m e n t T r a n s a c t i o n . commit () ;

You need to add the preference fragment to the back stack using the addTo-
BackStack() method so that 11the user can dismiss the fragment by clicking the
Back button.

4 ImageView in Android
ImageView class is used to display any kind of image resource in the android ap-
plication either it can be [Link] or [Link]
(it is a general abstraction for anything that can be drawn in Android).
ImageView class or [Link] inherits the [Link]
Mobile Application Development Unit II Notes Dr. Geetha

class which is the subclass of Java.


Moreover, ImageView is also used to control the size and movement of an image.

4.0.1 Adding an ImageView to an Activity


• Whenever ImageView is added to an activity, it means there is a require-
ment for an image resource.

• Thus it is oblivious to provide an Image file to that ImageView class.


• It can be done by adding an image file that is present in the Android
Studio itself or we can add our own image file.
• Android Studio owns a wide range of drawable resources which are very
common in the android application layout.

• The following are the steps to add a drawable resource to the ImageView
class.

1. Open the activity [Link] File in which the Image is to be Added


2. Switch from the Code View to the Design View of the activity [Link]
File

ss

3. For adding an image from Android Studio, Drag the ImageView widget
to the activity area of the application, a pop-up dialogue box will open
choose from the wide range of drawable resources and click “OK“.

For adding an image from Android Studio, Drag the ImageView widget to the
activity area of the application, a pop-up dialogue box will open choose from
the wide range of drawable resources and click “OK“
Mobile Application Development Unit II Notes Dr. Geetha

ss
Click on the “Resource Manager” tab on the leftmost panel and select the
“Import Drawables” option

ss

Select the path of the image file on your computer and click “OK“. After that
set, the “Qualifier type” and “value” of the image file according to your
need and click “Next” then “Import“.

ss
Drag the ImageView class in the activity area, a pop-up dialogue box will appear
which contains your imported image file. Choose your image file and click
“OK“, your image will be added to the activity.
Mobile Application Development Unit II Notes Dr. Geetha

4.0.2 XML Attributes of ImageView


• android:id To uniquely identify an image view
• android:src/app:srcCompat To add the file path of the inserted image
• android:background To provide a background color to the inserted im-
age
• android:layout width To set the width of the image
• android:layout height To set the height of the image
• android:padding To add padding to the image from the left, right, top,
or bottom of the view
• android:scaleType To re-size the image or to move it in order to fix its
size

4.0.3 Step by Step Implementation


Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start
a New Project in Android Studio.
Step 2: Working with the activity [Link] FileWorking with the
activity [Link] File
Go to the activity [Link] File and refer to the following code. Below is
the code for the activity [Link] File.
Navigate to the app res layout activity [Link] and add the below
code to that file. Below is the code for the activity [Link] file.
<? xml version = " 1.0 " encoding = " utf -8 " ? >
< androidx . c o n s t r a i n t l a y o u t . widget . C o n s t r a i n t L a y o u t
xmlns : android = " http :// schemas . android . com / apk / res / android "
xmlns : app = " http :// schemas . android . com / apk / res - auto "
xmlns : tools = " http :// schemas . android . com / tools "
android : layout_width = " match_parent "
android : layout_height = " match_parent "
tools : context = " . MainActivity " >
< ImageView
android : id = " @ + id / GfG_full_logo "
android : layout_width = " 0 dp "
android : layout_height = " wrap_content "
app : l a y o u t _ c o n s t r a i n t B o t t o m _ t o B o t t o m O f = " parent "
app : l a y o u t _ c o n s t r a i n t E n d _ t o E n d O f = " parent "
app : l a y o u t _ c o n s t r a i n t S t a r t _ t o S t a r t O f = " parent "
app : l a y o u t _ c o n s t r a i n t T o p _ t o T o p O f = " parent "
app : l a y o u t _ c o n s t r a i n t V e r t i c a l _ b i a s = " 0.078 "
app : srcCompat = " @drawable / full_logo " / >
< ImageView
android : id = " @ + id / GfG_logo "
android : layout_width = " wrap_content "
android : layout_height = " wrap_content "
app : l a y o u t _ c o n s t r a i n t B o t t o m _ t o B o t t o m O f = " parent "
Mobile Application Development Unit II Notes Dr. Geetha

app : l a y o u t _ c o n s t r a i n t E n d _ t o E n d O f = " parent "


app : l a y o u t _ c o n s t r a i n t S t a r t _ t o S t a r t O f = " parent "
app : l a y o u t _ c o n s t r a i n t T o p _ t o B o t t o m O f = " @ + id / GfG_full_logo "
app : srcCompat = " @drawable / logo " / >
</ androidx . c o n s t r a i n t l a y o u t . widget . ConstraintLayout >

Note: All the attributes of the ImageView which are starting with app:layout constraint
are the vertical and horizontal constraints to fix the image position in the activ-
ity. This is very necessary to add the constraint to the ImageView otherwise,
all the images will take the position (0, 0) of the activity layout.
Step 4: Working with the MainActivity File
Go to the MainActivity file and refer to the following code. Below is the code
for the MainActivity file. Since in the activity, only 2 images have been added
and nothing else is being done like touching a button, etc. So, the MainActivity
file will simply look like the below code i.e. no change.
import androidx . appcompat . app . A p p C o m p a t A c t i v i t y ;
import android . os . Bundle ;
public class MainActivity extends A p p C o m p a t A c t i v i t y {
@Override
protected void onCreate ( Bundle s a v e d I n s t a n c e S t a t e ) {
super . onCreate ( s a v e d I n s t a n c e S t a t e ) ;
setC ontentVi ew ( R . layout . activity_main ) ;
}
}

4.0.4 Android - Image Switcher


• Sometimes you don’t want an image to appear abruptly on the screen,
rather you want to apply some kind of animation to the image when it
transitions from one image to another.
• This is supported by android in the form of ImageSwitcher.
• An image switcher allows you to add some transitions on the images
through the way they appear on screen.
• In order to use image Switcher, you need to define its XML component
first. Its syntax is given below –
< ImageSwitcher
android : id = " @ + id / image Switcher 1 "
android : layout \ _width = " wrap \ _content "
android : layout \ _height = " wrap \ _content "
android : layout \ _ c e n t e r H o r i z o n t a l = " true "
android : layout \ _c e nt er V er ti ca l = " true " >
</ ImageSwitcher >

• Now we create an intance of ImageSwithcer in java file and get a reference


of this XML component.
Its syntax is given below –
Mobile Application Development Unit II Notes Dr. Geetha

private ImageSwitcher imageSwitcher ;


imageSwitcher = ( ImageSwitcher )
findViewById ( R . id . imag eSwitche r1 ) ;

• The last thing you need to do is to add Animation to the ImageSwitcher.


You need to define an object of Animation class through AnimationUtili-
ties class by calling a static method loadAnimation.
Its syntax is given below

Animation in =
Anim ationUti ls . loadAnimation ( this , android . R . anim . slide \ _in \ _left ) ;
imageSwitcher . s etInAni mation ( in ) ;
imageSwitcher . s et Ou tA n im at io n ( out ) ;

Apart from these methods, there are other methods defined in the ImageSwitcher
class. They are defined below –
1. Using Android Studio, create a new Android project and name it Im-
ageSwitcher.
2. Modify the activity [Link] file by adding the following bolded state-
ments. Please be sure to change all instances of [Link] to reflect
the package you use in your project:

ss

ss
Mobile Application Development Unit II Notes Dr. Geetha

3. Add two images to your res/mipmap folder (as you did in the previous
Try It Out). For this example, I added an image named [Link] and
an image named [Link].
4. Add the following bolded statements to the [Link] file

ss

ss

5. Press Shift+F9 to debug the application on the Android emulator. The


diagram below shows the ImageSwitcher and Button views, with no images
loaded

ss
Mobile Application Development Unit II Notes Dr. Geetha

6. Click the View Windows button. You see the windows image and a Toast
indicating that the image is being viewed

4.0.5 GridView
The GridView shows items in a two-dimensional scrolling grid. You can use the
GridView together with an ImageView to display a series of images.

4.0.6 How It Works


Like the ImageSwitcher example, you first implement the ImageAdapter class
and then bind it to the GridView

ss

ss
Mobile Application Development Unit II Notes Dr. Geetha

5 Using menus With Views


Menus are useful for displaying additional options that are not directly visible
on the main user interface (UI) of an application. There are two main types of
menus in Android:
• Options menu—This menu displays information related to the current
activity. In Android, you activate the options menu by pressing the Menu
button.
• Context menu— This menu displays information related to a particular
view on an activity. In Android, you tap and hold a context menu to
activate it.

5.0.1 Creating the helper methods


Before you go ahead and create your options and context menus, you need to
create two helper methods. One creates a list of items to show inside a menu,
whereas the other handles the event that is fired when the user selects an item
inside the menu.

5.1 Creating the Menu helper Methods


1. Using Android Studio, create a new Android project and name it Menus.
2. In the [Link] file, add the following bolded statements:

ss
Mobile Application Development Unit II Notes Dr. Geetha

ss

ss

5.2 How It Works


The preceding example creates two methods:
• createMenu()
• menuChoice()
The createMenu() method adds a series of menu items to a Menu argument.
To add a menu item to the menu, you create an instance of the MenuItem class
and use the Menu object’s add() method:
MenuItem mnu1 = menu . add (0 ,0 ,0 , " Item 1) ;
{
mnu1 . s e t A l p h a b e t i c S h o r t c u t ( ’ a ’) ;
mnu1 . setIcon ( R . mipmap . ic_launcher ) ;
}

The four arguments of the add() method are


• groupId - The group identifier of which the menu item should be a part.
Use 0 if the item is not in the group.
Mobile Application Development Unit II Notes Dr. Geetha

• itemId - A unique item ID.


• order - The order in which the item should be displayed.
• title - The text to be displayed on the menu item.
You can use the setAlphabeticShortcut() method to assign a shortcut key to the
menu item so that users can select an item by pressing a key on the keyboard.
The setIcon() method sets an image to be displayed on the menu item.
The menuChoice() method takes a MenuItem argument and checks its ID to
determine the menu item that is selected. It then displays a Toast message to
let the user know which menu item was selected.

5.3 Options Menu


You are now ready to modify the application to display the options menu when
the user presses the Menu key on the Android device.
Using the same project created in the previous section, add the following bolded
statements to the [Link] file:

ss

ss

ss
Mobile Application Development Unit II Notes Dr. Geetha

ss
Press Shift+F9 to debug the application on the Android emulator. Figure 6-7
shows the options menu that displays when you click the Menu button. To
select a menu item, either click an individual item or use its shortcut key

ss

5.4 How It Works


To display the options menu for your activity, you need to implement two meth-
ods in your activity:
Mobile Application Development Unit II Notes Dr. Geetha

• onCreateOptionsMenu()
• onOptionsItemSelected()
The onCreateOptionsMenu() method is called when the Menu button is pressed.
In this case, you call the createMenu() helper method to display the options
menu.
When a menu item is selected, the onOptionsItemSelected() method is called. In
this case, you call the menuChoice() method to display the menu item selected
(and perform whatever action is appropriate).

5.5 Context menu


• A context menu is usually associated with a view on an activity. A context
menu is displayed when the user taps and holds an item.
• For example, if the user taps a Button view and holds it for a few seconds,
a context menu can be displayed.
• If you want to associate a context menu with a view on an activity, you
need to call the setOnCreateContextMenuListener() method of that par-
ticular view.

Using the same project from the previous example, add the following bolded
statements to the activity [Link] file:

ss

ss
Mobile Application Development Unit II Notes Dr. Geetha

ss

Add the following bolded statements to the [Link] file

ss

ss
Mobile Application Development Unit II Notes Dr. Geetha

ss

ss
Mobile Application Development Unit II Notes Dr. Geetha

ss

Press Shift+F9 to debug the application on the Android emulator. The diagram
below shows the context menu that displays when you click and hold the Button
view.

ss

6 Android - WebView
WebView is a view that display web pages inside your application. You can also
specify HTML string and can show it inside your application using WebView.
WebView makes turns your application to a web application.
In order to add WebView to your application, you have to add ¡WebView¿
element to your xml layout file. Its syntax is as follows
< WebView
xmlns : android = " http :// schemas . android . com / apk / res / android "
Mobile Application Development Unit II Notes Dr. Geetha

android : id = " @ + id / webview "


android : layout_width = " fill_parent "
android : layout_height = " fill_parent "
/>

In order to use it, you have to get a reference of this view in Java file. To get a
reference, create an object of the class WebView. Its syntax is

WebView browser = ( WebView ) findViewById ( R . id . webview ) ;

In order to load a web url into the WebView, you need to call a method load-
Url(String url) of the WebView class, specifying the required url. Its syntax
is:
browser . loadUrl ( " https :// www . t utorial spoint . com " ) ;

Apart from just loading url, you can have more control over your WebView by
using the methods defined in WebView class. They are listed as follows
• canGoBack() This method specifies the WebView has a back history
item.

• canGoForward() This method specifies the WebView has a forward his-


tory item.
• clearHistory() This method will clear the WebView forward and back-
ward history.

• destroy() This method destroy the internal state of WebView.


• findAllAsync(String find) This method find all instances of string and
highlight them.
• getProgress() This method gets the progress of the current page.

• getTitle() This method return the title of the current page.


• getUrl()This method return the url of the current page.
If you click on any link inside the webpage of the WebView, that page will not
be loaded inside your WebView. In order to do that you need to extend your
class from WebViewClient and override its method. Its syntax is
private class MyBrowser extends WebViewClient {
@Override
public boolean s h o u l d O v e r r i d e U r l L o a d i n g ( WebView view ,
String url ) {
view . loadUrl ( url ) ;
return true ;
}
}
Mobile Application Development Unit II Notes Dr. Geetha

Example Here is an example demonstrating the use of WebView Layout. It


creates a basic web application that will ask you to specify a url and will load
this url website in the WebView.
To experiment with this example, you need to run this on an actual device on
which internet is running.
• You will use Android studio to create an Android application under a
package [Link].
• Modify src/[Link] file to add WebView code.
• Modify the res/layout/activity main to add respective XML components
• Modify the [Link] to add the necessary permissions
• Run the application and choose a running android device and install the
application on it and verify the results.
Following is the content of the modified main activity file src/[Link].
package com . example . sairamkrishna . myapplication ;
import android . app . Activity ;
import android . os . Bundle ;
import android . view . View ;
import android . webkit . WebView ;
import android . webkit . WebViewClient ;
import android . widget . Button ;
import android . widget . EditText ;
public class MainActivity extends Activity {
Button b1 ;
EditText ed1 ;
private WebView wv1 ;
@Override
protected void onCreate ( Bundle s a v e d I n s t a n c e S t a t e ) {
super . onCreate ( s a v e d I n s t a n c e S t a t e ) ;
setC ontentVi ew ( R . layout . activity_main ) ;
b1 =( Button ) findViewById ( R . id . button ) ;
ed1 =( EditText ) findViewById ( R . id . editText ) ;
wv1 =( WebView ) findViewById ( R . id . webView ) ;
wv1 . s e t W e b V i e w C l i e n t ( new MyBrowser () ) ;
b1 . s e t O n C l i c k L i s t e n e r ( new View . On Cl i ck Li st e ne r () {
@Override
public void onClick ( View v ) {
String url = ed1 . getText () . toString () ;
wv1 . getSettings () . s e t L o a d s I m a g e s A u t o m a t i c a l l y ( true ) ;
wv1 . getSettings () . s e t J a v a S c r i p t E n a b l e d ( true ) ;
wv1 . s e t S c r o l l B a r S t y l e ( View . S C R O L L B A R S _ I N S I D E _ O V E R L A Y ) ;
wv1 . loadUrl ( url ) ;
}
}) ;
}
private class MyBrowser extends WebViewClient {
@Override
public boolean s h o u l d O v e r r i d e U r l L o a d i n g ( WebView view , String url )
{
view . loadUrl ( url ) ;
Mobile Application Development Unit II Notes Dr. Geetha

return true ;
}
}
}

Following is the modified content of the xml res/layout/activity [Link].


<? xml version = " 1.0 " encoding = " utf -8 " ? >
< Relative Layout
xmlns : android = " http :// schemas . android . com / apk / res / android "
xmlns : tools = " http :// schemas . android . com / tools "
android : layout_width = " match_parent "
android : layout_height = " match_parent "
android : paddingLeft = " @dimen / a c t i v i t y _ h o r i z o n t a l _ m a r g i n "
android : paddingRight = " @dimen / a c t i v i t y _ h o r i z o n t a l _ m a r g i n "
android : paddingTop = " @dimen / a c t i v i t y _ v e r t i c a l _ m a r g i n "
android : paddingBottom = " @dimen / a c t i v i t y _ v e r t i c a l _ m a r g i n "
tools : context = " . MainActivity " >

< TextView android : text = " WebView "


android : layout_width = " wrap_content "
android : layout_height = " wrap_content "
android : id = " @ + id / textview "
android : textSize = " 35 dp "
android : l a y o u t _ a l i g n P a r e n t T o p = " true "
android : l a y o u t _ c e n t e r H o r i z o n t a l = " true " / >

< TextView
android : layout_width = " wrap_content "
android : layout_height = " wrap_content "
android : text = " Tutorials point "
android : id = " @ + id / textView "
android : layout_below = " @ + id / textview "
android : l a y o u t _ c e n t e r H o r i z o n t a l = " true "
android : textColor = " # ff7aff24 "
android : textSize = " 35 dp " / >

< EditText
android : layout_width = " wrap_content "
android : layout_height = " wrap_content "
android : id = " @ + id / editText "
android : hint = " Enter Text "
android : focusable = " true "
android : t e x t C o l o r H i g h l i g h t = " # ff7eff15 "
android : textColorHint = " # ffff25e6 "
android : l a y o u t _ m a rg i n T o p = " 46 dp "
android : layout_below = " @ + id / imageView "
android : l a y o u t _ a l i g n P a r e n t L e f t = " true "
android : l a y o u t _ a l i g n P a r e n t S t a r t = " true "
android : l a y o u t _ a l i g n R i g h t = " @ + id / imageView "
android : l a yo ut _a l ig nE nd = " @ + id / imageView " / >

< ImageView
android : layout_width = " wrap_content "
android : layout_height = " wrap_content "
android : id = " @ + id / imageView "
android : src = " @drawable / abc "
android : layout_below = " @ + id / textView "
Mobile Application Development Unit II Notes Dr. Geetha

android : l a y o u t _ c e n t e r H o r i z o n t a l = " true " / >

< Button
android : layout_width = " wrap_content "
android : layout_height = " wrap_content "
android : text = " Enter "
android : id = " @ + id / button "
android : l a yo ut _a l ig nT op = " @ + id / editText "
android : l a y o u t _ t o Ri g h t O f = " @ + id / imageView "
android : layou t_toEnd Of = " @ + id / imageView " / >

< WebView
android : layout_width = " wrap_content "
android : layout_height = " wrap_content "
android : id = " @ + id / webView "
android : layout_below = " @ + id / button "
android : l a y o u t _ a l i g n P a r e n t L e f t = " true "
android : l a y o u t _ a l i g n P a r e n t S t a r t = " true "
android : l a y o u t _ a l i g n P a r e n t R i g h t = " true "
android : l a y o u t _ a l i g n P a r e n t E n d = " true "
android : l a y o u t _ a l i g n P a r e n t B o t t o m = " true " / >

</ RelativeLayout >

Following is the content of the res/values/ [Link].


< resources >
< string name = " app_name " > My Application </ string >
</ resources >

Following is the content of [Link] file.


<? xml version = " 1.0 " encoding = " utf -8 " ? >
< manifest
xmlns : android = " http :// schemas . android . com / apk / res / android "
package = " com . example . sairamkrishna . myapplication " >
< uses - permission android : name = " android . permission . INTERNET " / >
< application
android : allowBackup = " true "
android : icon = " @mipmap / ic_launcher "
android : label = " @string / app_name "
android : theme = " @style / AppTheme " >

< activity
android : name = " . MainActivity "
android : label = " @string / app_name " >

< intent - filter >


< action android : name = " android . intent . action . MAIN " / >
< category
android : name = " android . intent . category . LAUNCHER " / >
</ intent - filter >

</ activity >

</ application >


</ manifest >
Mobile Application Development Unit II Notes Dr. Geetha

ss

6.1 Saving and loading user preferences


Android provides the SharedPreferences object to help you save simple applica-
tion data. For example, your application may have an option that enables users
to specify the font size used in your application. In this case, your application
needs to remember the size set by the user so that the size is set appropriately
each time the app is opened. You have several options for saving this type of
preference:
• Save data to a file—You can save the data to a file, but you have to
perform some file management routines, such as writing the data to the
file, indicating how many characters to read from it, and so on. Also,
if you have several pieces of information to save, such as text size, font
name, preferred background color, and so on, then the task of writing to
a file becomes more onerous.
• Writing text to a database—An alternative to writing to a text file is to
use a [Link], saving simple data to a database is overkill, both
from a developer’s point of view and in terms of the application’s run-time
performance.
• Using the SharedPreferences object—The SharedPreferences object, how-
ever, saves data through the use of name/value pairs. For example, specify
a name for the data you want to save, and then both it and its value will
be saved automatically to an XML file.
Mobile Application Development Unit II Notes Dr. Geetha

6.2 Android - Shared Preferences


• Android provides many ways of storing data of an application. One of
this way is called Shared Preferences. Shared Preferences allow you to
save and retrieve data in the form of key,value pair.

• Shared Preferences is the way in which one can store and retrieve small
amounts of primitive data as key/value pairs to a file on the device storage
such as String, int, float, Boolean that make up your preferences in an
XML file inside the app on the device storage.
• For example, you might have a key being “username” and for the value,
you might store the user’s username. And then you could retrieve that by
its key (here username).
• You can have a simple shared preference API that you can use to store
preferences and pull them back as and when needed.

• The shared Preferences class provides APIs for reading, writing, and man-
aging this data.
• In order to use shared preferences, you have to call a method getShared-
Preferences() that returns a SharedPreference instance pointing to the file
that contains the values of preferences.

S h a r e d P r e f e r e n c e s s h a r e dp r e f e r e n c e s =
g e t S h a r e d P r e f e r e n c e s ( MyPREFERENCES , Context . MODE_PRIVATE ) ;

The first parameter is the key and the second parameter is the MODE.
This method takes two arguments, the first being the name of the SharedPref-
erence(SP) file and the other is the context mode that we want to store our file
in.

• MODE PUBLIC will make the file public which could be accessible by
other applications on the device
• MODE PRIVATE keeps the files private and secures the user’s data.
• MODE APPEND is used while reading the data from the SharedPrefer-
ence file.

Following are the methods of Shared Preferences


1. contains(String key): This method is used to check whether the pref-
erences contain a preference.
2. edit(): This method is used to create a new Editor for these preferences,
through which you can make modifications to the data in the preferences
and atomically commit those changes back to the SharedPreferences ob-
ject.
Mobile Application Development Unit II Notes Dr. Geetha

3. getAll(): This method is used to retrieve all values from the preferences.
4. getBoolean(String key, boolean defValue): This method is used to
retrieve a boolean value from the preferences.
5. getFloat(String key, float defValue): This method is used to retrieve
a float value from the preferences.
6. getInt(String key, int defValue): This method is used to retrieve an
int value from the preferences.
7. getLong(String key, long defValue): This method is used to retrieve
a long value from the preferences.

8. getString(String key, String defValue): This method is used to re-


trieve a String value from the preferences.
9. getStringSet(String key, Set defValues): This method is used to
retrieve a set of String values from the preferences.

10. ([Link] PreferencechangeListenerlistener):


This method is used to register a callback to be invoked when a change
happens to a preference.
11. unregisterOnSharedPreference change Listener(SharedPreferences.
OnShared PreferencechangeListener listener): This method is used
to unregister a previous callback.
You can save something in the sharedpreferences by using [Link]
class. You will call the edit method of SharedPreference instance and will receive
it in an editor object. Its syntax is –
Editor editor = s h a r e d p re f e r e n c e s . edit () ;
editor . putString ( " key " , " value " ) ;
editor . commit () ;

Apart from the putString method , there are methods available in the editor
class that allows manipulation of data inside shared preferences. They are listed
as follows
• apply() It is an abstract method. It will commit your changes back from
editor to the sharedPreference object you are calling.

• clear() It will remove all the values from the editor.


• remove(String key) It will remove the value whose key has been passed
as a parameter.
• putLong(String key, long value) It will save a long value in a prefer-
ence editor.
Mobile Application Development Unit II Notes Dr. Geetha

• putInt(String key, int value) It will save a integer value in a preference


editor.
• putFloat(String key, float value) It will save a float value in a prefer-
ence editor
Example This example demonstrates the use of the Shared Preferences. It dis-
play a screen with some text fields, whose value are saved when the application
is closed and brought back when it is opened again.
[Steps]You will use Android studio to create an android application under
a package [Link]. myapplication. Modify src/MainActiv-
[Link] file to add progress code to display the spinning progress dialog.
Modify res/layout/activity [Link] file to add respective xml code. Runs
the application and choose a running android device and install the appli-
cation on it and verify the results.
Following is the content of the modified [Link].
import android . content . Context ;
import android . content . Sh a r e d P r e f e r e n c e s ;
import android . os . Bundle ;
import android . support . v7 . app . A p p C o m p a t A c t i v i t y ;
import android . view . View ;
import android . widget . Button ;
import android . widget . EditText ;
import android . widget . Toast ;
public class MainActivity extends A p p C o m p a t A c t i v i t y {
EditText ed1 , ed2 , ed3 ;
Button b1 ;
public static final String MyPREFERENCES = " MyPrefs " ;
public static final String Name = " nameKey " ;
public static final String Phone = " phoneKey " ;
public static final String Email = " emailKey " ;
SharedPreferences sharedpreferences ;
@Override
protected void onCreate ( Bundle s a v e d I n s t a n c e S t a t e ) {
super . onCreate ( s a v e d I n s t a n c e S t a t e ) ;
setC ontentVi ew ( R . layout . activity_main ) ;
ed1 =( EditText ) findViewById ( R . id . editText ) ;
ed2 =( EditText ) findViewById ( R . id . editText2 ) ;
ed3 =( EditText ) findViewById ( R . id . editText3 ) ;
b1 =( Button ) findViewById ( R . id . button ) ;
sharedpreferences =
g e t S h a r e d P r e f e r e n c e s ( MyPREFERENCES , Context . MODE_PRIVATE ) ;
b1 . s e t O n C l i c k L i s t e n e r ( new View . On Cl i ck Li st e ne r () {
@Override
public void onClick ( View v ) {
String n = ed1 . getText () . toString () ;
String ph = ed2 . getText () . toString () ;
String e = ed3 . getText () . toString () ;
S h a r e d P r e f e r e n c e s . Editor editor =
s h a r e d p r e f e r e n c e s . edit () ;
editor . putString ( Name , n ) ;
editor . putString ( Phone , ph ) ;
editor . putString ( Email , e ) ;
Mobile Application Development Unit II Notes Dr. Geetha

editor . commit () ;

Toast . makeText ( MainActivity . this , " Thanks " , Toast . LENGTH_LON


G ) . show () ;
}
}) ;
}
}

Following is the content of the modified main activity fileres/layout/activiy [Link].


<? xml version = " 1.0 " encoding = " utf -8 " ? >
< Relative Layout
xmlns : android = " http :// schemas . android . com / apk / res / android "
xmlns : tools = " http :// schemas . android . com / tools "
android : layout_width = " match_parent "
android : layout_height = " match_parent "
android : paddingLeft = " @dimen / a c t i v i t y _ h o r i z o n t a l _ m a r g i n "

android : paddingRight = " @dimen / a c t i v i t y _ h o r i z o n t a l _ m a r g i n "


android : paddingTop = " @dimen / a c t i v i t y _ v e r t i c a l _ m a r g i n "
android : paddingBottom = " @dimen / a c t i v i t y _ v e r t i c a l _ m a r g i n "
tools : context = " . MainActivity " >

< TextView
android : layout_width = " wrap_content "
android : layout_height = " wrap_content "
android : text = " Shared Preference "
android : id = " @ + id / textView "
android : l a y o u t _ a l i g n P a r e n t T o p = " true "
android : l a y o u t _ c e n t e r H o r i z o n t a l = " true "
android : textSize = " 35 dp " / >

< TextView
android : layout_width = " wrap_content "
android : layout_height = " wrap_content "
android : text = " Tutorials Point "
android : id = " @ + id / textView2 "
android : layout_below = " @ + id / textView "
android : l a y o u t _ c e n t e r H o r i z o n t a l = " true "
android : textSize = " 35 dp "
android : textColor = " # ff16ff01 " / >

< EditText
android : layout_width = " wrap_content "
android : layout_height = " wrap_content "
android : id = " @ + id / editText "
android : layout_below = " @ + id / textView2 "
android : l a y o u t _ m a rg i n T o p = " 67 dp "
android : hint = " Name "
android : l a y o u t _ a l i g n P a r e n t R i g h t = " true "
android : l a y o u t _ a l i g n P a r e n t E n d = " true "
android : l a y o u t _ a l i g n P a r e n t L e f t = " true "
android : l a y o u t _ a l i g n P a r e n t S t a r t = " true " / >

< EditText
android : layout_width = " wrap_content "
android : layout_height = " wrap_content "
Mobile Application Development Unit II Notes Dr. Geetha

android : id = " @ + id / editText2 "


android : layout_below = " @ + id / editText "
android : l a y o u t _ a l i g n P a r e n t L e f t = " true "
android : l a y o u t _ a l i g n P a r e n t S t a r t = " true "
android : l a y o u t _ a l i g n P a r e n t R i g h t = " true "
android : l a y o u t _ a l i g n P a r e n t E n d = " true "
android : hint = " Pass " / >

< EditText
android : layout_width = " wrap_content "
android : layout_height = " wrap_content "
android : id = " @ + id / editText3 "
android : layout_below = " @ + id / editText2 "
android : l a y o u t _ a l i g n P a r e n t L e f t = " true "
android : l a y o u t _ a l i g n P a r e n t S t a r t = " true "
android : l a y o u t _ a l i g n P a r e n t R i g h t = " true "
android : l a y o u t _ a l i g n P a r e n t E n d = " true "
android : hint = " Email " / >

< Button
android : layout_width = " wrap_content "
android : layout_height = " wrap_content "
android : text = " Save "
android : id = " @ + id / button "
android : layout_below = " @ + id / editText3 "
android : l a y o u t _ c e n t e r H o r i z o n t a l = " true "
android : l a y o u t _ m a rg i n T o p = " 50 dp " / >

</ RelativeLayout >

Now just put in some text in the field. Like i put some random name and other
information and click on save button.
Mobile Application Development Unit II Notes Dr. Geetha

• ss
Now when you press save button, the text will be saved in the shared preferences.
Now press back button and exit the application. Now open it again and you
will see all the text you have written back in your application.
Android supports the following ways of storing data in the local file system:
• Files - You can create and update files
• Preferences - Android allows you to save and retrieve persistent key-
value pairs of primitive data type.

• SQLite database - instances of SQLite databases are also stored on the


local file system.

7 Android - Internal Storage


Android provides many kinds of storage for applications to store their data.
These storage places are shared preferences, internal and external storage, SQLite
storage, and storage via network connection.
In this chapter we are going to look at the internal storage. Internal storage is
the storage of the private data on the device memory.
By default these files are private and are accessed by only your application and
get deleted , when user delete your application.
Mobile Application Development Unit II Notes Dr. Geetha

7.1 Writing file


In order to use internal storage to write some data in the file, call the openFile-
Output() method with the name of the file and the mode. The mode could be
private , public e.t.c.
Its syntax is given below –
F i l e O u t p u t S t r e a m fOut = op enFileOu tput ( " file name
here " , M O D E _ W O R L D _ R E A D A B L E ) ;

The method openFileOutput() returns an instance of FileOutputStream. So


you receive it in the object of FileInputStream. After that you can call write
method to write data on the file. Its syntax is given below –
String str = " data " ;
fOut . write ( str . getBytes () ) ;
fOut . close () ;

7.2 Reading file


In order to read from the file you just created , call the openFileInput() method
with the name of the file. It returns an instance of FileInputStream.
Its syntax is given below –
F il eI np u tS tr ea m fin = openFileInput ( file ) ;

After that, you can call read method to read one character at a time from the
file and then you can print it.
Its syntax is given below –
int c ;
String temp = " " ;
while ( ( c = fin . read () ) != -1) {
temp = temp + Character . toString (( char ) c ) ;
}
// string temp contains all the data of the file .
fin . close () ;

Apart from the methods of write and close, there are other methods provided
by the FileOutputStream class for better writing files. These methods are listed
below –
• fileOutputStream(File file, boolean append) This method constructs
a new FileOutputStream that writes to file.
• getChannel() This method returns a write-only fileChannel that shares
its position with this stream.
• getFD() This method returns the underlying file descriptor.
• write(byte[] buffer, int byteOffset, int byteCount This method
Writes count bytes from the byte array buffer starting at position offset
to this stream.
Mobile Application Development Unit II Notes Dr. Geetha

Apart from the the methods of read and close, there are other methods provided
by the FileInputStream class for better reading files. These methods are listed
below: -
• available() This method returns an estimated number of bytes that can
be read or skipped without blocking for more input.

• getChannel() This method returns a read-only FileChannel that shares


its position with this stream.
• getFD() This method returns the underlying file descriptor
• read(byte[] buffer, int byteOffset, int byteCount This method reads
at most length bytes from this stream and stores them in the byte array
b starting at offset.
Example Here is an example demonstrating the use of internal storage to store
and read files. It creates a basic storage application that allows you to read and
write from internal storage.
[Steps]You will use Android Studio IDE to create an Android application
under a package [Link]. Modify src/MainAc-
[Link] file to add necessary code. Modify the res/layout/activity main
to add respective XML components. Run the application and choose a
running android device and install the application on it and verify the
results.

Following is the content of the modified main activity file src/[Link].


package com . example . sairamkrishna . myapplication ;
import android . app . Activity ;
import android . os . Bundle ;
import android . view . View ;
import android . widget . Button ;
import android . widget . EditText ;
import android . widget . TextView ;
import android . widget . Toast ;
import java . io . F il eI n pu tS tr e am ;
import java . io . F i l e O u t p u t S t r e a m ;
public class MainActivity extends Activity {
Button b1 , b2 ;
TextView tv ;
EditText ed1 ;
String data ;
private String file = " mydata " ;
@Override
protected void onCreate ( Bundle s a v e d I n s t a n c e S t a t e ) {
super . onCreate ( s a v e d I n s t a n c e S t a t e ) ;
setC ontentVi ew ( R . layout . activity_main ) ;
b1 =( Button ) findViewById ( R . id . button ) ;
b2 =( Button ) findViewById ( R . id . button2 ) ;
ed1 =( EditText ) findViewById ( R . id . editText ) ;
tv =( TextView ) findViewById ( R . id . textView2 ) ;
b1 . s e t O n C l i c k L i s t e n e r ( new View . On Cl i ck Li st e ne r () {
Mobile Application Development Unit II Notes Dr. Geetha

@Override
public void onClick ( View v ) {
data = ed1 . getText () . toString () ;
try {
F i l e O u t p u t S t r e a m fOut =
openF ileOutp ut ( file , M O D E _ W O R L D _ R E A D A B L E ) ;
fOut . write ( data . getBytes () ) ;
fOut . close () ;
Toast . makeText ( getBa seContex t () ," file
saved " , Toast . LENGTH_SHORT ) . show () ;
}
catch ( Exception e ) {
// TODO Auto - generated catch block
e . pr i nt St ac k Tr ac e () ;
}
}
}) ;
b2 . s e t O n C l i c k L i s t e n e r ( new View . On Cl i ck Li st e ne r () {

@Override
public void onClick ( View v ) {
try {
F il eI np u tS tr e am fin = openFileInput ( file ) ;
int c ;
String temp = " " ;
while ( ( c = fin . read () ) != -1) {
temp = temp +
Character . toString (( char ) c ) ;
}
tv . setText ( temp ) ;
Toast . makeText ( getBa seContex t () ," file
read " , Toast . LENGTH_SHORT ) . show () ;
}
catch ( Exception e ) {
}
}
}) ;
}
}

Following is the modified content of the xml res/layout/activity [Link].


<? xml version = " 1.0 " encoding = " utf -8 " ? >
< Relative Layout
xmlns : android = " http :// schemas . android . com / apk / res / android "
xmlns : tools = " http :// schemas . android . com / tools "
android : layout_width = " match_parent "
android : layout_height = " match_parent "
android : paddingLeft = " @dimen / a c t i v i t y _ h o r i z o n t a l _ m a r g i n "

android : paddingRight = " @dimen / a c t i v i t y _ h o r i z o n t a l _ m a r g i n "


android : paddingTop = " @dimen / a c t i v i t y _ v e r t i c a l _ m a r g i n "
android : paddingBottom = " @dimen / a c t i v i t y _ v e r t i c a l _ m a r g i n "
tools : context = " . MainActivity " >

< TextView android : text = " Internal storage "


android : layout_width = " wrap_content "
Mobile Application Development Unit II Notes Dr. Geetha

android : layout_height = " wrap_content "


android : id = " @ + id / textview "
android : textSize = " 35 dp "
android : l a y o u t _ a l i g n P a r e n t T o p = " true "
android : l a y o u t _ c e n t e r H o r i z o n t a l = " true " / >

< TextView
android : layout_width = " wrap_content "
android : layout_height = " wrap_content "
android : text = " Tutorials point "
android : id = " @ + id / textView "
android : layout_below = " @ + id / textview "
android : l a y o u t _ c e n t e r H o r i z o n t a l = " true "
android : textColor = " # ff7aff24 "
android : textSize = " 35 dp " / >

< Button
android : layout_width = " wrap_content "
android : layout_height = " wrap_content "
android : text = " Save "
android : id = " @ + id / button "
android : l a y o u t _ a l i g n P a r e n t B o t t o m = " true "
android : l a y o u t _ a l ig n L e f t = " @ + id / textView "
android : l a y o u t _ a l i g n S t a r t = " @ + id / textView " / >

< EditText
android : layout_width = " wrap_content "
android : layout_height = " wrap_content "
android : id = " @ + id / editText "
android : hint = " Enter Text "
android : focusable = " true "
android : t e x t C o l o r H i g h l i g h t = " # ff7eff15 "
android : textColorHint = " # ffff25e6 "
android : layout_below = " @ + id / imageView "
android : l a y o u t _ a l i g n R i g h t = " @ + id / textView "
android : l a yo ut _a l ig nE nd = " @ + id / textView "
android : l a y o u t _ m a rg i n T o p = " 42 dp "
android : l a y o u t _ a l ig n L e f t = " @ + id / imageView "
android : l a y o u t _ a l i g n S t a r t = " @ + id / imageView " / >

< ImageView
android : layout_width = " wrap_content "
android : layout_height = " wrap_content "
android : id = " @ + id / imageView "
android : src = " @drawable / abc "
android : layout_below = " @ + id / textView "
android : l a y o u t _ c e n t e r H o r i z o n t a l = " true " / >

< Button
android : layout_width = " wrap_content "
android : layout_height = " wrap_content "
android : text = " load "
android : id = " @ + id / button2 "
android : l a yo ut _a l ig nT op = " @ + id / button "
android : l a y o u t _ a l i g n R i g h t = " @ + id / editText "
android : l a yo ut _a l ig nE nd = " @ + id / editText " / >
Mobile Application Development Unit II Notes Dr. Geetha

< TextView
android : layout_width = " wrap_content "
android : layout_height = " wrap_content "
android : text = " Read "
android : id = " @ + id / textView2 "
android : layout_below = " @ + id / editText "
android : l a yo ut _t o Le ft Of = " @ + id / button2 "
android : l a y o u t _ t o St a r t O f = " @ + id / button2 "
android : textColor = " # ff5bff1f "
android : textSize = " 25 dp " / >

</ RelativeLayout >

• ss

Now what you need to do is to enter any text in the field. For example , i have
entered some text. Press the save button. The following notification would
appear in you AVD –
Mobile Application Development Unit II Notes Dr. Geetha

ss
Now when you press the load button, the application will read the file , and
display the data
Mobile Application Development Unit II Notes Dr. Geetha

ss

7.3 Persisting Data to Files


The SharedPreferences object enables you to store data that is best stored as
name/value pairs— for example, user ID, birth date, gender, driver’s license
number, and so on. However, sometimes you might prefer to use the traditional
file system to store your data. For example, you might want to store the text
of poems you want to display in your applications. In Android, you can use the
classes in the [Link] package to do [Link] to internal storage.
The first way to save files in your Android application is to write to the device’s
internal storage. The following Try It Out demonstrates how to save a string
entered by the user to the device’s internal storage.
• Using Android Studio, create an Android project and name it Files.
• In the activity [Link] file, add the following bolded statements:
Mobile Application Development Unit II Notes Dr. Geetha

ss

ss

ss

ss

• In the [Link] file, add the following bolded statements:


Mobile Application Development Unit II Notes Dr. Geetha

ss

ss

ss

• Press Shift+F9 to debug the application on the Android emulator.


Mobile Application Development Unit II Notes Dr. Geetha

• Type some text into the EditText view (see Figure below) and then click
the Save button

ss

• If the file is saved successfully, you see the Toast class displaying the
“File saved successfully!”message. The text in the EditText view should
disappear.

• Click the Load button and you should see the string appearing in the
EditText view again. This confirms that the text is saved correctly.

7.4 How It Works


To save text into a file, you use the FileOutputStream class. The openFile-
Output() method opens a named file for writing, with the mode specified. In
this example, you use the MODE PRIVATE constant to indicate that the file
is readable by all other applications:
F i l e O u t p u t S t r e a m fOut = op enFileOu tput ( " textfile . txt " ,
MODE_PRIVATE ) ;

To convert a character stream into a byte stream, you use an instance of the
OutputStreamWriter class, by passing it an instance of the FileOutputStream
object:
O u t p u t S t r e a m W r i t e r osw = new O u t p u t S t r e a m W r i t e r ( fOut ) ;
Mobile Application Development Unit II Notes Dr. Geetha

You then use its write() method to write the string to the file. To ensure that
all the bytes are written to the file, use the flush() method. Finally, use the
close() method to close the file:
// - - - write the string to the file - - - osw . write ( str ) ;
osw . flush () ; osw . close () ;

o read the content of a file, you use the FileInputStream class, together with
the InputStreamReader class:
openFileInput ( " textfile . txt " ) ;
I n p u t S t r e a m R e a d e r isr = new I n p u t S t r e a m R e a d e r ( fIn ) ;

FileInputStream fIn = Because you do not know the size of the file to read, the
content is read in blocks of 100 characters into a buffer (character array). The
characters read are then copied into a String object:
char [] inputBuffer = new char [ R EA D _B LO CK _ SI ZE ];
String s = " " ;
int charRead ;
while (( charRead = isr . read ( inputBuffer ) ) >0)
{
// - - - convert the chars to a String - - -
String readString = String . copyValueOf ( inputBuffer , 0 , charRead ) ;
s += readString ;
inputBuffer = new char [ REA D_ BL O CK _S IZ E ];
}

The read() method of the InputStreamReader object checks the number of char-
acters read and returns –1 if the end of the file is reached.
Saving to External storage (sd Card) Sometimes, it would be useful to save
them to external storage (such as an SD card) because of its larger capacity,
as well as the capability to share the files easily with other users (by removing
the SD card and passing it to somebody else).You can use the following steps
to save files to external storage.

• Using the project created in the previous section as the example (saving
text entered by the user to the SD card), modify the onClick() method of
the Save button as shown in bold here:
Mobile Application Development Unit II Notes Dr. Geetha

ss

ss

• The preceding code uses the getExternalStorageDirectory() method to


return the full path to the external storage. Typically, it should return
the “/sdcard” path for a real device, and “/mnt/sdcard” for an Android
emulator. However, you should never try to hardcode the path to the
SD card, as manufacturers may choose to assign a different path name to
the SD card. Be sure to use the getExternalStorageDirectory() method to
return the full path to the SD card.
• You then create a directory called MyFiles in the SD card.
• Finally, you save the file into this directory.

• To load the file from the external storage, modify the onClickLoad()
method for the Load button:
Mobile Application Development Unit II Notes Dr. Geetha

ss

ss

• Note that in order to write to the external storage, you need to add
the WRITE EXTERNAL STORAGE permission in your AndroidMani-
[Link] file:

ss
Mobile Application Development Unit II Notes Dr. Geetha

7.5 Choosing the Best storage option


Which one should you use in your applications? Here are some guidelines:
• If you have data that can be represented using name/value pairs, then
use the SharedPreferences object. For example, if you want to store user
preference data such as username, background color, date of birth, or last
login date, then the SharedPreferences object is the ideal way to store this
data. Moreover, you don’t really have to do much to store data this way.
Simply use the SharedPreferences object to store and retrieve it.
• If you need to store ad-hoc data then using the internal storage is a good
option. For example, your application (such as an RSS reader) might need
to download images from the web for display. In this scenario, saving the
images to internal storage is a good solution. You might also need to
persist data created by the user, such as when you have an application
that enables users to take notes and save them for later use. In both of
these scenarios, using the internal storage is a good choice.
• There are times when you need to share your application data with other
users. For example ,you might create an Android application that logs
the coordinates of the locations that a user has been to, and subsequently,
you want to share all this data with other users. In this scenario, you
can store your files on the SD card of the device so that users can easily
transfer the data to other devices (and computers) for use later.

7.6 Creating and using dataBases


• So far, all the techniques you have seen are useful for saving simple sets
of data.
• For saving relational data, using a database is much more efficient.
• For example, if you want to store the test results of all the students in
a school, it is much more efficient to use a database to represent them
because you can use database querying to retrieve the results of specific
students.
• Moreover, using databases enables you to enforce data integrity by speci-
fying the relationships between different sets of data.
• Android uses the SQLite database system.
• The database that you create for an application is only accessible to itself;
other applications will not be able to access it.
• In this section, you find out how to programmatically create a SQLite
database in your Android application.
For Android, the SQLite database that you create programmatically in an ap-
plication is always stored in the /data/data/¡package name¿/databases folder.
Mobile Application Development Unit II Notes Dr. Geetha

7.7 Creating the dBadapter helper Class


1. Using Android Studio, create an Android project and name it Databases.
2. Add a new Java Class file to the package and name it DBAdapter

ss

3. Add the following bolded statements to the [Link] file:

ss
Mobile Application Development Unit II Notes Dr. Geetha

ss

ss

ss

ss
Mobile Application Development Unit II Notes Dr. Geetha

7.8 How it works


You first define several constants to contain the various fields for the table that
you are going to create in your database:
static final String KEY_ROWID = " _id " ;
static final String KEY_NAME = " name " ;
static final String KEY_EMAIL = " email " ;
static final String TAG = " DBAdapter " ;
static final String DATABASE_NAME = " MyDB " ;
static final String DA TABASE_T ABLE = " contacts " ; static final int
D A T A B A S E _ V E R S IO N = 1;
static final String DA TAB AS E_ CR E AT E =
" create table contacts ( _id integer primary key autoincrement , " +
" name text not null ,
email text not null ) ; " ;

In particular, the DATABASE CREATE constant contains the SQL statement


for creating the contacts table within the MyDB database.
Within the DBAdapter class, you also add a private class that extends the
SQLiteOpenHelper class. SQLiteOpenHelper is a helper class in Android to
manage database creation and version management. In particular, you must
override the onCreate() and onUpgrade() methods:

ss
The onCreate() method creates a new database if the required database is not
present. The onUpgrade() method is called when the database needs to be up-
graded. This is achieved by checking the value defined in the DATABASE VERSION
constant. For this implementation of the onUpgrade() method, you simply drop
the table and create it again. You can then define the various methods for open-
ing and closing the database, as well as the methods for adding/editing/deleting
rows in the table:
Mobile Application Development Unit II Notes Dr. Geetha

ss

ss

ss

Notice that Android uses the Cursor class as a return value for queries. Think
of the Cursor as a pointer to the result set from a database query. Using Cursor
enables Android to more efficiently manage rows and columns as [Link] use
a ContentValues object to store name/value pairs. Its put() method enables you
to insert keys with values of different data [Link] create a database in your
application using the DBAdapter class, you create an instance of the DBAdapter
class:
public DBAdapter ( Context ctx )
{
this . context = ctx ; DBHelper = new D atabase Helper ( context ) ;
}

The constructor of the DBAdapter class will then create an instance of the
DatabaseHelper class to create a new database:
Datab aseHelp er ( Context context )
{
Mobile Application Development Unit II Notes Dr. Geetha

super ( context , DATABASE_NAME , null , D A T A B A S E _ V E R S I O N ) ;


}

8 Using the Database Programmatically


With the DBAdapter helper class created, you are now ready to use the database.
In the following sections, you will learn how to perform the regular CRUD (cre-
ate, read, update and delete) operations commonly associated with databases.

8.0.1 Adding Contacts


The following Try It Out demonstrates how you can add a contact to the table

ss
Press Shift+F9 to debug the application on the Android emulator.

8.1 How It Works


In this example, you create an instance of the DBAdapter class:
DBAdapter db = new DBAdapter ( this ) ;

The insertContact() method returns the ID of the inserted row. If an error


occurs during the operation, it returns –1.

8.2 Retrieving all the Contacts


To retrieve all the contacts in the contacts table, use the getAllContacts()
method of the DBAdapter class, as the following Try It Out shows
Mobile Application Development Unit II Notes Dr. Geetha

ss

ss

ss

8.3 How It Works


The getAllContacts() method of the DBAdapter class retrieves all the contacts
stored in the database. The result is returned as a Cursor object. To display
Mobile Application Development Unit II Notes Dr. Geetha

all the contacts, you first need to call the moveToFirst() method of the Cursor
object. If it succeeds (which means at least one row is available), then you
display the details of the contact using the DisplayContact() method. To move
to the next contact, call the moveToNext() method of the Cursor object.

8.4 Retrieving a Single Contact


To retrieve a single contact using its ID, call the getContact() method of the
DBAdapter class, as the following Try It Out shows.
Retrieving a Contact from a table

ss

8.5 How It Works


The getContact() method of the DBAdapter class retrieves a single contact
using its ID. You pass in the ID of the contact. In this case, you pass in an
ID of 2 to indicate that you want to retrieve the second contact: Cursor c
= [Link](2); Updating a Contact To update a particular contact, call
the updateContact() method in the DBAdapter class by passing the ID of the
contact you want to update, as the following Try It Out shows.
Mobile Application Development Unit II Notes Dr. Geetha

8.6 Updating a Contact in a table

ss

8.7 How It Works


The updateContact() method in the DBAdapter class updates a contact’s details
by using the ID of the contact you want to update. It returns a Boolean value,
indicating whether the update was successful.

8.8 Deleting a Contact


To delete a contact, use the deleteContact() method in the DBAdapter class by
passing the ID of the contact you want to update, as the following Try It Out
shows

ss

8.9 How It Works


The deleteContact() method in the DBAdapter class deletes a contact using the
ID of the contact you want to delete. It returns a Boolean value, indicating
whether the deletion was successful.
Mobile Application Development Unit II Notes Dr. Geetha

8.10 Upgrading the Database


Sometimes, after creating and using the database, you might need to add addi-
tional tables, change the schema of the database, or add columns to your tables.
In this case, you need to migrate your existing data from the old database to a
newer one.
To upgrade the database, change the DATABASE VERSION constant to a
value higher than the previous one. For example, if its previous value was 1,
change it to 2:

ss
When you run the application one more time, you see the following message in
the logcat window of Android Studio: DBAdapter(8705): Upgrading database
from version 1 to 2,

You might also like