Android Labbook

Download as pdf or txt
Download as pdf or txt
You are on page 1of 66

Sangamner Nagarpalik Arts, D. J. Malpani Commerce & B.

N. Sarda Science College, Sangamner


(Autonomous College) Affiliated to Savitribai Phule
Pune University

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


(CBCS 2020 Pattern)
Lab Book : Android Programming

Student Name:

College Name:

Roll No.: Division: Seat No: _

Academic Year:
Sangamner Nagarpalik Arts, D. J. Malpani Commerce & B.
N. Sarda Science College, Sangamner
(Autonomous College) Affiliated to Savitribai Phule Pune University
T. Y. B. B. A. (C. A.) Semester- VI
(CBCS 2020 Pattern)
Lab Book:- Android Programming

CERTIFICATE

This is to certify that Mr./Ms.

Seat Number of T.Y.B.B.A. (C.A) Sem-VI has


successfully completed Laboratory course (Android Programming) in the
year .

He/She has scored mark out of 10 (For Lab Book).

Subject Teacher H.O.D./Coordinator

Internal Examiner External Examiner


Assignment Completion Sheet

Sr. Assignment Name Teacher’s


No. Sign

1 Introduction to Android

2 Activity, Layout and Intent

3 Android User Interface and Event Handling

4 Android TimePicker, DatePicker, Alert Dailog

5 Android Adapter and Menu

6 Android Threads and Services

7 Android Databases – Sqlite

8 Location-Based Services and Google Maps


Assignment 1: Introduction to Android
Objectives

 Study Android Studio installation.


 Create basic android application.

Reading

You should read the following topics before starting this exercise:
1. Installing Android Studio
2. Create "Hello World" application
3. Explore the project structure
4. The Gradle build system
5. Create a virtual device (emulator)
6. Run your app on an emulator
7. Android Architecture
1. Installing Android Studio
1) Install Java JDK: Get the latest version. The JDK may be downloaded here
https://www.oracle.com/java/technologies/downloads/#java8
2) Install Android Studio bundle. Use the latest stable version. Android Studio may be downloaded here:
https://developer.android.com/studio
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 All. Scroll down and select ―Android 8.1 (API 27) Install the packages.

1
2. Create "Hello World" application
1. In the Welcome to Android Studio window, click Create New Project. (If you have a project already
opened, select File > New > New Project.)
2. In the Select a Project Template window, select Empty Activity and click Next.

3. In the Configure your project window, complete the following:


a. Enter "MyFirstApp" in the Name field.
b. Enter "com.example.myfirstapp" in the Package name field.
c. If you'd like to place the project in a different folder, change its Save location.
d. Select either Java or Kotlin from the Language drop-down menu.
e. Select the lowest version of Android you want your app to support in the Minimum SDK field.
f. Leave the other options as they are.

4. Click Finish.

2
5. After some processing time, the Android Studio main window appears.

3. Explore the project structure


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:
 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).
 com.example.hello.helloworld(androidTest): This folder is for your instrumented tests, and starts
out with a skeleton test file.
 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:
 drawable: Store all your app's images in this folder.
 layout: Every activity has at least one layout file that describes the UI in XML. For Hello World, this
folder contains activity_main.xml.
 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.
 values: Instead of hard coding 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

3
consistent across your app. 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.
4. 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
5. Create a virtual device (emulator)
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. 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.
In order to run an emulator on your computer, you have to create a configuration that describes the virtual
device.
o In Android Studio, select Tools > AVD Manager, or click the AVD Manager icon in the toolbar.
o 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).
o Choose which version of the Android 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.
o 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.
o On System Image screen, choose a system image and click Next.
o Verify your configuration, and click Finish. (If the Your Android Devices AVD Manager window
stays open, you can go ahead and close it.)
6. 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 Pixel API 27 and click
OK
3) You should see the Hello World app as shown in the following screenshot.

7. Android Architecture
Android architecture or Android software stack is categorized into five parts:
1. Linux kernel

4
2. Native libraries (middleware),
3. Android Runtime
4. Application Framework
5. Applications

1) Linux kernel
It is the heart of android architecture that exists at the root of android architecture. Linux kernel is responsible
for device drivers, power management, memory management, device management and resource access.
2) Native Libraries
On the top of Linux kernel, there are Native libraries such as WebKit, OpenGL, FreeType, SQLite, Media, C
runtime library (libc) etc. The WebKit library is responsible for browser support. SQLite is for database.
FreeType for font support, Media for playing and recording audio and video formats.
3) Android Runtime
In android runtime, there are core libraries and DVM (Dalvik Virtual Machine) which is responsible to run
android application. DVM is like JVM but it is optimized for mobile devices. It consumes less memory and
provides fast performance.
4) Android Framework
On the top of Native libraries and android runtime, there is android framework. Android framework includes
Android API's such as UI (User Interface), telephony, resources, locations, Content Providers (data) and
package managers. It provides a lot of classes and interfaces for android application development.
5) Applications
On the top of android framework, there are applications. All applications such as home, contact, settings,
games, browsers are using android framework that uses android runtime and libraries. Android runtime and
native libraries are using Linux kernel.

5
Assignment 2 : Layout, Activity and Intent

Objectives
 To study how to use Activities, Layouts and Intents in the application.
 To study different layout in an Android.
 To study how to link Activities and interaction between Intent.
Reading
You should read the following topics before starting this exercise:
 Android - UI Layouts
 Activity, Activity Lifecycle
 Linking Activities using Intent.
Ready Reference
1) Android - UI Layouts
A layout defines the structure for a user interface in our app, such as in an activity. All elements in the
layout are built using a hierarchy of View and ViewGroup objects. A View usually draws something
the user can see and interact with. Whereas a View Group is an invisible container that defines the
layout structure for View and other ViewGroup objects.
The View objects are usually called
"widgets" and can be one of many
subclasses, such as Button or TextView.The
ViewGroup objects are usually called
"layouts" can be one of many types that
provide a different layout structure, suchas
LinearLayout or ConstraintLayout .
There are number of Layouts provided by
Android which we will use in almost all the Android applications to provide different view, look and
feel and they are...
<?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"
LinearLayout:
android:layout_height="wrap_content"
android:text="This is a TextView"/>
<Button android:id="@+id/button"
android:layout_width="wrap_content"
Android LinearLayout is a view group that aligns
android:layout_height="wrap_content"
all children in a single direction either vertically
android:text="This is a Button"/>
or horizontally.
<EditText
android:id="@+id/edtPainText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a EditText"/>
<!-- More GUI components go here -->
</LinearLayout>

6
<?xml version="1.0" encoding="utf-8"?>
RelativeLayout:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
Android RelativeLayout enables you to specify android:paddingLeft="16dp"
how child views are positioned relative to each android:paddingRight="16dp" >
other. The position of each view can be specified <EditText
as relative to sibling elements or relative to the android:id="@+id/name"
parent. Using RelativeLayout, you can align two android:layout_width="match_parent"
elements by right border, or make one below android:layout_height="wrap_content"
another, centered in the screen, centered left, and android:hint="@string/reminder" />
so on. By default, all child views are drawn at the <Spinner android:id="@+id/dates"
top-left of the layout. android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_below="@id/name"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/times" />
<Spinner android:id="@id/times"
android:layout_width="96dp"
android:layout_height="wrap_content"
android:layout_below="@id/name"
android:layout_alignParentRight="true" />
<Button android:layout_width="96dp"
android:layout_height="wrap_content"
android:layout_below="@id/times"
android:layout_alignParentRight="true"
android:text="@string/done" />
</RelativeLayout>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
TableLayout :
<TableRow android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:text="First Name"
Android TableLayout going to be arranged
android:layout_width="wrap_content"
groups of views into rows and columns. You will
android:layout_height="wrap_content"
use the <TableRow> element to build a row in the
android:layout_column="1"/>
table. Each row has zero or more cells; each cell
<EditText android:width="200px"
can hold one View object,like
android:layout_width="wrap_content"
ImageView, TextView or any other view.
android:layout_height="wrap_content"/>
For building a row in a table you will use the
</TableRow>
<TableRow> element. Table row objects are the
<TableRow
child views of a table layout. Total width of atable
android:layout_width="fill_parent"
is defined by its parent container. Column can be
android:layout_height="fill_parent">
both stretchable and shrinkable. Ifshrinkable then
<Button
the width of column can be shrunk to fit the table
android:layout_width="wrap_content"
into its parent object and ifstretchable then it can
android:layout_height="wrap_content"
expand in width to fit any extra space available.
android:text="Submit"
android:id="@+id/button"
android:layout_column="2"/>
</TableRow>
</TableLayout>

