0% found this document useful (0 votes)
5 views

android lab1

This document is a workbook for the T.Y.B.C.A. (Science) Semester-VI Android Programming lab course at Ahmednagar Jilha Maratha Vidya Prasarak Samaj’s New Arts, Commerce and Science College. It includes certification templates, assignment completion sheets, and detailed instructions for installing Android Studio, creating a basic Android application, and understanding Android components like activities and fragments. The document outlines practical tasks and evaluation criteria for students completing the Android Programming coursework.

Uploaded by

pranita.tathe15
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

android lab1

This document is a workbook for the T.Y.B.C.A. (Science) Semester-VI Android Programming lab course at Ahmednagar Jilha Maratha Vidya Prasarak Samaj’s New Arts, Commerce and Science College. It includes certification templates, assignment completion sheets, and detailed instructions for installing Android Studio, creating a basic Android application, and understanding Android components like activities and fragments. The document outlines practical tasks and evaluation criteria for students completing the Android Programming coursework.

Uploaded by

pranita.tathe15
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 86

Ahmednagar Jilha Maratha Vidya Prasarak Samaj’s

New Arts, Commerce and Science College, Ahmednagar


(Autonomous)

T.Y.B.C.A. (Science) Semester-VI


(2019 Pattern)
BCA 605P
DSE I Lab

Work Book
Android Programming
To be implemented from
Academic Year 2024–2025
Name:

College Name

Roll No.: Seat No:

Academic Year:
CERTIFICATE

This is to certify that Mr./Ms.____________________________

has successfully completed TYBCA (Science) BCA605P DSE I

Lab Programming in Java Semester VI course in year

_______________and his/her seat no. is __________.

He / She have scored ________ marks out of 15.

Instructor HOD/Coordinator

Internal Examiner External Examiner


Assignment Completion Sheet

Lab Course I – Android Programming

Assignment Assignment Name Marks Teachers Sign


No. (out of 5)

1 Introduction to Android

2 Activities, Fragments and Intents

3 Android User Interface and Event Handling

4 Designing Your User Interface with Views

5 Displaying Pictures and Menus

6 Databases – SQLite

7 Messaging and Email

8 Location-Based Services and Google Maps

Total (out of 40)

Total (out of 10)

This is to certify that Mr. / Ms.


Has successfully completed the Android Programming course work for Lab Course I
and has scored ____________ Marks out of 30.

Instructor H.O.D. / Coordinator


Assignment No. 1 No. of Sessions: 02
Assignment Name : Introduction to Android

• Study Android Studio installation.


• Create basic android application.

You should read the following topics before starting this exercise:
1. Java Installation
2. Android Studio
3. Android architecture

1. Installing Android Studio

1) Install Java JDK. The file I used is: (jdk-8u45-windows-x64.exe). 8u45-windows


indicate the version 8u45 for windows. Get the latest version. x64 indicates this is for 64
bit processors, x86 is the 32bit version.
The JDK may be downloaded here:
http://www.oracle.com/technetwork/java/javase/downloads/jdk8-
downloads2133151.html
2) Install Android Studio bundle. The file I used is: (android-studio-bundle-141.1903250 -
windows.exe). Use the latest stable version. Android Studio may be downloaded here:
https://developer.android.com/sdk/index.html
3) Follow the prompts to complete the installation. I used the default settings.
4) Allow Android Studio access to the network.
5) Select your desired UI theme.
6) Android Studio will download additional components. This will take several minutes.
7) Select ―Configure/SDK Manager‖.
8) Deselect A

ll. Scroll
down and select ―Android 4.4.2 (API 19)‖ and ―Intel x86 Emulator
Accelerator (HAXM installer)‖
9) Install the packages. You may need to repeat the process of installing packages until all
of them are installed. When the ―Install packages…‖ button is no longer active you may
close the Android SDK Manager.
10) To create new project, click on Start a new Android Studio project.
11) You may change the Application name and Company Domain.
12) Select API 19 as the Minimum SDK.
13) Select Blank Activity.
14) The default values are good.
15) The Windows Firewall may complain again. Click on Allow access.
16) Select the AVD Manager from the toolbar at the top.
17) Edit this AVD by clicking the green marker icon on the right.
18) Change the AVD name to Nexus 5 API 19 and OS from Lollipop to KitKat.
19) Change the Google API from Lollipop to KitKat API level 19.
a. The x86 virtual devices run faster on a Windows system. If you have problems
running it then select armeabi-v7a Google APIs instead.

Android Studio is now installed. It automatically checks for updates. If you update it you may
need to repeat some of the steps above to get it working again.

2. Create "Hello World" application

1. Launch Android Studio if it is not already opened.


2. In the main Welcome to Android Studio window, click "Start a new Android Studio
project".
3. In the New Project window, give your application an Application Name, such as "Hello
World".
4. Verify the Project location, or choose a different directory for storing your project.
5. Choose a unique Company Domain.
o Apps published to the Google Play Store must have a unique package name. Since
domains are unique, prepending your app's name with your or your company's
domain name is going to result in a unique package name. o If you are not planning
to publish your app, you can accept the default example domain. Be aware that
changing the package name of your app later is extra work.
6. Verify that the default Project location is where you want to store your Hello World app
and other Android Studio projects, or change it to your preferred directory. Click Next.
7. On the Target Android Devices screen, "Phone and Tablet" should be selected. And you
should ensure that API 15: Android 4.0.3 IceCreamSandwich is set as the
Minimum SDK. (Fix this if necessary.) o At the writing of this book, choosing this API
level makes your "Hello World" app compatible with 97% of Android devices active
on the Google Play Store.
o These are the settings used by the examples in this book.
8. Click Next.
9. ustomize the Activity window. Every app needs at least one activity. An activity
represents a single screen with a user interface and Android Studio provides templates to
help you get started. For the Hello World project, choose the simplest template (as of this
writing, the "Empty Activity" project template is the simplest template) available.
10. It is a common practice to call your main activity MainActivity. This is not a
requirement.
11. Make sure the Generate Layout file box is checked (if visible).
12. Make sure the Backwards Compatibility (App Compat) box is checked.
13. Leave the Layout Name as activity_main. It is customary to name layouts after the
activity they belong to. Accept the defaults and click Finish.
14. Builds your project with Gradle (this may take a few moments). Android Studio uses
Gradle as its build system. See the Configure your build developer page for more
information.
15. Opens the code editor with your project. And it displays a tip of the day.
o Android Studio offers many keyboard shortcuts, and reading the tips is a great way
to learn them over time.
17. The Android Studio window should look similar to the following diagram:
o Click on the Hello World folder to expand the hierarchy of files (1), o Click
on Project (2). o Click on the Android menu (3). o Explore the different view
options for your project.

3. Explore the project structure


3.1. Explore the project structure and layout

In the Project > Android view of your previous task, there are three top-level folders
below your app folder: manifests, java, and res.

1. Expand the manifests folder.

This folder contains AndroidManifest.xml. This file describes all of the components of
your Android app and is read by the Android run-time system when your program is
executed.

2. Expand the java folder. All your Java language files are organized in this folder. The
java folder contains three subfolders:
o com.example.hello.helloworld (or the domain name you have specified): All
the files for a package are in a folder named after the package. For your Hello
World application, there is one package and it only contains MainActivity.java
(the file extension may be omitted in the Project view). o
com.example.hello.helloworld(androidTest): This folder is for your
instrumented tests, and starts out with a skeleton test file.
o com.example.hello.helloworld(test): This folder is for your unit tests and starts
out with an automatically created skeleton unit test file.

3. Expand the res folder. This folder contains all the resources for your app, including
images, layout files, strings, icons, and styling. It includes these subfolders:
o drawable: Store all your app's images in this folder.
o mipmap: Store your launcher icons in this folder. There is a sub-folder for each
supported screen density. Android uses the screen density, that is, the number of
pixels per inch to determine the required image resolution. Android groups all
actual screen densities into generalized densities, such as medium (mdpi), high
(hdpi), or extra-extra-extra-high (xxxhdpi). The ic_launcher.png folder contains
the default launcher icons for all the densities supported by your app.
o values: Instead of hardcoding values like strings, dimensions, and colors in your
XML and Java files, it is best practice to define them in their respective values
file. This makes it easier to change and be consistent across your app.

4. Expand the values subfolder within the res folder. It includes these subfolders:
o colors.xml: Shows the default colors for your chosen theme, and you can add
your own colors or change them based on your app's requirements.
o dimens.xml: Store the sizes of views and objects for different resolutions.
o strings.xml: Create resources for all your strings. This makes it easy to translate
them to other languages.
o styles.xml: All the styles for your app and theme go here. Styles help give your
app a consistent look for all UI elements.

3.2. The Gradle build system

Android Studio uses Gradle as its build system. As you progress through these practicals,
you will learn more about gradle and what you need to build and run your apps.

1. Expand the Gradle Scripts folder. This folder contains all the files needed by the build
system.
2. Look for the build.gradle(Module:app) file. When you are adding app-specific
dependencies, such as using additional libraries, they go into this file.

In this task, you will use the Android Virtual Device (AVD) manager to create a virtual device
or emulator that simulates the configuration for a particular type of Android device.

Using the AVD Manager, you define the hardware characteristics of a device and its API level,
and save it as a virtual device configuration.
When you start the Android emulator, it reads a specified configuration and creates an emulated
device that behaves exactly like a physical version of that device, but it resides on your
computer.

Why: With virtual devices, you can test your apps on different devices (tablets, phones) with
different API levels to make sure it looks good and works for most users. You do not need to
depend on having a physical device available for app development.

4.1 Create a virtual device

In order to run an emulator on your computer, you have to create a configuration that
describes the virtual device.

1. In Android Studio, select Tools > Android > AVD Manager, or click the AVD

Manager icon in the toolbar.


2. Click the +Create Virtual Device…. (If you have created a virtual device before, the
window shows all of your existing devices and the button is at the bottom.)
The Select Hardware screen appears showing a list of preconfigured hardware devices.
For each device, the table shows its diagonal display size (Size), screen resolution in
pixels (Resolution), and pixel density (Density).
For the Nexus 5 device, the pixel density is xxhdpi, which means your app uses the
launcher icons in the xxhdpi folder of the mipmap folder. Likewise, your app will use
layouts and drawables from folders defined for that density as well.
3. Choose the Nexus 5 hardware device and click Next.

