Android Labbook
Android Labbook
Android Labbook
Student Name:
College Name:
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
1 Introduction to Android
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.
4. Click Finish.
2
5. After some processing time, the Android Studio main window appears.
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.
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).
11
Set C
1. Create a Simple calculator. (Use Linear Layout)
Assignment Evaluation
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 -
<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"/>
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"/>
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.
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
Set C
1. Construct image switcher using setFactory().
17
Signature of the instructor: ------------------------- Date:------------------------
Assignment Evaluation
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();
} });
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.
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.
Assignment Evaluation
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>
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
switch (item.getItemId()) {
case R.id.i1:
case R.id.a:
case R.id.b:
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);
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.
@Override
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.
Set B
1. Create an Android Application that Demonstrate Custom ListView which shows the BookName and
Author Name
30
3. Create an Android Application that Demonstrate ContextMenu.
Set C
1. Create the following layout using spinner
Assignment Evaluation
Objective:
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:
Looper will take care of dispatching work on its message-loop thread. On the other hand
Handler will serve two roles:
Example:
public void onClick(View v) {
nstoploop = true;
new Thread(new Runnable() {
@Override
public void run() {
while (nstoploop){
try
{
Thread.sleep(500);
count++;
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:
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.
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
@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
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:
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)
}
38
Intent Description Of Event
android.intent.action.DATE_CHANGED Indicates that the date has changed
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;
}
}
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.
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.
<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>
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
player = MediaPlayer.create( this, R.raw.ss);
44
player.setLooping( true );
@Override
public void onDestroy() {
super.onDestroy();
player.stop();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
// assigning ID of stopButton
// to the object stop
stop = (Button) findViewById( R.id.stopButton );
// process to be performed
45
// if start button is clicked
if(view == start){
// process to be performed
// if stop button is clicked
else if (view == stop){
}
}
}
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.
<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" />
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.
Example:
mBuilder.setSmallIcon(R.drawable.notification_icon);
mBuilder.setContentTitle("Notification Alert, Click Me!");
mBuilder.setContentText("Hi, This is Android Notification Detail!");
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:
// 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);
Example:
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.
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‖ />
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)
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
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
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 = {― ‖};
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.
Assignment Evaluation
Complete
52
Assignment 7: SQLite Database Connection
Objective:
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
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
String getDatabaseName()
SQLiteDatabase getWritableDatabase()
time.
void onOpen(SQLiteDatabase db) Called when the database has been opened.
54
Sets the maximum number of milliseconds that
void setIdleConnectionTimeout(long
idleConnectionTimeoutMs)
Example:
public class DBHelper extends SQLiteOpenHelper{
public DBHelper(){
super(context,DATABASE_NAME,null,1);
}
public void onCreate(SQLiteDatabase db){
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:
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
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)
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.
iii) Display the total salary of employee which is greater than > 120000
Assignment Evaluation
58
Assignment 8:
Location-Based Services and Google Map
Objectives:
• Study the location based services in android
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.
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.
Classes and Interface used for displaying Map are given below:
Interfaces:
60
Finds a fragment that was identified by the
Fragment findFragmentById(int id) given id.
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
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.
61
SET B
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.
Assignment Evaluation
62
63