7
AbsoluteLayout: <AbsoluteLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
In Android, an Absolute Layout is a layout used android:layout_height="fill_parent">
to design the custom layouts. An Absolute Layout <Button android:layout_width="100dp"
lets you specify exact locations (x/y coordinates) android:layout_height="wrap_content"
of its children. Absolute layouts are less flexible android:text="OK"
and harder to maintain than other types of layouts android:layout_x="50px"
without absolute positioning 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>
FrameLayout : ConstraintLayout :
Frame Layout is designed to block out an area on
the screen to display a single item. Generally, Android Constraint Layout is a ViewGroup (i.e. a view that
FrameLayout should be used to hold a single holds other views) which allows you to create large and
child view, because it can be difficult to organize complex layouts with a flat view hierarchy, and also allows
child views in a way that's scalable to different you to position and size widgets in a very flexible way. It was
screen sizes without the children overlapping created to help reduce the nesting of views and also improve
each other. You can, however, add multiple the performance of layout files.
children to a FrameLayout and control their
position within the FrameLayout by assigning
gravity to each child, using the
android:layout_gravity attribute.
ListView : GridView :
List of scrollable items can be displayed in In android GridView is a view group that display items in two
Android using ListView. It helps you to or more dimensional scrolling grid (rows and columns), the
displaying the data in the form of a scrollable list. grid items are not necessarily predetermined but they are
Users can then select any list item by clicking on automatically inserted to the layout using a ListAdapter. Users
it. ListView is default scrollable so you do not can then select any grid item by clicking on it. GridView is
need to use scroll View or anything elsewith default scrollable so you don’t need to use ScrollView or
ListView. A very common example of anything else with GridView. An example of GridView is your
ListView is phone contact book default Gallery
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
ScrollView :
android:layout_height="match_parent"
tools:context=".MainActivity">
In Android, a ScrollView is a view group that is
<ScrollView
used to make vertically scrollable views. A scroll
android:layout_width="match_parent"
view contains a single direct child only. In order
android:layout_height="match_parent"
to place multiple views in the scroll view, one
tools:layout_editor_absoluteX="0dp"
needs to make a view group(like LinearLayout)
tools:layout_editor_absoluteY="-127dp">
as a direct child and then you can define many
<TextView android:id="@+id/scrolltext"
views inside it. A ScrollView supports Vertical
android:layout_width="match_parent"
scrolling only, so in order to create a horizontally
android:layout_height="wrap_content"
scrollable view, HorizontalScrollView is used.
android:text="@string/scrolltext"
android:textColor="@color/green"/>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>

8
2) Activity, Activity Lifecycle
Activity : An activity represents a single screen with a user interface just like window or frame of Java.
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.
Activity Lifecycle Public Methods , Description & Structure
1) onCreate ( ) : called when activity is first created. This
is where you should do all of your normal staticset up:
create views, bind data to lists, ect.
2) onStart ( ) : called when activity is becoming visible
to the user.
3) onResume ( ): called when activity will start
interacting with the user.

4) onPause ( ) : called when activity is not visible to the


user.

5) onStop ( ) : called when activity is no longer visible


to the user.
6) onRestart( ) : called after your activity is stopped,
prior to start.
7) onDestroy ( ) : called before the activity is destroyed
3) Linking Activities using Intent.
Intent is the objects, which is used in android for passing the information among Activities in an
Application and from one app to another also.
For example: Intent facilitates you to redirect your activity to another activity on occurrence of any
event. By calling, startActivity() you can perform this task.
Intent intent = new Intent (getApplicationContext ( ), SecondActivity.class);
startActivity (intent);
In the above example, foreground activity is getting redirected to another activity i.e.
SecondActivity.java.
getApplicationContext() returns the context for your foreground activity.
Intent are of two types: Explicit Intent and Implicit Intent

Explicit Intent: Explicit Intents are used to connect the application internally.In Explicit we use the name of
component which will be affected by Intent. For Example: If we know class name then we can navigate the
app from One Activity to another activity using Intent. Explicit Intent work internally within an application
to perform navigation and data transfer.
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
Here SecondActivity is the JAVA class name where the activity will now be navigated.
Implicit Intent: In Implicit Intents we do need to specify the name of the component. We just specify the
Action which has to be performed and further this action is handled by the component of another application.
The basic example of implicit Intent is to open any web page
Intent intentObj = new Intent(Intent.ACTION_VIEW);
intentObj.setData(Uri.parse("https://www.google.com"));
9
startActivity(intentObj);
Unlike Explicit Intent you do not use any class name to pass through Intent(). In this example you have just
specified an action. Now when we will run this code then Android will automatically start your web browser
and it will open google home page.
Example :
Activity_main.xml MainActivity.java
<?xml version="1.0" encoding="utf-8"?> package com.example.factorial;
<androidx.constraintlayout.widget.ConstraintLayout import androidx.appcompat.app.AppCompatActivity;
xmlns:android="http://schemas.android.com/apk/res/android" import android.os.Bundle;
xmlns:app="http://schemas.android.com/apk/res-auto" import android.view.View;
xmlns:tools="http://schemas.android.com/tools" import android.widget.Button;
android:layout_width="match_parent" import android.widget.EditText;
android:layout_height="match_parent" import android.widget.TextView;
tools:context=".MainActivity"> public class MainActivity extends AppCompatActivity {
<TextView EditText edNum;
android:id="@+id/textView" Button btFind,btReset;
android:layout_width="404dp" TextView txtDisplay;
android:layout_height="36dp" @Override
android:layout_marginLeft="16dp" protected void onCreate(Bundle savedInstanceState) {
android:layout_marginTop="52dp" super.onCreate(savedInstanceState);
android:fontFamily="sans-serif-light" setContentView(R.layout.activity_main);
android:gravity="center" init();
android:text="The Facorial Demo" android:textSize="24sp" btFind.setOnClickListener(new View.OnClickListener() {
app:layout_constraintBottom_toTopOf="@+id/edNum" @Override
app:layout_constraintEnd_toEndOf="parent" public void onClick(View v) {
app:layout_constraintHorizontal_bias="1.0" int num = Integer.parseInt(edNum.getText().toString());
app:layout_constraintStart_toStartOf="parent" int f = 1;
app:layout_constraintTop_toTopOf="parent" /> for(int i = 1;i<=num;i++)
<EditText f = f * i;
android:id="@+id/edNum" txtDisplay.setText("Facorial : "+f);
android:layout_width="318dp" android:layout_height="76dp" }
android:layout_marginTop="24dp" android:ems="10" });
android:hint="Enter the Positive Number" }
android:inputType="textPersonName" public void init()
android:textColor="#C50F0F" android:textSize="24sp" {
app:layout_constraintEnd_toEndOf="parent" edNum = findViewById(R.id.edNum);
app:layout_constraintHorizontal_bias="0.494" btFind = findViewById(R.id.btFind);
app:layout_constraintStart_toStartOf="parent" btReset = findViewById(R.id.btReset);
app:layout_constraintTop_toBottomOf="@+id/textView" /> txtDisplay = findViewById(R.id.txtDisplay);
<Button }
android:id="@+id/btFind" }
android:layout_width="296dp" android:layout_height="95dp"
android:layout_marginBottom="348dp" android:text="Find"
android:textColor="#AD1111" android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/edNum" />
<Button
android:id="@+id/btReset"
android:layout_width="287dp"
android:layout_height="104dp"
android:text="Reset"
android:textColor="#AD1111" android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btFind"
app:layout_constraintVertical_bias="0.151" />
<TextView
android:id="@+id/txtDisplay"
android:layout_width="269dp" android:layout_height="78dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btReset"
app:layout_constraintVertical_bias="0.245" />
</androidx.constraintlayout.widget.ConstraintLayout>

10
Lab Assignments:
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 a Simple Application, which read a positive number from the user and display its factorial value in
another activity.
4. Create a Simple Application, that performs Arithmetic Operations. (Use constraint layout)

Set B
1. Create an Android App, Which reads the Students Details (Name, Surname, Class, Gender, Hobbies, Marks)
and Display the all information in another activity in table format on click of Submit button.
2. Create an Android App with Login Screen. On successful login, gives message go to next Activity (Without
Using Database & use Table Layout).

3. Create following Vertical Scroll View Creation in Android.

11
Set C
1. Create a Simple calculator. (Use Linear Layout)

2) Create an Android Application to convert Indian Rupee(IND) to USD & EUR.

Signature of the instructor: ------------------------- Date:------------------------