4. system to run on the virtual device. You can select the latest system image.
There are many more versions available than shown in the Recommended tab. Look at
the x86 Images and Other Images tabs to see them.
5. If a Download link is visible next to a system image version, it is not installed yet, and
you need to download it. If necessary, click the link to start the download, and click
Finish when it's done.
6. On System Image screen, choose a system image and click Next.

Verify your configuration, and click Finish. (If the Your Android Devices AVD Manager

window stays open, you can go ahead and close it.) 5. Run your app on an emulator

In this task, you will finally run your Hello World app.

5.1 Run your app on an emulator


1. In Android Studio, select Run > Run app or click the Run icon in the toolbar.
2. In the Select Deployment Target window, under Available Emulators, select Nexus 5
API 23 and click OK.

You should see the Hello World app as shown in the following screenshot.
Assignment Evaluation

a. 0: Not Done [ ] 1: Incomplete [] 2: Late Complete []


b. 3: Needs Improvement [] 4: Complete [] 5: Well-done []

Assignment No. 2 No. of Sessions: 02


Assignment Name : : Activities, Fragments and Intents

1. Activity
An activity is a single, focused thing that the user can do. Almost all activities interact with the
user, so the Activity class takes care of creating a window for you in which you can place your
UI with setContentView(View).
Activity Lifecycle
Activities in the system are managed as an activity stack. When a new activity is started, it is
placed on the top of the stack and becomes the running activity - the previous activity always
remains below it in the stack, and will not come to the foreground again until the new activity
exits.
Public Methods Description
void onCreate(Bundle saveInstanceState) Called when the activity is first created. This
is where you should do all of your normal
static set up: create views; bind data to lists,
etc.
void onRestart() Called after your activity has been stopped,
prior to it being started again.
void onStart() Called when the activity is becoming visible
to the user.
void onResume() Called when the activity will start interacting
with the user.
void onPause() Called when the system is about to start
resuming a previous

Public Methods Description


void onStop() Called when the activity is no longer visible to the user.

void onDestroy() The final call you receive before your activity is This
can happen either because the activity is finishing
This method is used get in this method a reference to the
void onAttach (Activity activity) activity which uses the fragment for further initialization
work.
The system calls this method when creating the fragment.
activity. This is typically used to commit unsaved
void onCreate (Bundle changes to persistent

2. Fragments
A Fragment is a piece of an activity which enable more modular activity design. It will not be
wrong if we say, a fragment is a kind of sub-activity.

A Fragment is a piece of an activity which enable more modular activity design. It will not be
wrong if we say, a fragment is a kind of sub-activity.

savedInstanceState) You should initialize essential components of the


fragment that you want to retain when the fragment is
paused or stopped, then resumed.

A Fragment is a piece of an activity which enable more modular activity design. It will not be
wrong if we say, a fragment is a kind of sub-activity.
View onCreateView (LayoutInflater The system calls this callback when it's time for the
inflater, ViewGroup container, fragment to draw its user interface for the first time.
Bundle savedInstanceState)
void onActivityCreated (Bundle This method is called when the host activity is
savedInstanceState) created. In this method you can instantiate objects
which require a Context object.
void onStart() This method is called once the fragment gets visible.
void onResume() Fragment becomes active.
void onPause() The system calls this method as the first indication
that the user is leaving the fragment. This is usually
where you should commit any changes that should
be persisted beyond the current user session. 2 In
void onStop() Fragment going to be stopped by calling onStop() tent
An
void onDestroyView() Fragment view will destroy after call this method
void onDestroy() This method is called to do final cleanup of the
fragment's state but Not guaranteed to be called by
the Android platform.

Android Intent is an abstract description of an operation to be performed. The intent itself, an


Intent object, is a passive data structure holding an abstract description of an operation to be
performed

Method Description
Context.startActivity() The Intent object is passed to this method to launch a new activity
or get an existing activity to do something new.
Context.startService() The Intent object is passed to this method to initiate a service or
deliver new instructions to an ongoing service.
Context.sendBroadcast() The Intent object is passed to this method to deliver the message to
all interested broadcast receivers.

Example: Assume that you have an Activity that needs to open URL in a web browser on your
Android device. For this purpose, your Activity will send ACTION_WEB_SEARCH Intent to the
Android Intent Resolver to open given URL in the web browser. The Intent Resolver parses
through a list of Activities and chooses the one that would best match your Intent, in this case, the
Web Browser Activity. The Intent Resolver then passes your web page to the web browser and
starts the Web Browser Activity.
String q = "developers.android";
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH );
intent.putExtra(SearchManager.QUERY, q);
startActivity(intent)

3.1. Types Of Intent


1) Implicit Intent: These intents do not name a target and the field for the component name is left
blank. Implicit intents are often used to activate components in other application
Example:
Intent i1=new Intent();
i1.setAction(android.contact.Intent.ACTION_VIEW);
.setData(ContactsContract.CONTENT_URI);
startActivity(I1)

Above code will give result as shown below:


2) Explicit Intent: Explicit intent going to be connected internal world of application, suppose if
you wants to connect one activity to another activity, we can do this quote by explicit intent, below
image is connecting first activity to second activity by clicking button. Example
// Explicit Intent by specifying its class name
Intent i=new Intent(FirstActivity.this,SecondActivity.class) //Starts
TargetActivit

SET A
1. Create a Simple Application Which Shows Life Cycle of Activity.
2. Create a Simple Application Which Send ―Hello‖ message from one activity to another with
help of Button (Use Intent).
3. Create Simple application to display details of selected list item on Second Activity (use
Fragmentation)
SET B
1 Create simple application with Login Screen. On successful login, gives message go to
next Activity (Without Using Database)

3 . Create First Activity to accept information like Student First Name, Middle Name, Last
Name, Date of birth, Address, Email ID and display all information on Second Activity when
user click on Submit button.
SET C
Design Following Screens Using Intents. On second activity take Button. On clicking it, it
should Show Information of profile on Third activity. (Without Using Database)
Assignment Evaluation
c. 0: Not Done [ ] 1: Incomplete [] 2: Late Complete []
d. 3: Needs Improvement [] 4: Complete [] 5: Well-done []
Assignment No. 3 No. of Sessions: 02

Assignment Android User Interface and Event Handling


Name :
Views –
The basic building block for user interface is a View object which is created from the View class
and occupies a rectangular area on the screen and is responsible for drawing and event handling
Views Groups - The View Group is a subclass of View and provides invisible container that hold
other Views or other View Groups and define their layout properties.
At third level we have different layouts which are subclasses of View Group class and a typical
layout defines the visual structure for an Android user interface and can be created either at run
time using View/View Group objects or you can declare your layout using simple XML file
main_layout.xml which is located in the res/layout folder of your project

 Types of layouts
1. Linear Layout: Linear Layout is a view group that aligns all children in a single direction,
vertically or horizontally.

<?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:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a TextView"/>
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a Button"/>
<!-- More GUI components go here -->
</LinearLayout>

2. Absolute Layout:
Absolute Layout enables you to specify the exact location of its children.
<AbsoluteLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="OK"
android:layout_x="50px"
android:layout_y="361px"/>
<Button android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Cancel"
android:layout_x="225px"
android:layout_y="361px"/>
</AbsoluteLayout>

3. Table Layout: Table Layout is a view that groups views into rows and columns.
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableRow android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:text="First Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"/>

3. RelativeLayout: Relative Layout is a view group that displays child views in relative
positions.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<EditText android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/reminder"/>
<LinearLayout android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentStart="true"
20
android:layout_below="@+id/name">
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button"/>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button2"/>
</LinearLayout>
</RelativeLayout>

4. FragmentLayout: FrameLayout is a placeholder on screen that you can use to display a


single view
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView android:src="@drawable/ic_launcher"
android:scaleType="fitCenter"
android:layout_height="250px"
android:layout_width="250px"/>
<TextView android:text="Frame Demo"
android:textSize="30px"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:gravity="center"/>
</FrameLayout>

5. ScrollLayouts: When an app has layout content that might be longer than the height of
the device and that content should be vertically scrollable, then we need to use a Scroll
View.
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp"
android:fillViewport="false">
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="200dp"
android:scaleType="centerCrop"
android:src="@drawable/image"/>
<Button android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="KNOW MORE"/>
<TextView android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/title"
android:textAppearance="?android:attr/textAppearanceLarge"/>
<TextView android:id="@+id/textView2"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="@string/description"
android:textAppearance="?android:attr/textAppearanceSmall"/>

6. ScrollView: ScrollView
is a special kind of layout, designed to hold view larger than its actual size. When the Views
size goes beyond the ScrollView size, it automatically adds scroll bars and can be scrolled
vertically.
<ScrollView android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/tv_long" android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="@string/really_long_string">
</TextView>
<Button android:id="@+id/btn_act"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="View">
</Button>
</LinearLayout>
</ScrollView>

 Adopting to Display Orientation


 Anchoring View Anchoring –
This is easiest way to anchor views to the four edges of the screen. When the screen
orientation changes, the views can anchor neatly to the edges.

Attribute Name Description


android:layout_alignParentLeft If set true, component place at left
corner
android:layout_alignParentRight If set true, component place at right
corner
android:layout_alignParentTop if set true, component place at top.
android:layout_alignParentBottom If set true, component place at bottom.
android:layout_centerVertical If set true, component place at
vertically center position.
android:layout_centerHorizontal If set true, component place at
horizontally center position.

Below is the example to display button at bottom center position.

<Button android:layout_width="120px"
android:layout_height="wrap_content"
android:text="Position - Bottom Middle"
android:id="@+id/buttondisplay7"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true" />

 Managing changes to screen orientation Some device configurations can change during