Assignment Evaluation

0: Not Done 2: Late Complete 4: Complete

1: Incomplete 3: Needs Improvement 5: Well Done

12
Assignment 3 : Android User Interface and Event Handling

Objectives
 Study how to create user interface in Android.
 Study how to perform event handling
Reading
You should read the following topics before starting this exercise:
 Android - UI Layouts
 Activity, Activity Lifecycle
Control Description Xml code Java Code

Android - TextView <TextView TextView textView = findViewById(R.id.textView);


Control: android:id="@+id/textView" textView.setText(" Satish Mulgi "); //set text for text view
android:layout_width="wrap_content" textView.setTextColor(Color.RED); //set red color for text view
android:layout_height="wrap_content" textView.setTextSize(20); //set 20sp size of text
In Android, TextView displays text
to the user and optionally allows android:text=“Dr. D Y Patil College" //set background color
android:textSize="20sp" textView.setBackgroundColor(Color.BLACK);
them to edit it programmatically.
android:gravity="center_horizontal"
android:textColor="#f00"
android:textStyle="bold|italic" />
Android - EditText <EditText EditText editText = findViewById(R.id.simpleEditText);
Control : android:id="@+id/simpleEditText" editText.setHint("Enter Your Name Here");//display the hint
In Android, EditText is a standard android:layout_width="fill_parent" //set the green hint color
android:layout_height="wrap_content“ simpleEditText.setHintTextColor(Color.green(0));
entry widget in android apps. It is an
overlay over TextView that android:layout_centerInParent="true“ String editTextValue = editText.getText().toString();
configures itself to be editable. We android:hint="Enter Your Name Here" editText.setText(" Satish Mulgi "); //set text for text view
android:textColorHint="#0f0" /> editText.setTextSize(20); //set 20sp size of text
often use EditText in our
applications in order to provide
an input or text field
Android - Button Control <Button simpleButton = findViewById(R.id.simpleButton);
: android:id="@+id/simpleButton" //get id of button
In Android, Button represents a android:layout_width="wrap_content" simpleButton.setOnClickListener(new View.OnClickListener() {
push button. A Push buttons can be android:layout_height="wrap_content" @Override
clicked, or pressed by the user to android:gravity="right|center_vertical" public void onClick(View view) {
perform an action. android:textColor="#f00" Toast.makeText(getApplicationContext(),
android:textSize="25sp" "Simple Button ", Toast.LENGTH_LONG).show();
android:textStyle="bold|italic" //display the text of button
android:background="#147D03" }
android:text="ClickMe"/> });

Android -
<ImageView ImageView img = findViewById(R.id.img);
ImageView Control android:id="@+id/img" //get the id of second image view
Android android:layout_width="fill_parent" img.setOnClickListener(new View.OnClickListener() {
ImageButton Control android:layout_height="wrap_content" @Override
In Android, ImageView class is android:src="@drawable/lion" /> public void onClick(View view) {
used to display an image file in <ImageButton Toast.makeText(getApplicationContext(),
application. android:id="@+id/img1" "Lion", Toast.LENGTH_LONG).show();
In Android, ImageButton is used to android:layout_width="wrap_content" //display the text on image click event
display a normal button with a android:layout_height="wrap_content" }
custom image in a button android:src="@drawable/home" });
android:background="#000"/>

Android - CheckBox Control :


In Android, CheckBox is a type of <CheckBox android:id="@+id/cb" CheckBox cb = findViewById(R.id.cb);
two state button either unchecked android:layout_width="wrap_content" // set the current state of a check box
or checked in Android. Or you android:layout_height="wrap_content" cb.setChecked(true);
can say it is a type android:text="Cricket" //check current state of a check box (true or false)
of on/off switch that can be toggled android:textColor="#44f" Boolean checkBoxState = cb.isChecked();
by the users. android:textSize="20sp"/>

13
Android - Switch (On/Off)
<Switch simpleSwitch = findViewById(R.id.simpleSwitch);
: android:id="@+id/simpleSwitch" submit = (Button) findViewById(R.id.submitButton);
In Android, Switch is a two-state android:layout_width="wrap_content submit.setOnClickListener(new View.OnClickListener() {
toggle, switch widget that can select " @Override
between two options. It is used to android:layout_height="wrap_content public void onClick(View view) {
display checked and unchecked " String ss;
state of android:checked="true" if (simpleSwitch.isChecked())
a button providing slider control to android:text="switch" ss = simpleSwitch.getTextOn().toString();
user. It is basically an off/on android:layout_centerHorizontal="true else
button which indicate the current " ss = simpleSwitch.getTextOff().toString();
state of Switch. It is commonly used android:textOn="On"
in selecting on/off in Sound, android:textOff="Off" Toast.makeText(getApplicationContext(), "Switch :" + ss + "\n",
Bluetooth, WiFi etc. android:textColor="#f00" Toast.LENGTH_LONG).show();
android:padding="20dp"
android:gravity="center"
android:textSize="25sp"
android:background="#000"/>

ToggleButton (On/Off) : <ToggleButton tb = findViewById(R.id.tb);


In Android, ToggleButton is used to
android:id="@+id/tb" submit = (Button) findViewById(R.id.submitButton);
display checked and unchecked
android:layout_width="wrap_conten submit.setOnClickListener(new View.OnClickListener() {
state of
t" @Override
a button. ToggleButton basically
android:layout_height="wrap_conten public void onClick(View view) {
an off/on button with a light
t" String status = "ToggleButton : " + tb.getText();
indicator, which indicate the
android:checked="true" Toast.makeText(getApplicationContext(),
current state of toggle button. The
android:textOff="Off State" status, Toast.LENGTH_SHORT).show();
most simple example
android:textOn="On State" // display the current state of toggle button's
of ToggleButton is doing on/off in
android:textSize="25sp" } });
sound, Bluetooth, wifi, hotspot etc.
android:layout_centerHorizontal="tru
e"

android:textColor="#f00"
android:padding="40dp"/>

RadioButton &
<RadioGroup public void showMethod(View view){
RadioGroup android:layout_width="wrap_conten male = findViewById(R.id.male);
In Android, RadioButton are t" android:layout_height="wrap_conten female = findViewById(R.id.female);
mainly used together in t">
a RadioGroup. str = "Male : "+male.isChecked()+"\n Female :
<RadioButton "+female.isChecked();
In RadioGroup checking the one android:id="@+id/simpleRadioButton str = str+"\nYes : "+yes.isChecked()+"\n No : "+no.isChecked();
radio button out of severalradio " textView.setText(str.toString());
button added in it willautomatically android:layout_width="wrap_conten Toast toast =
unchecked all the others. t" Toast.makeText(getApplicationContext(),str,Toast.LENGTH_LONG);
It means at one time we can android:layout_height="wrap_conten toast.setMargin(200,100);
checked only one radio button from t" toast.show(); }
a group of radio buttons which android:checked="true"
belong to same radio group. android:textSize="25sp"
RadioButon is a two state button android:textStyle="bold|italic"
that can be checked or unchecked. android:padding="20dp"
If a radio button is unchecked then android:layout_centerHorizontal="tru
a user can check it by simply e"
clicking on it. Once a RadiaButton android:text="Male"
is checked by user it can’t be android:textColor="#f00"
unchecked by simply pressing on android:background="#000"/>
the same button. <RadioButton
It will automatically unchecked android:id="@+id/female" android:la
when you press any other yout_width="wrap_content" android:la
RadioButton within yout_height="wrap_content"/>
same RadioGroup. </RadioGroup>

14
Android Toast : Android Toast can be used to display information for the short period of time. Toast class is
used to show notification for a particular interval of time. After sometime it disappears. It doesn't block the
user interaction. Constants of toast :
public static final int LENGTH_LONG : displays view for the long duration of time.
public static final int LENGTH_SHORT : displays view for the short duration of time.
public static Toast makeText(Context context, CharSequence text, int duration) : makes the toast
containing text and duration.
public void show() : displays toast.
public void setMargin (float horizontalMargin, float verticalMargin): changes the horizontal and
vertical margin difference.
Example :
Toast toast=Toast.makeText(getApplicationContext(),"Hello Friends”, Toast.LENGTH_SHORT);
toast.setMargin(50,50);
toast.show();
RatingBar : RatingBar is used to get the rating from the app user. A user can simply touch, drag or click on
the stars to set the rating value. The value of rating always returns a floating point number which may be 1.0,
2.5, 4.5 etc.
1) The getRating() method of android RatingBar class returns the rating number.
RatingBar simpleRatingBar = (RatingBar) findViewById(R.id.simpleRatingBar); // initiate a rating bar
Float ratingNumber = simpleRatingBar.getRating(); // get rating number from a rating bar
2) numStars: numStars attribute is used to set the number of stars (or rating items) to be displayed in a
rating bar. By default a rating bar shows five stars but we can change it using numStars attribute.
numStars must have a integer number like 1,2 etc.
<RatingBar
android:id="@+id/simpleRatingBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numStars="7" />
Java code : simpleRatingBar.setNumStars(7); // set total number of stars
3) getNumStars(): is used to get the number of stars of a RatingBar.
int numberOfStars = simpleRatingBar.getNumStars(); // get total number of stars of rating bar
4) rating: Rating attribute set the default rating of a rating bar. It must be a floating point number.
<RatingBar
android:id="@+id/simpleRatingBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:rating="3.5" />
Java code : simpleRatingBar.setRating((float) 3.5); // set default rating

Lab Assignments:
Set A
1. Create an Android Application that will change color of the College Name(Use TextView) on click
of Push Button and change the font size, font style of text view using xml.

15
2. Create an Android Application to accept two numbers(Use PainText) and create two buttons
(power and Average). Display the result on the next activity on Button click

3. Design Following Screens Using RadioButtons & CheckBoxes.Display the selected text using Toast.

4. Create an Android Application that Demonstrate Switch and Toggle Button.

Set B
1. Create an Android Application that Demonstrate RatingBar and Display the number of stars selected on
Toast and TextView

2. Create an Android Application to perform following string operation according to user selection
of radio button.

16
3. Write an Android Application to Change the Image
Displayed on the Screen

4. Design following-add a border to an Android Layout .

Set C
1. Construct image switcher using setFactory().

2. Create an Android Application to convert Decimal number to Binary equivalent.

17
Signature of the instructor: ------------------------- Date:------------------------

Assignment Evaluation

0: Not Done 2: Late Complete 4: Complete

1: Incomplete 3: Needs Improvement 5: Well Done

18
Assignment 4 : Android TimePicker, DatePicker, Alert Dailog
Android - Alert Dialog: Alert Dialog in an android UI prompts a small window to make decision on mobile
screen. Sometimes before making a decision, it is required to give an alert to the user without moving to next
activity. For example you have seen this type of alert when you try to exit the App and App ask you to confirm
exiting.

AlertDialog.Builder is used to create an interface for Alert Dialog in Android for setting like alert title,
message, image, button, button onclick functionality etc.
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
1) setTitle(CharSequence title) – This component is used to set the title of the alert dialog.
It is optional component.
alertDialogBuilder.setTitle("Confirm Exit..!!!"); // Setting Alert Dialog Title
2) setIcon(Drawable icon) – This component add icon before the title. You will need to
save image in drawable icon.
alertDialogBuilder.setIcon(R.drawable.question); // Icon Of Alert Dialog
3) setMessage(CharSequence message) – This component displays the required message
in the alert dialog.
alertDialogBuilder.setMessage("Are you sure,You want to exit");// Setting Alert Dialog
Message
4) setCancelable(boolean cancelable) – This component has boolean value i.e true/false.
If set to false it allows to cancel the dialog box by clicking on area outside the dialog
else it allows.
alertDialogBuilder.setCancelable(false);
5) setPositiveButton(CharSequence text, DialogInterface.OnClickListener listener) – This
component add positive button and further with this user confirm he wants the alert dialog question to
happen.
alertDialogBuilder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
finish ();
} });

19
6) setNegativeButton(CharSequence text, DialogInterface.OnClickListener listener) – This
component add negative button and further with this user confirm he doesn’t want the alert dialog
question to happen.
alertDialogBuilder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this,"You clicked over No",Toast.LENGTH_SHORT).show();
} });

7) setNeutralButton(CharSequence text, DialogInterface.OnClickListener listener) – This


component simply add a new button and on this button developer can set any other onclick
functionality like cancel button on alert dialog.
alertDialogBuilder.setNeutralButton("Cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),"You clicked on
Cancel",Toast.LENGTH_SHORT).show();
}
});
8) alertDialogBuilder.create();
9) alertDialogBuilder.show();
Example :
final AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setTitle("Confirm Exit !");
adb.setMessage("are you sure, you want to Exit ?");
adb.setCancelable(true);
adb.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),"You pressed Cancel ",Toast.LENGTH_LONG).show();
}
});
adb.setNeutralButton("Retry", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),"You Presses cancel ",Toast.LENGTH_LONG).show();
}
});
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
adb.create();

20
adb.show();
}
});
Custom Alert Dialog: The custom dialog uses DIALOG to create custom alert in android studio. Dialog
display a small window that is a popup which draws the user attention over the activity before they continue
moving forward. The following are the steps to create custom alert Dialog.
Step 1: Create a new project and name it CustomAlertDialogDemo.
Step 2: Open res -> layout -> activity_main.xml and create XML for button and textview. On button
click custom alert dialog will appear & textview is for asking user to click on button.
Step 3 : Now create a layout file name as custom.xml . In this file we are going to define the XML
for custom dialog appearance. For example a textbox , imageview and a button.

Step 4 : Now open app -> java -> package -> MainActivity.java and add the below code. In this code
onclick is added over the button click and Dialog is used to create the custom alert dialog.
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
final Dialog dialog = new Dialog(context); // custom dialog
dialog.setContentView(R.layout.custom);
// if button is clicked, close the custom dialog
dialog.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
Toast.makeText(getApplicationContext(),"Dismissed..!!",Toast.LENGTH_SHORT).show();
}
});
TimePicker: In Android, TimePicker is a widget used for selecting the time of the day in either
AM/PM mode or 24 hours mode. The displayed time consist of hours, minutes and clock format. If
we need to show this view as a Dialog then we have to use a TimePickerDialog class.
<TimePicker
android:id="@+id/simpleTimePicker“
android:layout_width="wrap_content"
android:layout_height="wrap_content“
android:timePickerMode="spinner"/> or clock
Some Methods of TimePicker:
1) setCurrentHour(Integer currentHour): This method is used to set the current hours in
a time picker.

21
2) setHour(Integer hour): setCurrentHour() method was deprecated in API level 23. From api
level 23 we have to use setHour(Integer hour). In this method there is only one parameter of
integer type which is used to set the value for hours.
3) setCurrentMinute(Integer currentMinute): This method is used to set the current minutes
in a time picker.
4) getCurrentHour(): getCurrentHour() method was deprecated in API level 23. From api level 23
you have to use getHour(). This method returns an integer value.
5) getCurrentMinute():This method is used to get the current minutes from a time picker.
6) getMinute(): getCurrentMinute() method was deprecated in API level 23. From api level 23
we have to use getMinute(). This method returns an integer value.
7) setIs24HourView(Boolean is24HourView):This method is used to set the mode of the Time
picker either 24 hour mode or AM/PM mode. In this method we set a Boolean value either
true or false. True value indicate 24 hour mode and false value indicate AM/PM mode.
8) is24HourView():This method is used to check the current mode of the time picker. This
method returns true if its 24 hour mode or false if AM/PM mode is set.

TimePicker simpleTimePicker = (TimePicker)findViewById(R.id.simpleTimePicker);


// initiate a time picker
simpleTimePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener()
{
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
time.setText(hourOfDay + ":" + minute);
} });
Set A
1. Create an Android application that demonstrate the Alert Dialog.
2. Write an Android code to merge given two Array/List

3. . Create an Android application that demonstrate the Custom Alert Dialog.


4. Create an Android Application to find the factorial of a number and Display the Result on Alert
Box.

22
Set B
1. Develop an Android application that create custom Alert Dialog containing Friends Name and
onClick of Friend Name Button greet accordingly.
2. Create an Android Application that Demonstrate DatePicker and DatePickerDailog.

3. Create an Android Application that Demonstrate TimePicker and


TimePickerDailog.
Set C
1) Create a Simple Android Application to calculate age of a person. (Use
Table Layout)

Signature of the instructor: ------------------------- Date:------------------------

Assignment Evaluation

0: Not Done 2: Late Complete 4: Complete

1: Incomplete 3: Needs Improvement 5: Well Done