runtime (such as screen orientation, keyboard availability, and language). When such a
change occurs, Android restarts the running Activity. To properly handle a restart, it is
important that your activity restores its previous state through the normalActivity lifecycle,
in which Android calls onSaveInstanceState() before it destroys 24 your activity so that you
can save data about the application state. Details on how you can use onSaveInstanceState()
can be found at Saving and restoring activity state.
a. Retain an object during a configuration change Allow your activity to restart when a
configuration changes, but carry a stateful object to the new instance of your activity.
b. Handle the configuration change yourself Prevent the system from restarting your
activity during certain configuration changes, but receive a callback when the
configurations do change, so that you can manually update your activity as necessary.
c. Retaining an Object during a Configuration Change When the Android system shuts
down your activity due to a configuration change, the fragments of your activity that you
have marked to retain are not destroyed. You can add such fragments to your activity to
preserve stateful objects.
i) Extend the Fragment class and declare references to your stateful objects
. ii) Call setRetainInstance(boolean) when the fragment is created
iii) Add the fragment to your activity.
iv) Use FragmentManager to retrieve the fragment when the activity is restarted
public class RetainedFragment extends Fragment{
// data object we want to retain
private MyDataObject data;
// this method is only called once for this fragment
@Override
public void onCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
// retain this fragment
setRetainInstance(true);
}
public void setData(MyDataObject data){
25
this.data= data;
}
public MyDataObject getData(){
return data;
}
}

While onCreate() is called only once when the retained fragment is first created you can use
onAttach() or onActivityCreated() to know when the holding activity is ready to interact
with this fragment. And in your activity you can use this fragment to preserve states across
configuration change restarts. Then use FragmentManager to add the fragment to the
activity. You can obtain the data object from the fragment when the activity starts again
during runtime configuration changes.
For example, define your activity as follows:

public class RetainedFragment extends Fragment{


// data object we want to retain
private MyDataObject data;
// this method is only called once for this fragment
@Override
public void onCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
// retain this fragment
setRetainInstance(true);
}
public void setData(MyDataObject data){

this.data= data;
}
public MyDataObject getData(){
return data;
}
}

In order to proactively remove the retained fragment when you no longer need it, you may
check for isFinishing() in onPause() in the activity.

@Override
public void onPause(){
// perform other onPause related actions
...
// this means that this activity will not be recreated now, user is leaving it
// or the activity is otherwise finishing
if(isFinishing()){
FragmentManager fm = getFragmentManager();
// we will not need this fragment anymore, this may also be a good place to
signal
// to the retained fragment object to perform its own cleanup.
fm.beginTransaction().remove(mDataFragment).commit();
}
}

 Handling Configuration change If your application doesn't need to update resources


during a specific configuration change and you have a performance limitation that requires
you to avoid the activity restart, then
you can declare that your activity handles the configuration change itself, which prevents
the system from restarting your activity
.  Utilizing Action Bar Overview of Action Bar Action bar mainly contains four functional
areas. They are app icon, view control, action buttons and action overflow.
1. App Icon – App branding logo or icon will be displayed here.
2. View Control – A dedicated space to display app title. Also provides option to switch
between views by adding spinner or tabbed navigation.
3. Action Buttons – Some important actions of the app can be added here. 4. Action
Overflow – All unimportant action will be shown as a menu

Adding Action Bar Icons


Once you are done copying required icons, we will start adding the action items first. The

under res ⇒ menu named activity_main_actions.xml and add the following code. Here each
action bar uses the same older menu method to show action items. Create a new xml file

indicates each action item.


<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- Search / will display always -->
<item android:id="@+id/action_search"
android:icon="@drawable/ic_action_search"
android:title="@string/action_search"
android:showAsAction="ifRoom"/>
<!-- Location Found -->
<item android:id="@+id/action_location_found"
android:icon="@drawable/ic_action_location_found"
android:title="@string/action_location_found"
android:showAsAction="ifRoom" />
<!-- Help -->
<item android:id="@+id/action_help"
android:icon="@drawable/ic_action_help"
android:title="@string/action_help"android:showAsAction="never"/>
</menu>

Here the important xml attributes should be known are android:icon – Defines the icon of
the action item
. android:title – Title for the icon.
Androidd:showAsAction – Defines the visibility of the action item. It accepts following
values.

ifRoom Displays the icon if there is space available on the screen

never Never places this icon on the action bar

always Forces to display the icon always irrespective of space available.


This way is not suggested.

withText Displays a text along with the icon. Normally the text value
defined by android:title will be displayed

collapseActionView Defines the action layout associated with it. This action view
defined usingandroid:actionLayout or android:actionViewClass

Now open your mainActivity.java and do the following in onCreateOptionsMenu() method


public class MainActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflaterinflater = getMenuInflater();
inflater.inflate(R.menu.activity_main_actions, menu);
returnsuper.onCreateOptionsMenu(menu);
}
}
Android Custom Action Bar: The activity_main.xml is an empty Relative Layout since our
emphasis here is on the Action Bar. The MainActivity.java is given below.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity{
@Override
protected void onCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setDisplayOptions(
ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setCustomView(R.layout.custom_action_bar_layout);
View view=getSupportActionBar().getCustomView();
ImageButtonimageButton = (ImageButton) view.findViewById
(R.id.action_bar_back);
imageButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
finish()
}
});
ImageButton imageButton2 = (ImageButton) view.findViewById
(R.id.action_bar_forward);
imageButton2.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
Toast.makeText(getApplicationContext(),"Forward
Button is clicked",Toast.LENGTH_LONG).show();
}
});
}
}
SET A
1. Design following-add a border to an Android Layout

3. Create the simple calculator shown below also perform appropriate operation
SET B
1. Create new contact for designing following layout

2. Create following Vertical Scroll View Creation in Android.

SET C
1. Create following layout which is changing android spinner text size with styles.
Assignment Evaluation

a. 0: Not Done [ ] 1: Incomplete [] 2: Late Complete []


b. 3: Needs Improvement [] 4: Complete [] 5: Well-done []
Assignment No. 4 No. of Sessions: 02
Assignment Name : Designing Your User Interface with View

Types of View
 TextView: TextView used to create text field.
A TextView displays text to the user and optionally allows them to edit it.
Attribute Name Description
android:id This is the ID which uniquely identifies the control.
android:editable If set to true, specifies that this TextView has an input method.
android:inputType The type of data being placed in a text field. Phone, Date, Time,
Number, Password etc.

android:text Text to display.


android:textAllCaps If set to true, display the text in ALL CAPS.
• TextView: TextView used to create text field. A TextView displays text to the user and
optionally allows them to edit it.

To create TextView make following changes in res/layout/activity_main.xml file

<TextView android:id="@+id/text_id"

android:layout_width="300dp"
android:layout_height="200dp"
android:capitalize="characters"
android:text="hello_world"/>

To access the value of TextView make following changes in MainActivity.java file

TextView txtView = (TextView) findViewById(R.id.text_id);

• EditText: An EditText is an overlay over TextView that configures itself to be editable. It


is the predefined subclass of TextView that includes rich editing capabilities.

Attribute Name Description


android:autoText If set to true, specifies that this TextView has a textual input method
and automatically corrects some common spelling errors.

android:drawableBottom This is the drawable to be drawn below the text.

To create EditText make following changes in res/layout/activity_main.xml file


<EditText android:id="@+id/edittext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/enter_text"
android:inputType="text" />

EditText eText = (EditText) findViewById(R.id.edittext);


To access the value of EditText make following changes in MainActivity.java file
• Button: A Button is a Push-button which can be pressed, or clicked, by the user to perform
an action.

To create Button make following changes in res/layout/activity_main.xml file

<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" android:id="@+id/button"
/>
To access the value of Button make following changes in MainActivity.java file

Button b1 = (Button)findViewById(R.id.button);

• ImageButton: An ImageButton is an AbsoluteLayout which enables you to specify the


exact location of its children. This shows a button with an image.

Attribute Name Description


android:adjustViewBounds Set this to true if you want the ImageView to adjust its bounds to
preserve the aspect ratio of its drawable.

android:baseline This is the offset of the baseline within this view.


android:baselineAlignBottom If true, the image view will be baseline aligned with based on its
bottom edge.

android:cropToPadding If true, the image will be cropped to fit within its padding.
android:src This sets a drawable as the content of this ImageView.

<ImageButton android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
To create ImageButton

android:src="@drawable/abc"/>
To access the value of ImageButton make following changes in MainActivity.java file

ImageButton imgButton = (ImageButton)findViewById(R.id.imageButton);


• ToggleButton: A ToggleButton displays checked/unchecked states as a button. It is
basically an on/off button.

Attribute Name Description


android:disabledAlpha This is the alpha to apply to the indicator when disabled.
android:textOff This is the text for the button when it is not checked.
android:textOn This is the text for the button when it is checked.

To create ToggleButton make following changes in res/layout/activity_main.xml file

<ToggleButton android:layout_width="wrap_content"

android:layout_height="wrap_content"
android:text="On"
android:id="@+id/toggleButton"
android:checked="true" />
To access the value of ToggleButton make following changes in MainActivity.java file

ToggleButton tg1 = (ToggleButton)findViewById(R.id.toggleButton);


• RadioButton: A RadioButton has two states: either checked or unchecked. This allows the
user to select one option from a set.

<RadioButton android:layout_width="wrap_content"

android:layout_height="wrap_content"
To create RadioButton make following changes in res/layout/activity_main.xml file
android:text="ANDROID"
android:id="@+id/radioButton2" android:checked="false"
/>

• RadioGroup: A RadioGroup class is used for set of radio buttons. If we check one radio
button that belongs to a radio group, it automatically unchecks any previously checked radio
button within the same group.

Attribute Name Description


android:checkedButton This is the id of child radio button that should be checked by
default within this radio group.

<RadioGroup android:layout_width="fill_parent"

android:layout_height="90dp"

android:layout_marginTop="58dp"

android:id="@+id/radioGroup" >

<RadioButton android:layout_width="wrap_content"

android:layout_height="55dp"

android:text="Male"

android:id="@+id/radioButton"

android:checked="false" />

<RadioButton android:layout_width="wrap_content"