23
Assignment 5 : Android Adapter and Menu
In Android, Adapter is a bridge between UI component and data source that helps us to fill data in
UI component. It holds the data and send the data to an Adapter view then view can takes the data
from the adapter view and shows the data on different views like
as ListView, GridView, Spinner etc. For more customization in Views we uses the base adapter or
custom adapters. To fill data in a list or a grid we need to implement Adapter.
There are the some commonly used Adapter in Android used to fill the data in the UI components.
1) BaseAdapter – It is parent adapter for all other adapters
2) ArrayAdapter – It is used whenever we have a list of single items which is backed by an
array.
3) Custom ArrayAdapter – It is used whenever we need to display a custom list.
4) SimpleAdapter – It is an easy adapter to map static data to views defined in your XML file
5) Custom SimpleAdapter – It is used whenever we need to display a customized list and
needed to access the child items of the list or grid
List View: It is widely used in android applications. A very common example of ListView is your
phone contact book, where you have a list of your contacts displayed in a ListView and if you click
on it then user information is displayed.
Adapter: To fill the data in a ListView we simply use adapters. List items are automatically inserted
to a list using an Adapter that pulls the content from a source such as an arraylist, array or database.
Listview is present inside Containers. From there you can drag and drop on virtual mobile screen to
create it. Alternatively you can also XML code to create it.
divider: This is a drawable or color to draw between different list items.
dividerHeight: This specify the height of the divider between list items. This could be in dp(density
pixel), sp(scale independent pixel) or px(pixel).
XML Code :
<ListView
android:id="@+id/simpleListView“
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#f00"
android:dividerHeight="1dp"
android:listSelector="#0f0"/>
Java code :
ListView simpleList;
String countryList[] = {"Rajesh", "Ramesh", "Suresh", "Satish", "Rakesh", "Dinesh"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
simpleList = (ListView)findViewById(R.id.simpleListView);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
R.layout.activity_listview, R.id.textView, countryList);
simpleList.setAdapter(arrayAdapter);
}

24
GridView : In android GridView is a view group that display items in two dimensional scrolling grid
(rows and columns), the grid items are not necessarily predetermined but they are automatically
inserted to the layout using a Adapter. Users can then select any grid item by clicking on it. GridView
is default scrollable. An example of GridView is your default Gallery, where you have number of
images displayed using grid. To fill the data in a GridView we simply use adapter and grid items are
automatically inserted to a GridView using an Adapter which pulls the content from a source such
as an arraylist, array or database
XML Code :
<GridView
android:id="@+id/simpleGridView" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:numColumns="3“
android:verticalSpacing="50dp“
android:horizontalSpacing="50dp“
android:columnWidth="80dp"
android:listSelector="#0f0"
/>
Spinner :
In Android, Spinner provides a quick way to select one value from a set of values. Android spinners
are nothing but the drop down-list seen in other programming languages. In a default state,
a spinner shows its currently selected value. It provides a easy way to select a value from a list of
values.
XML Code :
<Spinner
android:id="@+id/simpleSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content”
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp" />
Java code :
String[] bankNames={"BOI","SBI","HDFC","PNB","OBC"};
Spinner spin = (Spinner) findViewById(R.id.simpleSpinner);
ArrayAdapter aa = new
ArrayAdapter(this,android.R.layout.simple_spinner_item,bankNames);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(aa);
spin.setOnItemSelectedListener(this);
public void onItemSelected(AdapterView<?> arg0, View arg1, int position,long id) {
Toast.makeText(getApplicationContext(), bankNames[position],
Toast.LENGTH_LONG).show(); }

Menu in Android : In android, there are three types of Menus available to define a set of options
and actions in our android applications.
1) Android Options Menu : The options menu is the primary collection of menu items for an
activity. It's where you should place actions that have a overall impact on the app, such as
Search, Compose Email and Settings.
2) Android Context Menu : A context menu is a floating menu that appears when the user
performs a long-click on an element. It provides actions that affect the selected content or
context frame.

25
3) Android Popup Menu : A popup menu displays a list of items in a vertical list that is
anchored(sticked) to the view that invoked the menu. It's good for providing an overflow of
actions that relate to specific content or to provide options for a second part of a command.
How to create a Menu?
For all menu types, Android provides a standard XML format to define menu items. you should
define a menu and all its items in an XML menu resource. You can then inflate the menu resource i.e load
the XML files as a Menu object in your activity.
1) A new menu directory would be made under res directory.
2) Add menu_file.xml file in menu directory by right clicking on menu --> New --> Menu
resource file.
3) Give the name as menu_file.xml and click on Ok.
4) The menu_file.xml file contains the following tags:
a) <menu> : It defines a Menu, which is a container for menu items. A <menu> element
must be the root node for the file and can hold one or more <item> and <group> elements.
b) <item>: It creates a MenuItem, which represents a single item in a menu. This element
may contain a nested <menu> element in order to create a submenu.
c) <group> :It is an optional, invisible container for <item> elements. It allows you to
categorize menu items so they share properties such as active state and visibility.
menu_file.xml
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/item1"
android:title="item1“
android:icon="@drawable/item" >
<!-- "item" submenu -->
<menu>
<item
android:id="@+id/a"
android:title="subitem a"
android:icon="@drawable/subitem_a"/>
<item
android:id="@+id/b“
android:title="subitem b“
android:icon="@drawable/subitem_b" />
</menu>
</item>
</menu>

Making an Option Menu


 To make an option menu, we need to Override onCreateOptionsMenu() method as
follows:
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_file, menu);
return true;

26
}
MenuInflater inflater = getMenuInflater();
This gives a MenuInflater object that will be used to inflate(convert our XML file into Java
Object) the menu_file.xml file.
inflater.inflate(R.menu.menu_file, menu);
inflate() method is used to inflate the menu_file.xml file.
Handling Click Events

 When the user selects an item from the options menu, the system calls your
activity's onOptionsItemSelected() method.
 This method passes the MenuItem selected.
 You can identify the item by calling getItemId() method, which returns the unique ID for
the menu item (defined by the android:id attribute in the menu resource).
 You can match this ID against known menu items to perform the appropriate action.
@Override

public boolean onOptionsItemSelected(MenuItem item) {

//Handle item selection

switch (item.getItemId()) {

case R.id.i1:

//perform any action; return true;

case R.id.a:

//perform any action; return true;

case R.id.b:

//perform any action; return true;

default: return super.onOptionsItemSelected(item);

Making Contextual Menu

 To make a floating context menu, you need to follow the following steps:
 Register the View to which the context menu should be associated by
calling registerForContextMenu() and pass it the View.
 If your activity uses a ListView or GridView and you want each item to provide the same
context menu, you can register yout all items for a context menu by passing the ListView or
GridView object to registerForContextMenu() method.
 Implement the onCreateContextMenu() method in your Activity.

27
 When the registered view receives a long-click event, the system calls
your onCreateContextMenu() method.
 This is where you define the menu items, usually by inflating a menu resource.
For example:
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {

super.onCreateContextMenu(menu, v, menuInfo);

MenuInflater inflater = getMenuInflater();

inflater.inflate(R.menu.menu_file, menu);

MenuInflater allows you to inflate the menu_file.xml file from a menu resource. The method
parameters include the View that the user selected and aContextMenu. ContextMenuInfo object
provides additional information about the item selected. If your activity has several views such that
each provide a different context menu, you might use these parameters to determine which context
menu to inflate.

Handling Click Events

@Override

public boolean onContextItemSelected(MenuItem item)

switch (item.getItemId())
{
case R.id.i1:
//Perform any action; return true;
case R.id.a:
//Perform any action; return true;
case R.id.b:
//Perform any action; return true;
default: return super.onContextItemSelected(item);
}
}
Making Popup Menu
 If you have define your menu_file.xml file in XML, here's how you can show the popup
menu:
 Make an object of PopupMenu, whose constuctor takes the current application Context and
the View to which the menu should be anchored.
 Use MenuInflater to inflate your menu resource into the Menu object returned
by PopupMenu.getMenu()

28
 Call PopupMenu.show()
For example,
<Button android:id="@+id/button" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Button"
android:onClick="pop" />
The activity can then show the popup menu like this:
public void pop(View v)
{ PopupMenu popup = new PopupMenu(this,v);
MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_file,popup.getMenu());
popup.show();
}
Listener

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final PopupMenu popup = new PopupMenu(getApplicationContext(),v);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_file,popup.getMenu());
popup.show();

popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(getApplicationContext(),"selected
"+item.getTitle(),Toast.LENGTH_LONG).show();
return true;
}
});

Set A
1. Create an Android Application that Demonstrate ListView and Onclick of List Display the
Toast.

29
2. Create an Android Application that Demonstrate GridView and Onclick of Item Display the Toast.

3. Create an Android Application that Demonstrate GridView with Images

Set B
1. Create an Android Application that Demonstrate Custom ListView which shows the BookName and
Author Name