android:layout_height="wrap_content"
android:text="Female" android:id="@+id/radioButton2"
To create RadioGroup make following changes in res/layout/activity_main.xml file
RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radioGroup); int

selectedId=radioGroup.getCheckedRadioButtonId();

RadioButton radioButton = (RadioButton)findViewById(selectedId);

• CheckBox: A CheckBox is an on/off switch that can be toggled by the user. You should
use check-boxes when presenting users with a group of selectable options that are not
mutually exclusive.

To create CheckBox make following changes in res/layout/activity_main.xml file

<CheckBox android:id="@+id/checkBox2"

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Do you like android "
android:checked="false" />
To access the value of CheckBox make following changes in MainActivity.java file

CheckBox ch1 = (CheckBox)findViewById(R.id.checkBox1);


Public Methods Description
int getMax() This method returns the maximum value of the
progress.

• ProgressBar: Allows you to create progress bar. Progress bars are used to show progress of
a task.
void incrementProgressBy(int diff) This method increment the progress bar by the
difference of value passed as a parameter.

void setIndeterminate(boolean indeterminate) This method sets the progress indicator as


determinate or indeterminate.

void setMax(int max) This method sets the maximum value of the
progress dialog.

void setProgress(int value) This method is used to update the progress


dialog with some specific value.

void show(Context context, CharSequence This is a static method, used to display progress
title, CharSequence message) dialog.

To create ProgressBar make following changes in res/layout/activity_main.xml file

<ProgressBar android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:progress=‖25‖ />
progressBar = (ProgressBar) findViewById(R.id.progressBar); new

Thread(new Runnable() {

public void run() {

while (progressStatus < 100) {

progressStatus += 1;

// Update the progress bar and display the current value in the text view

handler.post(new Runnable() {

public void run()


{ progressBar.setProgress(progressStatus);
textView.setText(progressStatus+"/"+ progressBar.getMax());
}
});
try {
Thread.sleep(200); // Sleep for 200 milliseconds.
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start()
To access
 AutoCompleteTextView:
An AutoCompleteTextView is a view that is similar to EditText, except that it shows a list of
completion suggestions automatically while the user is typing

textView.setText(progressStatus+"/"+ progressBar.getMax());

});

try {

Thread.sleep(200); // Sleep for 200 milliseconds.

} catch (InterruptedException e) {

e.printStackTrace();

}).start();

To access the value of ProgressBar make following changes in MainActivity.java file 


AutoCompleteTextView: An AutoCompleteTextView is a view that is similar to EditText, except
that it shows a list of completion suggestions automatically while the user is typing.

Attribute Name Description


android:completionHint Used to define the hint displayed in the drop down menu.
android:completionThreshold Used to define the number of characters that the user must type
before completion suggestions are displayed in a drop down.

android:dropDownAnchor This is the View to anchor the auto-complete dropdown to.


android:dropDownHeight Used to specify the basic height of the dropdown.
android:dropDownSelector This is the selector in a drop down list.
android:dropDownWidth This specifies the basic width of the dropdown.

<AutoCompleteTextView android:id="@+id/autoCompleteTextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" />

To access the value of AutoCompleteTextView make following changes in MainActivity.java


AutoCompleteTextView autocomplete = (AutoCompleteTextView) findViewById
(R.id.autoCompleteTextView1);
String[] arr = { "India", "United States","Brazil", "Italy"};
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this,
android.R.layout.select_dialog_item, arr); autocomplete.setThreshold(2);
autocomplete.setAdapter(adapter);

TimePicker:
Android Time Picker allows you to select the time of day in either 24 hour or AM/PM mode. The
time consists of hours, minutes and clock format.
Public Methods Description
boolean is24HourView() Returns true if this is in 24 hour view
boolean isEnabled() Returns the enabled status for this view
void setCurrentHour(Integer currentHour) This method sets the current hour
void setCurrentMinute(Integer currentMinute) This method sets the current minute
void setIs24HourView(Boolean is24HourView) This method set whether in 24 hour or
AM/PM mode
void setOnTimeChangedListener
This method Set the callback that indicates the
(TimePicker.OnTimeChangedListener time has been adjusted by the user
onTimeChangedListener)

To create TimePicker make following changes in res/layout/activity_main.xml file


TimePicker android:id="@+id/timePicker1"
Public Methods Description
int getDayOfMonth() Returns the selected day of month
android:layout_width="wrap_content"
int getMonth() Returns the selected month
android:layout_height="wrap_content" />
int getYear() Returns the selected year
void setMaxDate(long maxDate) This method sets the maximal date supported by
this DatePicker in milliseconds since January 1,

1970 00:00:00 in getDefault() time zone


void updateDate(int year, int month, int
This method updates the current date
dayOfMonth)
CalendarView getCalendarView() Returns calendar view
int getFirstDayOfWeek() Returns first day of the week
To access the value of TimePicker make following changes in MainActivity.java file

import android.widget.TimePicker; private TimePicker


timePicker1; timePicker1 = (TimePicker)
findViewById(R.id.timePicker1); int hour =
timePicker1.getCurrentHour(); int min =
timePicker1.getCurrentMinute();
• DatePicker: Android Date Picker allows you to select the date consisting of day, month
and year in your custom user interface.

To create DatePicker make following changes in res/layout/activity_main.xml file

<DatePicker android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

To access the value of DatePicker make following changes in MainActivity.java file

DatePicker picker = (DatePicker)findViewById(R.id.datePicker1);

• ListView: ListView is a view which groups several items and display them in vertical
scrollable list. The list items are automatically inserted to the list using an Adapter that pulls
content from a source such as an array or database.
To create ListView make following changes in res/layout/activity_main.xml file

<ListView android:id="@+id/mobile_list"

android:layout_width="match_parent"

android:layout_height="wrap_content" >

</ListView>
To access the value of ListView make following changes in MainActivity.java file

// Array of strings...

String[] mobileArray = {"Android","IPhone","WindowsMobile","Blackberry"};

ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.activity_listview,


mobileArray);

ListView listView = (ListView) findViewById(R.id.mobile_list);


listView.setAdapter(adapter);

• Spinner: Spinner allows you to select an item from a drop down menu To create Spinner

make following changes in res/layout/activity_main.xml file

<Spinner android:id="@+id/spinner"
android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:prompt="@string/spinner_title"/>
To access the value of Spinner make following changes in MainActivity.java file

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

Spinner spinner = (Spinner) findViewById(R.id.spinner);

spinner.setOnItemSelectedListener(this); // Spinner click listener

List<String> categories = new ArrayList<String>();

categories.add("Automobile");

categories.add("Computers");

categories.add("Education");

categories.add("Personal");

// Creating adapter for spinner

ArrayAdapter<String> dataAdapter = new ArrayAdapter<String> (this,

android.R.layout.simple_spinner_item, categories);

// Drop down layout style - list view with radio button

dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

spinner.setAdapter(dataAdapter); // attaching data adapter to spinner

43
@Override

public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

// On selecting a spinner item

String item = parent.getItemAtPosition(position).toString();

// Showing selected spinner item

Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();

46