2. Create a Custom ListView in Android Application

30
3. Create an Android Application that Demonstrate ContextMenu.

Set C
1. Create the following layout using spinner

2. Create an Android Application to demonstrate Length converter.

Signature of the instructor: ------------------------- Date:------------------------

Assignment Evaluation

0: Not Done 2: Late Complete 4: Complete

1: Incomplete 3: Needs Improvement 5: Well Done


31
Assignment 6: Thread and Services

Objective:

 To provide a way to improve application performance through parallelism.


 To ensure that the application remains active in the background so that the user can operate
multiple applications at the same time.
Thread and Notification:

A thread is a thread of execution in a program. The Java Virtual Machine allows an application to
have multiple threads of execution running concurrently. When an application is launched, the system
creates a thread of execution for the application, called "main." This thread is very important because
it is in charge of dispatching events to the appropriate user interface widgets, including drawing
events.

Worker threads
Worker threads are background threads. They are the threads that are created separately, other than
the UI thread. Since blocking the UI thread is restricted according to the rule, user should run the
child processes and tasks in worker threads.
Example
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
Bitmap b = loadImageFromNetwork("http://example.com/image.png");
mImageView.setImageBitmap(b);
}
}).start();
}
In the above example code, the download operation is handled by a second thread other than
the UI thread. But the program violates the second rule. The imageView from UI thread is
manipulating from this worker thread. In the above example code, the download operation is handled by
a second thread other than the UI thread. But the program violates the second rule. The imageView from
UI thread is manipulating from this worker thread.
According to the second rule, UI could not be accessed from outside the UI thread. Solution
for such a restriction is runOnUiThread(Runnable) method. The main or UI thread can be accessed
from other threads using runOnUiThread(Runnable) method. As a result, the specified runnable
action passed through this method will run on the UI thread. The action will execute immediately, if
the current thread is in the UI itself. Else the action will be posted to the event queue.

Example:
MainClassName.this.runOnUiThread(new Runnable() {
public void run() {
textViewObject.setText("Set this " + value from worker thread + "!");
}
});

32
Handlers & Runnable:
A handler is basically a message queue. You post a message to it, and it will eventually
process it by calling its run method and passing the message to it. Since these run calls will always
occur in the order of messages received on the same thread, it allows you to serialize events.
Uses of Handler:

Handler has two main uses


1. Scehduling of messages and runnables that need to be executed in the future.
2. Enqueueing actions that need to be performed in the background thread.

Handler is a class fundamental to how we do threading in android, at the infrastructure level.


It works hand in hand with the Looper. Together they underpin everything that the main thread does
and including the invocation of the Activity lifecycle methods.

Looper will take care of dispatching work on its message-loop thread. On the other hand
Handler will serve two roles:

1. First it will provide an interface to submit messages to its Looper queue.


2. Secondly it will implement the callback for processing those messages when they are
dispatched by the Looper.

Example:
public void onClick(View v) {
nstoploop = true;
new Thread(new Runnable() {
@Override
public void run() {
while (nstoploop){
try
{
Thread.sleep(500);
count++;

}catch (InterruptedException e){


Log.i(TAG,e.getMessage());
}
handler.post(new Runnable() {
@Override
public void run() {
tv.setText(" "+count);
}
});
}
}
}).start();
}
});

33
We can’t touch background thread to main thread directly so handler is going to collect all events
which are available in main thread in a queue and posses this queue to looper class.
In android Handler is mainly used to update the main thread from background thread or other than
main thread. There are two methods are in handler.
 Post() − it going to post message from background thread to main thread using looper.
 sendmessage() − if you want to organize what you have sent to ui (message from background
thread) or ui functions. you should use sendMessage().
AsynTask:

Android AsyncTask going to do background operation on background thread and update on


main thread. In android we can’t directly touch background thread to main thread in android
development. asynctask help us to make communication between background thread to main thread.
Android AsyncTask is an abstract class provided by Android which gives us the liberty to
perform heavy tasks in the background and keep the UI thread light thus making the application more
responsive.
Android application runs on a single thread when launched. Due to this single thread model
tasks that take longer time to fetch the response can make the application non-responsive. To avoid
this we use android AsyncTask to perform the heavy tasks in background on a dedicated thread and
passing the results back to the UI thread. Hence use of AsyncTask in android application keeps the
UI thread responsive at all times.
Methods of AsyncTask
 onPreExecute() –
Before doing background operation we should show something on screen like
progressbar or any animation to user. we can directly comminicate background operation
using on doInBackground().

 doInBackground(Params) –
In this method we have to do background operation on background thread. Operations
in this method should not touch on any mainthread activities or fragments.

 onProgressUpdate(Progress…) –
While doing background operation, if you want to update some information on UI, we
can use this method.

 onPostExecute(Result) –
In this method we can update ui of background operation result.

Generic Types in Async Task

 TypeOfVarArgParams –
It contains information about what type of params used for execution.

 ProgressValue –

34
It contains information about progress units. While doing background operation we
can update information on ui using onProgressUpdate().

 ResultValue –
It contains information about result type.

Example:

MainActivity.java

public class MainActivity extends AppCompatActivity {


Button b1,b2;
TextView tv;
Boolean stoploop;
int count = 0;
String TAG = "Thread";
private MyAsynctask async;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button)findViewById(R.id.btn1);
b2 = (Button)findViewById(R.id.btn2);
tv = (TextView)findViewById(R.id.textView);

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stoploop = true;
async = new MyAsynctask();
async.execute(count);
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stoploop = false;
}
});
}
private class MyAsynctask extends AsyncTask<Integer,Integer ,Integer>
{
private int ccount;

@Override
protected void onPreExecute() {
super.onPreExecute();
ccount=0;

35
}

@Override
protected Integer doInBackground(Integer... integers) {
ccount = integers[0];
while(stoploop){
try
{
Thread.sleep(1000);
ccount++;
publishProgress(ccount);
}
catch (InterruptedException e){
Log.i(TAG," "+e.getMessage());
}
}
return ccount;
}

@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
tv.setText(""+values[0]);
}

@Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
tv.setText(""+integer);
count = integer;
}
}
}

Activity_main.xml

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


<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

36
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.58"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.102" />

<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Thread"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.6"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView"
app:layout_constraintVertical_bias="0.116" />

<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop Thread"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.6"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btn1"

37
app:layout_constraintVertical_bias="0.145" />

</androidx.constraintlayout.widget.ConstraintLayout>

Broadcast Receiver :

Broadcast in android is the system-wide events that can occur when the device starts, when a
message is received on the device or when incoming calls are received, or when a device goes to
airplane mode, etc. Broadcast Receivers are used to respond to these system-wide events. Broadcast
Receivers allow us to register for the system and application events, and when that event happens,
then the register receivers get notified. There are mainly two types of Broadcast Receivers:

 Static Broadcast Receivers:


These types of Receivers are declared in the manifest file and works even if the app is
closed.
 Dynamic Broadcast Receivers:
These types of receivers work only if the app is active or minimized.

Creating the Broadcast Receiver:


class AirplaneModeChangeReceiver:BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
// logic of the code needs to be written here
}
}
Registering a BroadcastReceiver:

IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED).also {
// receiver is the broadcast receiver that we have registered
// and it is the intent filter that we have created
registerReceiver(receiver,it)
}

Intent Description Of Event


Indicates low battery condition on
android.intent.action.BATTERY_LOW :
the device.

This is broadcast once after the


android.intent.action.BOOT_COMPLETED
system has finished booting

To perform a call to someone


android.intent.action.CALL
specified by the data

38
Intent Description Of Event
android.intent.action.DATE_CHANGED Indicates that the date has changed

Indicates that the device has been a


android.intent.action.REBOOT
reboot

The mobile network or wifi


android.net.conn.CONNECTIVITY_CHANGE
connection is changed(or reset)

android.intent. This indicates that airplane mode


ACTION_AIRPLANE_MODE_CHANGED has been switched on or off.

Example:

MainActivity.Java
public class MainActivity extends AppCompatActivity {
private EditText txtPhone;
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtPhone = (EditText)findViewById(R.id.mblTxt);
btn = (Button)findViewById(R.id.btnCall);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
callPhoneNumber();

}
});

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if(requestCode == 101)
{
if(grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
callPhoneNumber();
}

39
}
}
public void callPhoneNumber()
{
try
{
if(Build.VERSION.SDK_INT > 22)
{
if (ActivityCompat.checkSelfPermission
(this, Manifest.permission.CALL_PHONE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new
String[]{Manifest.permission.CALL_PHONE}, 101);
return;
}

Intent callIntent = new Intent(Intent.ACTION_CALL);


callIntent.setData(Uri.parse("tel:" + txtPhone.getText().toString()));
startActivity(callIntent);

}
else {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + txtPhone.getText().toString()));
startActivity(callIntent);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}

Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<TextView
android:id="@+id/fstTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"

40
android:layout_marginTop="150dp"
android:text="Mobile No"
/>
<EditText
android:id="@+id/mblTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10">
</EditText>
<Button
android:id="@+id/btnCall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Call" />
</LinearLayout>

Services:
A service is a component that runs in the background to perform long-running operations
without needing to interact with the user and it works even if application is destroyed.

Life Cycle of Android Service

There can be two forms of a service.The lifecycle of service can follow two different paths: started
or bound.

1. Started
2. Bound

1) Started Service
A service is started when component (like activity) calls startService() method, now it runs
in the background indefinitely. It is stopped by stopService() method. The service can stop itself by
calling the stopSelf() method.

2) Bound Service
A service is bound when another component (e.g. client) calls bindService() method. The
client can unbind the service by calling the unbindService() method.

41
Fundamentals of Android Services:
Methods Description
The Android service calls this method when a component(eg:
onStartCommand() activity) requests to start a service using startService(). Once the
service is started, it can be stopped explicitly using stopService()
or stopSelf() methods.
This method is mandatory to implement in android service and
is invoked whenever an application component calls the
onBind() bindService() method in order to bind itself with a service. User-
interface is also provided to communicate with the service
effectively by returning an IBinder object. If the binding of
service is not required then the method must return null.
onUnbind() The Android system invokes this method when all the clients get
disconnected from a particular service interface.
Once all clients are disconnected from the particular interface
onRebind() of service and there is a need to connect the service with new
clients, the system calls this method.
Whenever a service is created either using onStartCommand() or
onCreate() onBind(), the android system calls this method. This methodis
necessary to perform a one-time-set-up.
onDestroy() When a service is no longer in use, the system invokes this
method just before the service destroys as a final clean up call.

42
Methods Description
Services must implement this method in order to clean up
resources like registered listeners, threads, receivers, etc.

Example of Android Services:

Step 1: Working with the activity_main.xml file


Open the activity_main.xml file and add 2 Buttons in it which will start and stop the
service. Below is the code for designing a proper activity layout.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0"
tools:ignore="MissingConstraints">

<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="170dp"
android:text="@string/heading"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Large"
android:textColor="@android:color/holo_green_dark"
android:textSize="36sp"
android:textStyle="bold" />

<Button

43
android:id="@+id/startButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:background="#4CAF50"
android:text="@string/startButtonText"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Display1"
android:textColor="#FFFFFF"
android:textStyle="bold" />

<Button
android:id="@+id/stopButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:background="#4CAF50"
android:text="@string/stopButtonText"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Display1"
android:textColor="#FFFFFF"
android:textStyle="bold" />

</LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

Step 2: Creating the custom service class


A custom service class will be created in the same directory where the MainActivity class
resides and this class will extend the Service class.

public class NewService extends Service {


private MediaPlayer player;

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
player = MediaPlayer.create( this, R.raw.ss);

// providing the boolean


// value as true to play
// the audio on loop

44
player.setLooping( true );

// starting the process


player.start();

// returns the status


// of the program
return START_STICKY;
}

@Override
public void onDestroy() {
super.onDestroy();
player.stop();
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}

Step 5: Working with the MainActivity file


Now, the button objects will be declared and the process to be performed on clicking these
buttons will be defined in the MainActivity class.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button start, stop;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById( R.id.startButton );

// assigning ID of stopButton
// to the object stop
stop = (Button) findViewById( R.id.stopButton );

// declaring listeners for the


// buttons to make them respond
// correctly according to the process
start.setOnClickListener(this );
stop.setOnClickListener(this );
}
public void onClick(View view) {

// process to be performed

45
// if start button is clicked
if(view == start){

// starting the service


startService(new Intent( this, NewService.class ) );
}

// process to be performed
// if stop button is clicked
else if (view == stop){

// stopping the service


stopService(new Intent( this, NewService.class ) );

}
}
}
Step 6: Modify the AndroidManifest.xml file
To implement the services successfully on any android device, it is necessary to mention the
created service in the AndroidManifest.xml file.

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.servicedemo">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
<service android:name=".NewService"/>
</application>
</manifest>
Notification:
A notification is a message you can display to the user outside of your application's normal
UI. When you tell the system to issue a notification, it first appears as an icon in the notification area. To
see the details of the notification, the user opens the notification drawer. Both the notification area and
the notification drawer are system-controlled areas that the user can view at any time.

46
The NotificationCompat.Builder Class

Method Description
Notification build() Combine all of the options that have been
set and return a new Notification object.
NotificationCompat.Builder Setting this flag will make it so the
setAutoCancel (boolean autoCancel) notification is automatically canceled
when the user clicks it in the panel.
NotificationCompat.Builder setContent Supply a custom RemoteViews to use
(RemoteViews views) instead of the standard one.
NotificationCompat.Builder Set the text (first row) of the notification,
setContentTitle (CharSequence title) in a standard notification.

Create and Send Notifications

Step 1 - Create Notification Builder


As a first step is to create a notification builder using NotificationCompat.Builder.build().
You will use Notification Builder to set various Notification properties like its small and large icons,
title, priority etc.
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)

Step 2 - Setting Notification Properties


Once you have Builder object, you can set its Notification properties using Builder object as
per your requirement. But this is mandatory to set at least following –

 A small icon, set by setSmallIcon()


 A title, set by setContentTitle()
 Detail text, set by setContentText()

Example:

mBuilder.setSmallIcon(R.drawable.notification_icon);
mBuilder.setContentTitle("Notification Alert, Click Me!");
mBuilder.setContentText("Hi, This is Android Notification Detail!");

Step 3 - Attach Actions


This is an optional part and required if you want to attach an action with the notification. An
action allows users to go directly from the notification to an Activity in your application, where they can
look at one or more events or do further work.
The action is defined by a PendingIntent containing an Intent that starts an Activity in your
application. To associate the PendingIntent with a gesture, call the appropriate method of
NotificationCompat.Builder. For example, if you want to start Activity when the user clicks the
notification text in the notification drawer, you add the PendingIntent by calling setContentIntent().

47
A PendingIntent object helps you to perform an action on your applications behalf, often at a later
time, without caring of whether or not your application is running.

Example:

Intent resultIntent = new Intent(this, ResultActivity.class);


TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ResultActivity.class);

// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);

Step 4 - Issue the notification


Finally, you pass the Notification object to the system by calling NotificationManager.notify()
to send your notification. Make sure you call NotificationCompat.Builder.build() method on
builder object before notifying it. This method combines all of the options that have been set and
return a new Notification object.

Example:

NotificationManager mNotificationManager = (NotificationManager)


getSystemService(Context.NOTIFICATION_SERVICE);

// notificationID allows you to update the notification later on.


mNotificationManager.notify(notificationID, mBuilder.build());

Accessing Phone services(Call,SMS) :Messaging and E-


mail

Sending SMS messages

SMS messages can be send using SmsManager Class or Built-in SMS application.

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

Create a new Android project and name it SMS. Replace the TextView with the following
statements in the main.xml file:

48
Example:
<Button android:id=‖@+id/btnSendSMS‖
android:layout_width=‖fill_parent‖
android:layout_height=‖wrap_content‖
android:text=‖Send SMS‖
android:onClick=‖onClick‖ />

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


<uses-permission android:name=‖android.permission.SEND_SMS/>

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);
}

Methods of SmsManager Class:

Methods Description
ArrayList<String> This method divides a message text
divideMessage(String 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 , String scAddress, short
destinationPort, byte[]data, This method is used to send a data
PendingIntent sentIntent, based SMS to a specific application
PendingIntent deliveryIntent) port.
void sendMultipartTextMessage Send a multi-part text based SMS.
(String destAddress, String
scAddress, ArrayList<String> parts,
ArrayList<PendingIntent>
sentIntents,

49
ArrayList<PendingIntent>
deliveryIntents)
void sendTextMessage(String
destinationAddress, String Send a text based SMS.
scAddress, String text, PendingIntent
sentIntent, PendingIntent
deliveryIntent)

Sending SMS messages using Intent:


We can also use built-in messaging application to send the message.
Steps to send SMS

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);

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.

Example:

smsIntent.setData(Uri.parse("smsto:"));

smsIntent.setType("vnd.android-dir/mms-sms");

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‖);