public void onNothingSelected(AdapterView<?> arg0) {

// TODO Auto-generated method stub

ListFragment:

A list fragment is a fragment that contains a ListView, displaying a list of items from a data
source such as an array or a Cursor

Steps to create ListFragment


Step 1: Create fragment in res/layout/activity_main.xml file

<fragment

44
android:id="@+id/fragment1"
android:name="com.example.admin.ListFragmentExample.MainActivity"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Step 2: Create fragment1.xml in res/layout folder and add below code in fragment1.xml

<?xml version="1.0" encoding="utf


-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:gravity="center"

android:padding="10dp"

android:orientation="vertical">

<ListView android:id="@id/android:list"

android:layout_width="match_parent"
package com.example.admin.ListFragmentExample;

import android.app.ListFragment; import

android.os.Bundle; import

android.view.LayoutInflater; import android.

view.View; import android. view.ViewGroup; import

android.widget.ArrayAdapter; import android.

widget.ListView; import android. widget.Toast;

public class MainActivity extends ListFragment {

String[ ] CountryNames = { ―India‖, ―Nepal‖, ―South Africa‖,


―Shri Lanka‖};

45
public View onCreateView(LayoutInflater inflater, ViewGroup
container, Bundle savedInstanceState) {

return inflater.inflate(R.layout.fragment1,container,false);

}
android:layout_height="match_parent"
public void onCreate(Bundle savedInstanceState) {
android:layout_weight="1"
super.onCreate(savedInstanceState);
android:drawSelectorOnTop="false" />
setListAdapter(new ArrayAdapter<String>(getActivity(),
<android.R.layout.simple_list_item_1,
/LinearLayout> CountryNames) );

}
Step 3: Create a Java Class file and name it MainActivity.

46
Toast.LENGTH_SHORT).show( );

1. DialogFragment: A DialogFragment is a fragment that displays a modal window, floating


on top of the current activity window. Android provides several standard dialog
implementation AlertDialog, ProgressDialog, DatePickerDialog or TimePickerDialog

Steps to create dialog fragment


Step 1: Create a new class which extends DialogFragment and override the
onCreateView() method to create dialog fragment

public class MyDialogFragment extends DialogFragment {

@Override

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle


savedInstanceState) {

View view = inflater.inflate(R.layout.fragment_sample_dialog, container, false);

getDialog().setTitle("Test Dialog"); return view;

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
Step 2: Define DialogFragment Layout as given below:

47
android:gravity="center"

android:padding="10dp"

android:orientation="vertical"> <TextView

android:id="@+id/title"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Test"

android:textSize="20dp" /> <Button

android:id="@+id/dismiss"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="Dismiss" />

</LinearLayout>
Step 3: To display the DialogFragment, Add below code into MyDialogFragment.java
onCreateView() method.

FragmentManager fm = getFragmentManager();

MyDialogFragment dialogFragment = new MyDialogFragment ();


dialogFragment.show(fm, "Sample Fragment");

Button dismiss = (Button) rootView.findViewById(R.id.dismiss);

dismiss.setOnClickListener(new View.OnClickListener() {

@Override public void


onClick(View v) {
Step 4: To dismiss DialogFragment, Add below code into MyDialogFragment.java
onCreateView() method.

dismiss();

});

48
2. PreferenceFragment: Allow users to personalize the application for their own use.
Steps to create PreferenceFragment
Step 1: Create a new xml folder under res folder and then add a new Android XML file to
it. Name the xml file preferences.xml

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

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

<PreferenceCategory android:title="Category 1">

<CheckBoxPreference android:title="CheckBox"

android:defaultValue="false"

android:summary="True or Flase"

android:key="checkboxPref" />

</PreferenceCategory>
package com.example.admin.PreferenceFragmentExample;
<PreferenceCategory android:title="Category 2">
import android.os.Bundle; import
<EditTextPreference android:name="EditText"
android.preference.PreferenceFragment; public class
android:title="Edit Text"
Fragment1 extends PreferenceFragment {
android:key="editTextPref" />

public void onCreate(Bundle savedInstanceState) {


<RingtonePreference android:name="Ringtone Preference"
super.onCreate(savedInstanceState);
android:summary="Select a ringtone"
addPreferencesFromResource(R.xml.preferences);
android:title="Ringtones"
android:key="ringtonePref"
} />
Step 2: Populate the preferences.xml file as follows:
}

import android.app.FragmentManager; import

android.app.FragmentTransaction;

49
FragmentManager fragmentManager = getFragmentManager();

FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

SET A
1. Create a custom "Contact" layout to hold multiple pieces of information, including: Photo,
Name, Contact Number, E-mail id.
2. By using Spinner, Buttons. Write a program to draw following GUI

4 Create application to demonstrate date and time picker.

SET B
1. Create application to demonstrate file explorer (Use ListView).
50
2. Create registration form given below. Also perform appropriate validation and display the
message using dialog fragment.

SET C
 Create application to demonstrate alarm.

Assignment Evaluation

a. 0: Not Done [ ] 1: Incomplete [] 2: Late Complete []


b. 3: Needs Improvement [] 4: Complete [] 5: Well-done []

51
Assignment No. 5 No. of Sessions: 02

Name Displaying Pictures and Menus

Android Gallery and ImageView to View:

In your application if you want display a series of images to the user, you can make use of the
Gallery. The Gallery is a view that shows items (such as images) in a center-locked, horizontal
scrolling list.

How to Create Android Gallery and ImageView:

• Gallery is used to show Views in a horizontal list, and user will select a view , User
selected view will be shown in center of the Horizontal list.

• The items of Gallery are getting from an Adapter, just like ListView, in which ListView
items are getting from an Adapter.

• We need to make an Adapter class that extends BaseAdapter class and override
getView() method.

Example:
1. Using the Gallery View
1. For Android Gallery View Example, assume you have some images stored in the
res/drawable-mdpi folder of your project.

2. Create an XML file named attrs.xml and store it in the res/values folder.
52
3. Add this content to the attrs.xml file:

<resources>
<declare-styleable name="MyGallery">
<attr name="android:galleryItemBackground" />
</declare-styleable>
</resources>

Open ―res/layout/activity_main.xml‖ file and put this xml code it into file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="{relativePackage}.${activityClass}"
android:orientation="vertical" >
<Gallery android:id="@+id/gallery1"

android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<ImageView android:id="@+id/image1"
android:layout_width="215dp"

android:layout_height="315dp"
android:layout_gravity="center_horizontal"
android:background="#cfcfcf"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:src="@drawable/pic1" />
</LinearLayout>
Open ―src/package-name/MainActivity.java‖ file and add following JAVA code.

import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;

53
import android.widget.ImageView;
import android.widget.Toast
public class MainActivity extends Activity {
//the images to display
Integer[] imageIDs = { R.drawable.pic1, R.drawable.pic2, R.drawable.pic3,
R.drawable.pic4, R.drawable.pic5, R.drawable.pic6,
R.drawable.pic7
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Note that Gallery view is deprecated in Android 4.1---
Gallery gallery = (Gallery) findViewById(R.id.gallery1);
gallery.setAdapter(new ImageAdapter(this));
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position,long id)
{
Toast.makeText(getBaseContext(),"pic" + (position + 1) + " selected",
Toast.LENGTH_SHORT).show();
// display the images selected
ImageView imageView = (ImageView) findViewById (R.id.image1);
imageView.setImageResource(imageIDs[position]);
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context context;
private int itemBackground;
public ImageAdapter(Context c)

context = c;
// sets a grey background; wraps around the images
TypedArray a =obtainStyledAttributes(R.styleable.MyGallery);
itemBackground =
a.getResourceId(R.styleable.MyGallery_android_galleryItemBackground, 0);
a.recycle();
}
public int getCount() {
54
return imageIDs.length; // returns the number of images
}
public Object getItem(int position) {
return position; // returns the ID of an item
}
public long getItemId(int position) {
return position;
}
// returns an ImageView view
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(context);
imageView.setImageResource(imageIDs[position]);
imageView.setLayoutParams(new Gallery.LayoutParams(100, 100));
imageView.setBackgroundResource(itemBackground);
return imageView;
}
}
}
. The following Try It Out shows you how to use the Gallery view to display a set of images
 Using Android Studio, create a new Android project and name it Gallery
.  Add the following code in the main.xmlfile
<Gallery android:id=”@+id/gallery1”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content” />
<ImageView android:id=”@+id/image1”
android:layout_width=”320dp”
android:layout_height=”250dp”
android:scaleType=”fitXY” />
 Right-click on the res/valuesfolder and select New File. Name the file as attrs.xml.
 Populate the attrs.xmlfile as follows:
<?xml version=‖1.0‖ encoding=‖utf-8‖?>
<resources>
<declare-styleable name=‖Gallery1‖>
<attr name=‖android:galleryItemBackground‖ />
</declare-styleable>
</resources>
 Prepare a series of images and name them pic1.png, pic2.png, and so on for each
subsequent image. Drag and drop all the images into the res/drawable-mdpi folder.
When a dialog is displayed, check the Copy files option and click OK.
 Add the following statements into the GalleryActivity.java file
package net.learn2develop.Gallery;

55
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
importandroid.view.ViewGroup;
import android.widget.AdapterView;
60
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
public class GalleryActivity extends Activity{
//---theimagestodisplay---
Integer[] imageIDs ={ R.drawable.pic1, R.drawable.pic2, R.drawable.pic3,
R.drawable.pic4, R.drawable.pic5, R.drawable.pic6,
R.drawable.pic7 };
/**Calledwhentheactivityisfirstcreated.*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Gallery gallery= (Gallery)findViewById(R.id.gallery1);
gallery.setAdapter(new ImageAdapter(this));
gallery.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView parent, View v, int position, longid)
{
Toast.makeText(getBaseContext(), ―pic‖+(position+1)+
―selected‖, Toast.LENGTH_SHORT).show();
}
});
}
public class ImageAdapter extendsBaseAdapter {
Context context;
int itemBackground;
public ImageAdapter(Context c) {
61
context = c;
//---setting the style---
TypedArray a = obtainStyledAttributes( R.styleable.Gallery1);
itemBackground = a.getResourceId(
R.styleable.Gallery1_android_galleryItemBackground, 0);
a.recycle();
56
}
public int getCount(){
return imageIDs.length; // returnsthenumberofimages
}
publicObjectgetItem(int position){
return position; // returns the item
}
public long getItemId(int position){
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
imageView.setImageResource(imageIDs[position]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(150, 120));
} else {
imageView = (ImageView) convertView;
}
imageView.setBackgroundResource(itemBackground);
return imageView;
}
}
}

 Press F11 to debug the application on the Android emulator.


 To display the selected image in the ImageView, add the following statements in
bold to the GalleryActivity.javafile
 Image Switcher
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/imageSwitcher1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" >
</ImageSwitcher>
Now we create an instance of ImageSwithcer in java file and get a reference of this XML
component. Its sytnax is given below:
private ImageSwitcher imageSwitcher; imageSwitcher =
(ImageSwitcher)findViewById(R.id.imageSwitcher1

57
The next thing we need to do is implement the ViewFactory interface and implement
unimplemented method that returns an imageView. Its syntax is below:
imageSwitcher.setImageResource(R.drawable.ic_launcher);
imageSwitcher.setFactory(new ViewFactory() {
public View makeView() {
ImageView myView = new ImageView(getApplicationContext());

return myView;
}
}
The last thing you need to do is to add Animation to the ImageSwitcher. You need to define an
object of Animation class through AnimationUtilities class by calling a static method
loadAnimation. Its syntax is given below:
Animation in = AnimationUtils.loadAnimation(this,android.R.anim.slide_in_left);
imageSwitcher.setInAnimation(in);
imageSwitcher.setOutAnimation(out);

The method setInAnimaton sets the animation of the appearance of the object on the screen
whereas setOutAnimation does the opposite. The method loadAnimation() creates an animation
object. Apart from these methods, there are other methods defined in the ImageSwitcher class.
They are defined below.

They are defined below:


Public Methods Description
setImageDrawable(Drawable drawable) Sets an image with image switcher. The
image is passed in the form of bitmap.

setImageResource(int resid) Sets an image with image switcher. The


image is passed in the form of integer id.

setImageURI(Uri uri) Sets an image with image switcher. The


image is passed in the form of URI.

ImageSwitcher(Context context, AttributeSet attrs) Returns an image switcher object with


already setting some attributes passed in the
method.

Example:

58
import android.view.animation.AnimationUtils;

import android.widget.AdapterView;

import android.widget.AdapterView.OnItemClickListener;
1. Using the ImageSwitcher View

We want
import to apply some animation toimport
android.widget.BaseAdapter; the image when it transitions from one image to another. In
android.widget.Gallery;
this case, you need to use the ImageSwitcher together with the Gallery view.
import android.widget.ImageSwitcher; import android.widget.ImageView; import
The following Try It Out shows you how.
android.widget.ViewSwitcher.ViewFactory; public class ImageSwitcherActivity
1) Using Andriod, create a new Android project and name it ImageSwitcher 2)
Modify
extends the main.xml
Activity file ViewFactory
implements by adding the{following statements:

<Gallery android:id=‖@+id/gallery1‖
//---theimages to display---
android:layout_width=‖fill_parent‖
android:layout_height=‖wrap_content‖
Integer[] imageIDs = { R.drawable.pic1, />R.drawable.pic2,
<ImageSwitcher android:id=‖@+id/switcher1‖
android:layout_width=‖fill_parent‖ R.drawable.pic3, R.drawable.pic4,
android:layout_height=‖fill_parent‖
android:layout_alignParentLeft=‖true‖ R.drawable.pic5, R.drawable.pic6, R.drawable.pic7 };
android:layout_alignParentRight=‖true‖
private ImageSwitcher imageSwitcher;
android:layout_alignParentBottom=‖true‖ />
3) Right-click on the res/values folder and select New, File. Name the file attrs.xml.
public void onCreate(Bundle savedInstanceState)
4) Populate the attrs.xml file as follows:
{ imageSwitcher = (ImageSwitcher) findViewById(R.id.switcher1);
<?xml version=‖1.0‖ encoding=‖utf-8‖?>
imageSwitcher.setFactory(this);
<resources>
<declare-styleable name=‖Gallery1‖>
imageSwitcher.setInAnimation(AnimationUtils.loadAnimation
(this,android.R.anim.fade_in));
<attr name=‖android:galleryItemBackground‖ />
imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation
</declare-styleable>
</resources>
(this,android.R.anim.fade_out));
5) Drag and drop a series of images into the res/drawable-mdpi folder. When a dialog is
Gallery
displayed, check gallery
the Copy = option
files (Gallery)
andfindViewById(R.id.gallery1);
click OK.
gallery.setAdapter(new ImageAdapter(this));
6) Add the following statements to the ImageSwitcherActivity.java file:
gallery.setOnItemClickListener(new OnItemClickListener(){

public void onItemClick(AdapterView<?> parent, View v, int


position, long id) {
imageSwitcher.setFactory(this);
imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_in));
imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_out)); 59
Gallery gallery = (Gallery) findViewById(R.id.gallery1);
gallery.setAdapter(new ImageAdapter(this));
gallery.setOnItemClickListener(new OnItemClickListener() {
public voidonItemClick(AdapterView<?> parent, View v, int position, long id) {
imageSwitcher.setImageResource(imageIDs[position]);
import android.content.Context;
import android.content.res.TypedArray;
import
android.view.View; import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;

60
Attribute Name Description
android:id This is the ID which uniquely identifies the layout.

package com.example.helloworld;

import android.os.Bundle; import

android.app.Activity; import

android.view.Menu; import

android.widget.GridView; public

class MainActivity extends Activity

@Override protected void onCreate(Bundle

savedInstanceState)

{ super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

GridView gridview = (GridView) findViewById(R.id.gridview);

gridview.setAdapter(new ImageAdapter(this));

 Following will be the content of res/layout/activity_main.xml file.


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

61
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center" />

 Following will be the content of res/values/strings.xml to define two new constants


<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">HelloWorld</string>
<string name="action_settings">Settings</string>
</resources>
 Following will be the content of src/com.example.helloworld/ImageAdapter.java file.

import android.widget.ImageView;
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
}
else {
imageView = (ImageView) convertView;
}
62
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
public Integer[] mThumbIds = { R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
72
R.drawable.sample_6, R.drawable.sample_7,
R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7 };
}

 Let's try to run our modified Hello World! Application we just modified.
 Using Menus with Views Menus are useful for displaying additional options that are not
directly visible on the main UI of an application. There are two main types of menus in
Android:
 Options menu — Displays information related to the current activity. In Android, you
activate the options menu by pressing the MENU key.
 Context menu — Displays information related to a particular view on an activity. In
Android, to activate a context menu you tap and hold on to it.
 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, while the other handles the
event that
i fired when the user selects an item inside the menu.
Example:
1. Creating the Menu Helper Methods:--
a. Add the following statements in the MainActivity.java fil
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.Toast;
private void CreateMenu(Menu menu) {
MenuItem mnu1 = menu.add(0, 0, 0, ―Item 1‖);
{
73
mnu1.setAlphabeticShortcut(‗a‘);
mnu1.setIcon(R.drawable.icon);
}
MenuItem mnu2 = menu.add(0, 1, 1, ―Item 2‖);
{
mnu2.setAlphabeticShortcut(‗b‘);
mnu2.setIcon(R.drawable.icon);
63
}
menu.add(0, 2, 2, ―Item 3‖);
}
private boolean MenuChoice(MenuItem item)
{
switch (item.getItemId()) {
case 0: Toast.makeText(this, ―You clicked on Item 1‖,
Toast.LENGTH_LONG).show();
return true;
case 1: Toast.makeText(this, ―You clicked on Item 2‖,
Toast.LENGTH_LONG).show();
return true;
case 2: Toast.makeText(this, ―You clicked on Item 3‖,
Toast.LENGTH_LONG).show();
return true;
}
return false;
}

 Options Menu You are now ready to modify the application to display the options menu
when the user presses the MENU button on the Android device
 Displaying an Options Menu 1. Using the same project created in the previous section,
add the following statements into the MainActivity.java file
@Override public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
CreateMenu(menu); return true; }
@Override public boolean onOptionsItemSelected(MenuItem item)
{ return MenuChoice(item); }

2. Press F11 to debug the application on the Android Emulator.


 Context Menu A context menu is usually associated with a view on an activity, and it is
displayed when the user long clicks an item. For example, if the user taps on a Button
view and hold it for a few seconds, a context menu can be displayed.
Exmple:
 Displaying a Context Menu 1. using the same project created in the previous section, add
the following statements in the MainActivity.java file
import android.view.View;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
public void onCreate(Bundle savedInstanceState) {
Button btn = (Button) findViewById(R.id.btn1);
btn.setOnCreateContextMenuListener(this);
}
75

64
@Override
public void onCreateContextMenu(ContextMenu menu, View view,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
CreateMenu(menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
return MenuChoice(item);
}

SET A
1. Construct an app that toggles a light bulb on and off when the user clicks on toggle
button.
2. Construct an app to display the image on date wise.
3. Create a custom launcher icon
SET B
1. Construct image switcher using setFactory().
2. Construct a bank app to display different menu like windrow, deposite etc.
SET C
1. Construct App which shows Slides of multiple images after click on Slide menu

Assignment Evaluation

a. 0: Not Done [ ] 1: Incomplete [] 2: Late Complete []


b. 3: Needs Improvement [] 4: Complete [] 5: Well-done []

65
Assignment No. 6 No. of Sessions: 02
Assignment Name : Databases – SQLite

SQLite is an open source SQL database that stores data to a text file on a device. Android
comes in with built in SQLite database implementation. SQLite supports all the relational
database features. In order to access this database, you don't need to establish any kind of
connections for it like ODBC

 SQLiteOpenHelper
Android database sqlite.SQLiteOpenHelper manages database creation, up gradation,
down gradation, version management and opening it. We need to create sub class of
SQLiteOpenHelper and override onCreate and onUpgrade and optionally onOpen. If
database is
not created, onCreate is called where we write script for database creation. If already
created, then onOpen is called which opens database

Constructors Description
SQLiteOpenHelper(Context context, String name, Create a helper object to create, open,
SQLiteDatabase.CursorFactory factory, int version) and/or manage a database

SQLiteOpenHelper(Context context, String name, Create a helper object to create, open,


SQLiteDatabase.CursorFactory factory, int version, and/or manage a database.

DatabaseErrorHandler errorHandler)

66
Public Methods Description
void close() Close any open database object.
String getDatabaseName() Return the name of the SQLite database being
opened, as given to the constructor.

SQLiteDatabase getReadableDatabase() Create and/or open a database.


SQLiteDatabase getWritableDatabase() Create and/or open a database that will be used
for reading and writing.

void onConfigure(SQLiteDatabase db) Called when the database connection is being


configured, to enable features such as
writeahead logging or foreign key support.

abstract void onCreate(SQLiteDatabase db) Called when the database is created for the first
time.

void onDowngrade(SQLiteDatabase db, int Called when the database needs to be


oldVersion, int newVersion) downgraded.

void onOpen(SQLiteDatabase db) Called when the database has been opened.
void setIdleConnectionTimeout(long Sets the maximum number of milliseconds that
idleConnectionTimeoutMs) SQLite connection is allowed to be idle before it
is closed and removed from the pool.

public synchronized void close () Closes the database object.


public class DBHelper extends SQLiteOpenHelper{
public DBHelper(){
super(context,DATABASE_NAME,null,1);
}
public void onCreate(SQLiteDatabase db){
// Creates new database
// Create the tables
// execute query with the help of execSQL();
// Add initial data
………..
}
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){
}
}
 SQLite Database: The main package is android.database.sqlite that contains the classes

67
to manage your own databases:
1. Database – Creation
In a database you just need to call this method openOrCreateDatabase with your
database name and mode as a parameter. Its syntax is given below:
SQLiteDatabase mydatabase = openOrCreateDatabase("Database
name",MODE_PRIVATE,null);

Public Methods Description


openDatabase(String path, This method only opens the existing database
SQLiteDatabase.CursorFactory factory, int flags, with the appropriate flag mode.

DatabaseErrorHandler errorHandler)
openDatabase(String path, It is similar to the above method but it does
SQLiteDatabase.CursorFactory factory, int flags) not define any handler to handle the errors
of databases

openOrDatabase(String path, It not only opens but creates the database if


SQLiteDatabase.CursorFactory factory) it not exists. This method is equivalent to
openDatabase method.

2. Database – Insertion We can create table or insert data into table using execSQL
method defined in SQLiteDatabase class. Its syntax is given below Example
mydb.execSQL(―CREATE TABLE IF NOT EXISTS Login(Username
varchar,Password
Varchar)”);
mydb.execSQL(―INSERT INTO Login VALUES(‗admin‘,‘admin‘);)
Another method that also does the same job but take some additional parameter is given
below. execSQL(String sql, Object[] bindArgs):
This method not only inserts data, but also used to update or modify already existing data
in database using bind arguments.
3. Database – Fetching We can retrieve anything from database using an object of the
Cursor class. We will call a method of this class called rawQuery and it will return a
resultset with the cursor pointing to the table. We can move the cursor forward and retrieve
the data.
Cursor resultSet=mydb.rawQuery(―Select * from Login‖,null);
68
resultSet.moveToFirst();
String username= resultSet.getString(0);
String password= resultSet.getString(1);
Insert Format: long insert (String table, String nullColumnHack, ContentValues values)
 First argument is the table name.
 Second argument is a String nullColumnHack
o Workaround that allows you to insert empty rows
o Use null
 Third argument must be a ContentValues with values for the row.
 Returns the id of the newly inserted item.
Example:
newId = mWritableDB.insert( TABLE_NAME, null, values);
Delete Format:
int delete (String table, String whereClause, String[] whereArgs)
 First argument is table name
 Second argument is WHERE clause
 Third argument are arguments to WHERE clause
Example:
deleted = mWritableDB.delete( WORD_LIST_TABLE, KEY_ID + " =? ", new String[] {
String.valueOf(id) } );
Update Format:
int update(String table, ContentValues values, String whereClause, String[] whereArgs)
 First argument is table name
 Second argument must be ContentValues with new values for the row
 Third argument is WHERE clause.
 Fourth argument are the arguments to the WHERE clause
ContentValues values = new ContentValues();
values.put(KEY_WORD, word);
mNumberOfRowsUpdated = mWritableDB.update( WORD_LIST_TABLE, values, // new
values to
insert KEY_ID + " = ?", new String[]{String.valueOf(id)});

69
SET A
1. Create table Company (id, name, address, phno). Create Application for Performing the
following operation on the table.
i) Insert New Company Details.
ii) Show All the Company Details.
2. Create table Student (sno , s_name,s_class,s_addr)
Teacher (tno, t_name, qualification, experience)
Student-Teacher has many to many relationship.
Using above database Write Application to accept a teacher name from user and display
the names of students along with subjects to whom teacher is teaching.
3. Create Following Table:
Emp (emp_no,emp_name,address,phone,salary)
Dept (dept_no,dept_name,location)
Emp-Dept is related with one-many relationship.
Create application for performing the following Operation on the table
1) Add Records into Emp and Dept table.
2) Accept Department name from User and delete employee information which belongs
to that department.
SET B
1. Create sample application with login module (Check username and password). On
successful
login, pass username to next screen And on failing login, alert user using Toast (Hint :Use
Login(username, password) Table.)
1.

70
2. Create Table project (pno, p_name, ptype, duration) and employee (id, e_name,
qulification, joindate)
Project – employee have many to many relationship.
Using database perform following operation.
1) Add new record into table.
2) Accept a project name from user and display information of employees
working on the project.
SET C
1) Create simple application shown below. Create table Student(Sid ,Sname ,phno).
Use autoincrement for Sid and Perform following Operation.
a. Add Student and display its information.
b. Delete Student.

Assignment Evaluation

a. 0: Not Done [ ] 1: Incomplete [] 2: Late Complete []


b. 3: Needs Improvement [] 4: Complete [] 5: Well-done []

71
Assignment No. 7 No. of Sessions: 02
Assignment Name : Messaging and E-mail

 Sending SMS messages


SMS messages can be send using SmsManager Class or Built-in SMS application
1. Using SmsManager class: Using the SmsManager class, you can send SMS messages
from within your application without the need to involve the built-in Messaging application.
Steps to send SMS 1. Create a new Android project and name it SMS
2. Replace the TextView with the following statements in the main.xml file:
<Button android:id=”@+id/btnSendSMS”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Send SMs”
android:onClick=”onClick” />

3. In the AndroidManifest.xml fi le, add the following statements:


<uses-permission android:name=”android.permission.SEND_SMS”>

4. Add the following statements to the SMSActivity.java file:


import android.telephony.SmsManager;
import android.view.View;
public void onClick(View v) {
sendSMS(―5556‖, ―Hello my friends!‖);
}
//---sends an SMS message to another device--
private void sendSMS(String phoneNumber, String message) {
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
}
4. Debug the application on Android Emulator. 6. Click Send SMS button on first
Android Emulator and see the message on second Emulator (5556).
Methods of SmsManager Class

72
Public Methods Description
ArrayList divideMessage(String text) This method divides a message text into
several fragments, none bigger than the
maximum SMS message size.
static SmsManager getDefault() This method is used to get the default
instance of the SmsManager
void sendDataMessage (String destAddress This method is used to send a data based
, String scAddress, short destinationPort, SMS to a specific application port
byte[]data, PendingIntent sentIntent,
PendingIntent deliveryIntent)
void sendMultipartTextMessage (String Send a multi-part text based SMS.
destAddress, String scAddress, ArrayList
parts, ArrayList sentIntents, ArrayList
deliveryIntents) void
sendMultipartTextMessage (String
destAddress, String scAddress, ArrayList
parts, ArrayList sentIntents, ArrayList
deliveryIntents)
void sendTextMessage(String Send a text based SMS
destinationAddress, String scAddress,
String text, PendingIntent sentIntent,
PendingIntent deliveryIntent)

2. Sending SMS messages using Intent: We can also use built-in messaging application to
send
the message.
Steps to send SMS
1) Create an Intent Object (Action to send SMS)
ACTION_VIEW action is used to launch an SMS client installed on your Android device.

Intent smsIntent = new Intent(Intent.ACTION_VIEW)

2)Using Intent Object set Data/Type to send SMS smsto: is used as a URI to send message
using setData() method. data type is set to vnd.android-dir/mms-sms using setType()
method.
smsIntent.setData(Uri.parse("smsto:"));

73
smsIntent.setType("vnd.android-dir/mms-sms")
3)Intent Object used to set a message for one or more phone number with putExtra( )
method and a message can be send to multiple receivers separated by ‗:‘.
smsIntent.putExtra(―address‖,new String(―0123456789;3398765587‖)); OR
smsInent.putExtra(―address‖,‖5556 ; 5553 ; 5566‖)
3. Getting Feedback after Sending a Message: To check the status of the SMS message
sending process, two objects of PendingIntent are created. These objects are passed as
last two arguments of the sendTextMessage() method //---sends an SMS message to
another device---
SET A
1. Create application to send and receive messages using SMSManager.
2. Create application to send email.
3. Create application to send message. After sending message display delivery
report of
message.
SET B
1. Create application to design login form, validate it. Write and send email with
appropriate message.
2. Create application to send SMS with image and contact as attachment.

Assignment No. 8 No. of Sessions: 02


Assignment Name : : Location-Based Services and Google Map

SET C
1. Create application to send email with attachment

Location based services: ―


Location-based services‖ is used to create an application which uses
current location, location updates, and location information. The two main LBS elements are:
 Location Manager
74
These services allow applications to obtain periodic updates of the
device's geographical location.
 Location Providers —
provides periodic reports on the geographical location of the device.
Google Map: Google Maps is web based service developed by Google. It provides many
facilities such as Satellite view, Street view, real time traffic condition, and navigations for
travelling by foot, car, bicycle and public transportation. To use Google Maps in your
Android
applications programmatically.
Google API (Application Programming Interface)
Steps to create Google Map Application Step 1
: Start Android Studio Step 2: Install the Google Play Services SDK.
 Click Tools in the Android Studio menu bar, then Android, SDK Manager.
 Click SDK Tools, and if Google Play Services is not installed, install Google Play Services
. Step 3: Create a Google Maps Project 1. Create a new project as follows: a. If you see the
Welcome to Android Studio dialog, choose Start a new Android Studio project, available
under 'Quick Start' on the right of the dialog. b. Otherwise, click File in the Android Studio
menu bar, then New, New Project. 2. Enter your app name, company domain, and project
location, as prompted. Then click Next. 3. Select the form factors you need for your app. If
you're not sure what you need, just select Phone and Tablet. Then click
Next. 4. Select Google Maps Activity in the 'Add an activity to Mobile' dialog. Then click
Next. 5. Enter the activity name, layout name and title as prompted. The default values are
fine. Then click Finish. Step 4: Get Google Maps API Key
 Use the link provided in the google_maps_api.xml file.
 Copy the link provided in the google_maps_api.xml file and pastes it into your browser.
The link takes you to the Google API Console and supplies the required information to the
Google API Console via URL parameters.
 Follow the instructions to create a new project on the Google API Console or select an
existing project.
 Create an Android-restricted API key for your project.
 Copy the resulting API key, go back to Android Studio, and paste the API key into the
element in the google_maps_api.xml file.
Step 5: Examine the code supplied by the template.
Step 6: Build an APK file - Click Build in the Android Studio menu bar, then Build APK.
Step 7: install APK file on real device and open the application.
 Displaying the Map
 Classes and Interface used for displaying Map are given below:
 Interfaces:
 Package Name: com.google.android.gms.maps
OnMapReadyCallback – This interface is used to execute method when Map is ready.

Public Method Description


75
This method execute automatically
abstract void onMapReady (GoogleMap googleMap) when map is ready

GoogleMap: This is the main class of the Google Maps Android API. You cannot instantiate
a
GoogleMap object directly, rather, you must obtain one from the getMapAsync() method on
MapFragment. This class provides methods to set type of map, add markers, add polyline or
move camera etc
76
Public Method Description
Circle addCircle(CircleOptions options) Used to add a circle on the map.
Marker addMarker(MarkerOptions options) Used to add a marker on the map.
Polyline addPolyline (PolylineOptions options) Used to add a polyline on the map.
void animateCamera(CameraUpdate update) Animates the movement of the camera from
the current position to the position defined in
the update.

void clear() Removes all circles, markers, polylines,


polygons, overlays from the map.

CameraPosition getCameraPosition() Returns the current position of the camera on


the map.

int getMapType() Returns the type of map.


UiSettings getUiSettings() Returns the user interface settings for the map.
void moveCamera(CameraUpdate update) Used to move the camera to the position
specified by update.

void setMapType(int type) Sets the type of map.


void setMyLocationEnabled (boolean enabled) Enables or disables the my-location layer.
Constants Description
MAP_TYPE_HYBRID Satellite maps with a transparent layer of
major streets.
MAP_TYPE_NONE No base map tiles
MAP_TYPE_NORMAL Basic maps
MAP_TYPE_SATELLITE Satellite maps with no labels
Terrain maps (Topographic data)

SupportMapFragment: SupportMapFragement is used to create a map fragment.


Public Methods Description
void getMapAsync (OnMapReadyCallback This method called when map is ready.
callback)
static SupportMapFragment newInstance() Creates a map fragment, using default options.

SupportMapFragment: SupportMapFragement is used to create a map fragment.


 By default, the XML file that defines the app's layout is at res/layout/activity_maps.xml. It
contains the following code:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
77
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context= "com.example.admin.googlemapdemo.MapsActivity" />

The MapsActivity Java file


import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {

mMap = googleMap;
}
}

Changing Views: Google Maps is displayed in map view, which basically drawings of streets
and places of interest.
To display the satellite view add following line in onMapReady() method in the
MapsActivity.java file
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);

Getting Location Data: To know the information of a location we need to find latitude
and longitude values corresponding to the position. Converting location name to
respective latitude and longitude values is called as geocoding. To do the reverse
geocoding we need to use Geocoder class.
Package Name: android
Manifest.permission: It is static nested class of Manifest. It contains the constants to add user
permission or security settings in android application
78
Constants Description
String ACCESS_FINE_LOCATION Used to access precise location.
String ACCESS_COARSE_LOCATION Used to access approximate location.
String ACCESS_NETWORK_STATE Used to access the state of the network.
String ACCESS_WIFI_STATE Used to access the state of Wi-Fi.
String CHANGE_NETWORK_STATE Used to change network connectivity state.
String INTERNET Used to open network sockets.
String WRITE_EXTERNAL_STORAGE Allows an application to write to external storage.

Add below line in the manifests/AndroidManifest.xml file to add permission


<uses-permission android:name= "android.permission.ACCESS_FINE_LOCATION" />

Package Name:
com.google.android.gms.maps CameraUpdateFactory: This class is used to create
CameraUpdate objects that change or move a map's camera. It also provides the functionality
such as Zoom In, Zoom Out and Zoom By specific amount.
Public Methods Description
Returns a CameraUpdate that moves the camera
static CameraUpdate newCameraPosition to a specified CameraPosition.

(CameraPosition cameraPosition)
static CameraUpdate newLatLng(LatLng Returns a CameraUpdate that moves the center
latLng) of the screen to a latitude and longitude specified
by a LatLng object.

static CameraUpdate Returns a CameraUpdate that moves the center


newLatLngZoom(LatLng latLng, float zoom) of the screen to a latitude and longitude specified
by a LatLng object, and moves to the given
zoom level.

static CameraUpdate zoomIn() Returns a CameraUpdate that zooms in on the


map.

Returns a CameraUpdate that zooms out on the


static CameraUpdate zoomOut() map.

Package Name: com.google.android.gms.maps.model LatLng – This class represents a pair of


latitude and longitude coordinates.

79
Constructor Description
LatLng(double latitude, double longitude) Constructs a LatLng with the given latitude
and longitude, measured in degrees.

Fields Description
public final double latitude Latitude, in degrees.
public final double longitude Longitude, in degrees.

Marker: This class is used to mark particular point on Map. This class contains methods to set
opacity, title, rotation, position, or visibility of marker.

Properties Description
Alpha Sets the opacity of the marker. Defaults to 1.0.
Position The LatLng value for the marker's position on the map.
Title Sets the title and display when the user taps the marker.
Icon An image or logo that's displayed for the marker.
Visibility Set visibility of marker. By default, the marker is visible.
Rotation The rotation of the marker in degrees clockwise about the marker's anchor
point.

zIndex The draw order for the marker. The default value is 0.

80
Methods Description
float getAlpha() Returns the alpha of the marker.
String getId() Returns the marker's id.
LatLng getPosition() Returns the position of the marker.
float getRotation() Return the rotation of the marker.
String getTitle() Return the title of the marker.
float getZIndex() Returns the zIndex of the marker.
void setPosition(LatLng latlng) Sets the location of the marker.
void remove() Removes this marker from the map.
void setAlpha(float alpha) Sets the alpha (opacity) of the marker.
void setTitle(String title) Sets the title of the marker.
void setIcon(BitmapDescriptor iconDescriptor) Sets the icon for the marker.
void setRotation(float rotation) Sets the rotation of the marker in degrees
clockwise about the marker's anchor point.

MarkerOptions: This class defines different options available for a marker.

Constructor Description
MarkerOptions() Creates a new set of marker options.

Public Methods Description


MarkerOptions icon(BitmapDescriptor Sets the icon for the marker.
iconDescriptor)

MarkerOptions position(LatLng latlng) Sets the location for the marker.


MarkerOptions rotation(float rotation) Sets the rotation of the marker in degrees
clockwise about the marker's anchor point.

MarkerOptions title(String title) Sets the title for the marker.


MarkerOptions visible(boolean visible) Sets the visibility for the marker.

Address:
A class representing an Address. An address contains methods to find the information such
as Country name, Postal Code, locality etc.
Constructors Description

81
Criteria() Constructs a new Criteria object.
Criteria(Criteria criteria) Constructs a new Criteria object that is a copy of the given criteria.

Public Methods Description


int getAccuracy() Returns accuracy of location.
Returns a constant indicating the desired speed accuracy.
int getSpeedAccuracy()

Address:
A class representing an Address. An address contains methods to find the information such as
Country name, Postal Code, locality etc.

Constructor Description
Address(Locale locale) Constructs a new Address object set to the given Locale.
Public Methods Description
String getAddressLine(int index) Returns a line of the address numbered by
the given index, or null if no such line is
present.
String getCountryCode() Returns the country code of the address, or
null if it is unknown.

String getCountryName() Returns the localized country name of the


address, or null if it is unknown.

double getLatitude() Returns the latitude of the address.


double getLongitude() Returns the longitude of the address.
void setAddressLine(int index, Sets the line of the address numbered by
String line) index (starting at 0) to the given String.

void setCountryName(String Sets the country name of the address to the


countryName) given String, which may be null.

void setLatitude(double latitude) Sets the latitude associated with this


address.
Sets the longitude associated with this
void setLongitude(double lon 82
address.
gitude)
Geocoder:
A class for handling geocoding and reverse geocoding. Geocoding is the process of
transforming an address of a location into a (latitude, longitude) coordinates. Reverse
geocoding is the process of transforming a (latitude, longitude) coordinate into an
address

Constructors Description
Geocoder (Context context) Constructs a Geocoder whose responses will be localized for
the default system Locale.

Geocoder (Context context, Constructs a Geocoder whose responses will be localized for
Locale locale) the given Locale.

Public Methods Description


List<Address> getFromLocation(double Returns an array of Addresses that are known to
latitude, double longitude, int maxResults) describe the area the by given latitude and
longitude.

83
List<Address> Returns an array of Addresses that are known to
getFromLocationName(String locationName, describe the named location.

int maxResults)

Constants Description
String GPS_PROVIDER Name of the GPS location provider.
String NETWORK_PROVIDER Name of the network location provider.
LocationManager:
This class provides access to the system location services. These services allow applications
to obtain periodic updates of the device's geographical location.

Public Methods Description


boolean isProviderEnabled(String provider) Returns the current enabled status of the given
provider.

void requestLocationUpdates(String provider, Register for location updates using the named
provider, and a pending intent.
long minTime, float minDistance,
LocationListener listener)
String getBestProvider(Criteria criteria, Returns the name of the provider that best
boolean enabledOnly) meets the given criteria.

Location getLastKnownLocation(String Returns a Location indicating the data from the


provider) last known location obtained from the given
provider.

Example: 1. Program to display current location of android device on the Map a. Add below
line
in the manifests/AndroidManifest.xml file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
/>

b. To display the current location add following line in onMapReady() method in the
MapsActivity.java file

LatLng pune = new LatLng(18.531387, 73.849467);


84
mMap.addMarker(new MarkerOptions().position(pune).title("Pune"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(pune));
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION ) ==
PackageManager.PERMISSION_GRANTED ||
ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATIO ) ==
PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
}

2. Navigating to specific location – You can set Google Maps to display a particular location
by getting the latitude and longitude values. To display the specific location add
following line in onMapReady() method in the MapsActivity.java file
LatLng pune = new LatLng(18.531387, 73.849467); mMap.addMarker(new
MarkerOptions().position(pune).title("Pune"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(pune));

3. To display the information about the location using geocoding add following line in
onMapReady() method in the MapsActivity.java file
List<Address> addresses = null;
String locationName = "Shaniwar Wada Fort";
Geocoder geocoder = new Geocoder(this);
try {
addresses = geocoder.getFromLocationName(locationName,1);
104
} catch (IOException e) {
e.printStackTrace();
}
Address address = addresses.get(0);
LatLng shaniwar_wada= new LatLng(address.getLatitude(), address.getLongitude());
String addressline = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String postalCode = addresses.get(0).getPostalCode();
String title = addressline + "\n" + city + "\n" + state + "\n" + postalCode;
mMap.addMarker(new MarkerOptions().position(shaniwar_wada).title(title));
mMap.moveCamera(CameraUpdateFactory.newLatLng(shaniwar_wada));
Toast.makeText(getBaseContext(),title,Toast.LENGTH_LONG).show();

SET A
1. Write a program to find the specific location of an Android device and display details of
the place like Address line, city with Geocoding.

85
2. Write a program to search a specific location on Google Map.
3. Write a program to perform Zoom In, Zoom Out operation and display Satellite view,
Terrain view of current location on Google Map.
SET B
1. Write a program to calculate distance between two locations on Google Map.
2. Write a program to modify the above program to draw the path along a route on Google
Map.
SET C
1. Write a program to track an android device using mobile number and display the location
on Google Map.

Assignment Evaluation

a.0: Not Done [ ] 1: Incomplete [] 2: Late Complete []


b. 3: Needs Improvement [] 4: Complete [] 5: Well-done []

86

You might also like