Sending E-mail:
We can send Email by using Email/Gmail application available on Android. An Email account
is configured by using POP3 or IMAP.
Steps to send Email
Create Android project and name it as Emails

Add the following statements in main.xml file:

50
<Button android:id=”@+id/btnSendEmail”
android:layout_width=”fill_parent” android:layout_height=”wrap_content”
android:text=”Send Email”
android:onClick=”onClick” />
Add the following statements in MainActivity.java file:
public class MainActivity extends Activity {
Button btnSendEmail;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnSendEmail = (Button) findViewById(R.id.btnSendEmail);
btnSendEmail.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {

String[] to = {―[email protected]‖,
[email protected]‖};
String[] cc = {― ‖};

sendEmail(to, cc, ―Hello‖, ―Hello my friends!‖);


}
});
}
//---sends an SMS message to another device---
private void sendEmail(String[] emailAddresses, String[] carbonCopies, String subject,
String message)
{
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setData(Uri.parse(―mailto:‖));
String[] to = emailAddresses;
String[] cc = carbonCopies;
emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
emailIntent.putExtra(Intent.EXTRA_CC, cc);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, message);
emailIntent.setType(―message/rfc822‖);
startActivity(Intent.createChooser(emailIntent, ―Email‖));

Lab Assignments:

51
SET A
1. Create an Android application to service in android that plays an audio in the background.
Audio will not be stopped even if you switch to another activity. To stop the audio, you need
to stop the service.
2. Create application to send and receive messages using SMSManager.
3. Create application to send email.
4. Create a Notification in Android and display the notification message on second activity.
SET B

1. Create application to design login form, validate it. Write and send email with appropriate
message.
2. Create an Android application to demonstrate Progress Dialog Box using AsyncTask
3. Create an Android application to demonstrate phone call in android using Implicit Intent.

SET C
1. Create an Android application to demonstrates how to use a service to download a file from the Internet
based on a button click from an activity. Once done, the service notifies the activity via a broadcast
receiver that the download is complete.
2. Create application to send email with attachment.

Signature of the instructor: ------------------------- Date:----------------

Assignment Evaluation

0: Not Done 2: Late Complete 4:

Complete

1: Incomplete 3: Needs Improvement 5: Well Done

52
Assignment 7: SQLite Database Connection

Objective:

 How to use database in an application.


 How to create and execute database queries

SQLite is an open-source relational database i.e. used to perform database operations on android
devices such as storing, manipulating or retrieving persistent data from the database. It is embedded
in android bydefault. So, there is no need to perform any database setup or administration task.
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 fe atures.
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 SQLiteOpenHelperand
override onCreate and onUpgrade and optionally onOpen. If database is not created, onCreateis
called where we write script for database creation. If already created, then onOpen is called which
opens database.

There are two constructors of SQLiteOpenHelper class.

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

53
Public Methods Description

void close() Close any open database object.

Return the name of the SQLite database being

String getDatabaseName()

opened, as given to the constructor.

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

Create and/or open a database that will be used

SQLiteDatabase getWritableDatabase()

for reading and writing.

Called when the database connection is being

void onConfigure(SQLiteDatabase db) configured, to enable features such as write-

ahead logging or foreign key support.

Called when the database is created for the first

abstract void onCreate(SQLiteDatabase db)

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.

54
Sets the maximum number of milliseconds that

void setIdleConnectionTimeout(long

SQLite connection is allowed to be idle before

idleConnectionTimeoutMs)

it is closed and removed from the pool.

public synchronized void close () Closes the database object.

Example:
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 to manage your own
databases:

Database – Creation
In order to create 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);

Database – Insertion

We can create table or insert data into table using execSQL method defined in
SQLiteDatabase class. Its syntax is given below

55
public void insert(String name, String desc) { ContentValues contentValue = new ContentValues();
contentValue.put(DatabaseHelper.SUBJECT, name); contentValue.put(DatabaseHelper.DESC,
desc); database.insert(DatabaseHelper.TABLE_NAME, null, contentValue); }

Content Values creates an empty set of values using the given initial size.

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.

Example:
Cursor resultSet=mydb.rawQuery(―Select * from
Login‖,null); resultSet.moveToFirst();
String username= resultSet.getString(0);
String password= resultSet.getString(1);

Methods Description
int getColumnCount() Returns the total number of
columns of the table.
int getColumnIndex(String Returns the index number of a
columnName) column by specifying the name of
the column.
String getColumnName (int Returns the name of the column by
columnIndex) specifying the index of the
column.
String[ ] getColumnNames() Returns the array of all the column
names of the table.
int getCount() Returns the total number of rows
in the cursor.
int getPosition() Returns the current position of the
cursor in the table.
boolean isClosed() Returns true if the cursor is closed.

Lab AssignmentsSET A

56
1. Create table Customer (id, name, address, phno). Create Android Application for performing the
following operation on the table. (using sqlite database)
i) Insert New Customer Details.
ii) Show All the Customer Details

2. Create Table Employee(Eno,Ename,Designation,Salary). Create Android Application for


performing the following operation on the table. (Using SQLite Database)
i) Insert New Employee Details.
ii) Display specific employee details.
iii) Display all the Emplyee details.

3. 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.
4. 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.

SET B

1. 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) Display all the project Details.

2. Create Table Employee(Eno,Ename,Designation,Salary). Create Android Application for


performing the following operation on the table. (Using SQLite Database)
i) Insert New Employee Details.
ii) Display maximum and minimum salary from employees table
iii) Display average salary and number of employees

3. Create Table Student(Studno,Studname,StudTotalmarks,Studno_of_subjects). Create Android


Apllication for performing the following operation on the table. (Using SQLite Database)

i) Insert New student Details.


ii) Display student details.
iii) Display the percent of all students

SET C

57
1. Create table Game(no,name,type, no_of_players). Create Application to perform the following
operations.
i) Insert Game Details.
ii) Update no_of_players to four where game is Badminton.
iii) Display all the records.
2. Create Table Employee(empno,emp_name,dept,salary,branch). Create Android Application to
perform following operations.

i) Display all Fields of employee table.

ii) Display the name of employee in descending order.

iii) Display the total salary of employee which is greater than > 120000

Signature of the instructor: ------------------------- Date:------------------------

Assignment Evaluation

0: Not Done 2: Late Complete 4: Complete

1: Incomplete 3: Needs Improvement 5: Well Done

58
Assignment 8:
Location-Based Services and Google Map
Objectives:
• Study the location based services in android

• Use various operations of Google Map

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 — 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)

Google APIs is a set of application programming interfaces (APIs) developed by


Google which allow communication with Google Services and their integration to
other services. Your application needs an API key to access the Google Maps servers.
The key is free. You can use it with any of your applications that call the Google Maps
59
Android API.

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 <string> element in the google_maps_api.xml file.

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
abstract void onMapReady This method execute
(GoogleMap googleMap) automatically when map is ready

Package Name: android.app

FragmentManager: FragmentManager is a class used to create transactions for


adding, removing or replacing fragments. It used to interact with Fragment inside
the activity.

Public Methods Description

60
Finds a fragment that was identified by the
Fragment findFragmentById(int id) given id.

Fragment findFragmentByTag(String Finds a fragment that was identified by the


tag) given
tag.

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 a MapFragment. This class provides methods to set type
of map, add markers, add polyline or move camera etc.

Constants Description

MAP_TYPE_HYBRID Satellite maps with a transparent layer of major streets.


MAP_TYPE_NONE No base map tiles.
MAP_TYPE_NORMA
L Basic maps.
MAP_TYPE_SATELLIT
E Satellite maps with no labels.
MAP_TYPE_TERRAIN Terrain maps (Topographic data).

Lab Assignments

SET A

Write a program to perform Zoom In, Zoom Out operation and display Satellite view.
Write a program to perform Zoom In, Zoom Out operation and display Terrain view of current
location on Google Map.
Write a program to find the specific location of an Android device and display details of the
place like Address line, city with Geocoding.

Write a program to search a specific location on Google Map.

61
SET B

Write a program to calculate distance between two locations on Google Map.

Write a program to demonstrate navigation using Google Map.


Write a program to add Marker for indicating specific location using Google Map

SET C

Write a program to track an android device using mobile number and display the location on
Google Map.
Write a program to modify the above program to draw the path along a route on Google Map.

Signature of the instructor: ------------------------- Date:------------------------

Assignment Evaluation

0: Not Done 2: Late Complete 4: Complete

1: Incomplete 3: Needs Improvement 5: Well Done

62
63

You might also like