0% found this document useful (0 votes)
28 views192 pages

Chapter 5MAD

Uploaded by

sargamkapil56
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views192 pages

Chapter 5MAD

Uploaded by

sargamkapil56
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 192

Chapter 5

Activity and Multimedia with Database


Marks=20
Prepared by Prof. Biradar R.Y.
5.1 Intent
• Intent is an abstract description of an operation to be
performed.
• Three of the core components of an application —
activities, services, and broadcast receivers — are
activated through messages, called intents.
• Intent is used for communicating between the
components of an Application such as activities, content
providers, broadcast receivers and services.
• Intent is used for communicating from one application
to another application
• Intents are also used to transfer data between activities.
• It is mostly used to start activity, send broadcast
receiver, start services and send message between two
activities.
Intent
• Purpose of Intent:
– Navigation : one page to another page
– Data Exchange : passing information such as text, images
– Inter-App Communication: one app to another app

• There are separate mechanisms for delivering intents to each type


of component:
1. An Intent object is passed to startActivity() to launch an activity
2. An Intent object is passed to startService() to initiate a service.
Similarly, an intent can be passed to bindService() to establish a
connection between the calling component and a target service.
3. Intent objects passed to broadcast method sendBroadcast().
• Android intents are mainly used to:
1. Start the service
2. Launch an activity
3. Display a web page
4. Display a list of contacts
5. Broadcast a message
6. Dial a phone call etc.

• Types of Intent
– Implicit Intent
– Explicit Intent
Types of Intent

• Implicit Intent:
– Implicit Intent doesn't specifiy 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 action specifies the thing we want to do, such
as view, edit, send, or get something. Intents often
also include data associated with the action, such
as the address of website, or the email message
– For example, to view the webpage, Send an email
Intent in=new Intent(Intent.ACTION_VIEW);
in.setData(Uri.parse("http://www.google.com"));
startActivity(in);
• Explicit Intent:
– Explicit Intent specify the component
– Explicit Intents are used to connect the application
internally.
– Explicit Intents specify the name of the component
which will be affected by Intent.
– For ex: only the specified target component will be
invoked.
Intent in = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(in);
Implict Intent Example

• Steps
1. Design the UI of activity_main.xml. For ex: add one
Button with text “Implicit Intent”
2. Implement onClick event for Button inside
MainActivity.java. Add foll. code in response to
handle event.
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://www.google.com"));
startActivity(intent);
Implict Intent Example

• Contents of activity_main.xml file


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<Button
android:id="@+id/bt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:layout_centerHorizontal="true"
android:onClick="submit"
android:text="Implicit Intent"
/>

</RelativeLayout>
Implict Intent Example
• Contents of MainActivity.java file
package com.example.implicitdemo; public void submit(View v)
{
import android.app.Activity; Intent in=new
import android.content.Intent; Intent(Intent.ACTION_VIEW);
import android.net.Uri;
import android.os.Bundle; in.setData(Uri.parse("https://www.googl
import android.view.View; e.com"));
import android.widget.Button; startActivity(in);
}
public class MainActivity extends Activity }
{
Button bt;
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

bt=findViewById(R.id.bt);
}
Explict Intent Example

• Steps
1. Design the UI of activity_main.xml. For ex: add one Button
with text “Explicit Intent”
2. Implement onClick event for Button inside MainActivity.java.
Add foll. code in response to handle event.
Intent in=new
Intent(getApplicationContext(),SecondActivity.class);
startActivity(in);
3. Design the UI of second activity activity_second.xml. For ex:
add one TextView to display some text.
4 . Create A New JAVA class name SecondActivity
5. Add SecondActivity.java in Manifest file
Explict Intent Example

• Contents of activity_main.xml file


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<Button
android:id="@+id/bt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:layout_centerHorizontal="true"
android:onClick="submit"
android:text=“Explicit Intent"
/>

</RelativeLayout>
Explict Intent Example
• Contents of MainActivity.java file
package com.example.implicitdemo; public void submit(View v)
{
import android.app.Activity; Intent in=new
import android.content.Intent; Intent(getApplicationContext(),SecondAct
import android.os.Bundle; ivity.class);
import android.view.View;
import android.widget.Button; startActivity(in);
}
}
public class MainActivity extends Activity
{
Button bt;
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

bt=findViewById(R.id.bt);
}
Explict Intent Example
• Contents of SecondActivity.java file
package com.example.implicitdemo;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class SecondActivity extends Activity


{

@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

}
}
Explict Intent Example

• Contents of activity_second.xml file


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:layout_centerHorizontal="true“
android:text=“We are in Second Activity"
/>

</RelativeLayout>
Intent_Filter
• Intent Filter are the components which decide the
behavior of an intent.
• Implicit intent uses the intent filter to serve the user
request.
• Intent Filter is declared in manifest file.
• Intent filters specify the type of intents that an
Activity, service or Broadcast receiver can respond to.
• It declares the functionality of its parent component
• It declares the capability of any activity or services or a
broadcast receiver.
• Most of the contents of the filter are described by
its <action>, <category>, and <data> subelements.
• Intent filter must contain <action>
Attributes of Intent_Filter
Sr Attribute
No
.
1. android:icon: This is displayed as icon for activity.
Ex: android:icon=“@drawable/image_name”

2. android:label: The label / title represents the title of an activity on


the toolbar. Ex: android:label = "New Activity"
3 android:priority: used in broadcasting. It controls the order in which
broadcast receivers are executed to receive broadcast messages. Those
with higher priority values are called first.
• Syntax of Intent_Filter
<activity android:name=".MainActivity">
<intent-filter android:icon="drawable resource"
android:label="string resource"
android:priority="integer" >
...
</intent-filter>
</activity>
Elements in Intent_Filter
• three elements in an intent filter:
1. Action
2. Data
3. Category
• defining an activity with Intent Filter (<intent-filter>) in Android
Manifest file
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>
1. Action:
• It represents the action to be performed.
• It is declared with the name attribute.
• An <intent-filter> element must contain one or
more <action> elements.
• If there are no <action> elements in an intent filter, the
filter doesn’t accept any Intent objects.
• Syntax:<action android:name = "string" />
• Examples
• <activity android:name=".MainActivity">
<intent-filter>

<action android:name="android.intent.action.MAIN" />


</intent-filter>
• The action in an Intent object is set by the setAction()
method and read by getAction().
• There are many actions used in Implicit intents. Some
of them are as follows

Intent.ACTION_VIEW Display the data to the user.


Intent.ACTION_SEND Deliver some data to someone else.
Intent.ACTION_CALL Perform a call to someone specified by the
data.
Intent.ACTION_DIAL Dial a number as specified by the data.
Intent.ACTION_MAIN Start as a main entry point
Intent.ACTION_WEBSEARCH Perform a web search.
Intent.ACTION_EDIT Display data for the user to edit.

Intent.ACTION_SYNC Synchronize data on a server with data on


the mobile device.
2. Data:
• Adds a data specification to an intent filter
• Data is specified using two forms
1. URI(Uniform Resource Identifiers) or
2. MIME type of data.
• setData() specifies data only as a URI,
• setType() specifies data only as a MIME type, and
• setDataAndType() specifies data as both a URI and a MIME
type.
• The URI is read by getData() and the MIME type by getType().
• Syntax:
• <data android:scheme="string" android:host="string"
android:port="string“
android:path="string"
android:pathPattern="string"
android:pathPrefix="string"
• The mime type is the data type of the data being
matched.
• The scheme is the ―protocol‖ part of the URI — for
example, http:, mailto:, or tel:
• The host name or ―data authority‖ is the section of the
URI between the scheme and the path (e.g.,
www.google.com).
• The data path is what comes after the authority (e.g.,
/ig)
• Ex: <activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<data android:mimeType="text/plain"/>
</intent-filter></activity>
• Data Specified through URI.
Ex: Intent call = new Intent(Intent.ACTION_CALL);
call.setData(Uri.parse("tel:1234567890"));

ACTION DATA MEANING


Opens phone application and calls phone
Intent.ACTION_CALL tel:phone_number
number
Opens phone application and dials (but
Intent.ACTION_DIAL tel:phone_number
doesn’t call) phone_number

Opens phone application and dials (but


Intent.ACTION_DIAL voicemail:
doesn’t call) the voice mail number.

Opens the maps Application centered on


Intent.ACTION_VIEW geo:lat,long
(lat, long).
Opens the maps application centered on
Intent.ACTION_VIEW geo:0,0?q=address
the specified address.

http://url Opens the browser application to the


Intent.ACTION_VIEW
https://url specified address.

Intent.ACTION_WEB_SEARC Opens the browser application and uses


plain_text
H Google search for given string
3. Category:
• The category is an optional part of Intent object .
• To specify under which circumstances the action should be
serviced.
• Syntax:<category android:name="string" />
• Ex:
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter></activity>
CATEGORY_BROWSABLE Browsable category, activity allows itself to be
opened with web browser to open the
reference link provided in data. for example,
an image or an e-mail message.
CATEGORY_GADGET The activity can be embedded inside of
another activity that hosts gadgets.
CATEGORY_HOME This is the home activity, that is the first
activity that is displayed when the device
boots or when the Home button is pressed.
CATEGORY_LAUNCHER Launcher category puts an activity on the top
of stack, whenever application will start, the
activity containing this category will be opened
first.

CATEGORY_PREFERENCE The target activity is a preference panel.


CATEGORY_DEFAULT
CATEGORY_ALTERNATIV this action should be available as an
E alternative to the default action performed on
an item of this data type. For example, where
CATEGORY_BROWSABLE Browsable category, activity allows itself to be
opened with web browser to open the
reference link provided in data. for example,
an image or an e-mail message.
CATEGORY_GADGET Specify that this Activity can run embedded
inside another Activity.
CATEGORY_HOME This is the home activity, that is the first
activity that is displayed when the device
boots or when the Home button is pressed.
CATEGORY_LAUNCHER Launcher category puts an activity on the top
of stack, whenever application will start, the
activity containing this category will be opened
first.

CATEGORY_PREFERENCE The target activity is a preference panel.


CATEGORY_DEFAULT make a component the default action for the
data
5.2 Activity Lifecycle
• Activity is one of the building blocks of Android OS.
• Activity is a screen that user interact with.
• Activities in the system are managed as activity stack. When
new activity is happening, it is placed on top of stack and
becomes the running activity.
• Every Activity in android has lifecycle. As a user navigates
through app, the Activity transits through different states in
their lifecycle.
• Android Activity Lifecycle is controlled by 7 methods of
android.app.Activity class.
• To navigate transitions between stages of the activity
lifecycle, the Activity class provides a core set of 7
callbacks: onCreate(), onStart(), onResume(),
onPause(), onStop(), onRestart() and onDestroy().
• Activity Lifecycle methods are as follows:
Method Description
onCreate called when activity is first created.

onStart Called just after it’s creation or by restart method after


onStop(). Here activity is becoming visible to the user.
onResume Called when Activity is visible to user and user can interact
with it
onPause called when activity is not visible to the user because user
resume previous activity.
onStop called when activity is no longer visible to the user because
some other activity takes place of it
onRestart called after your activity is stopped, prior to start.

onDestroy called before the activity is destroyed.


Fig: Activity Lifecycle
1) onCreate()
• It is called when the activity is first created.
• Here all the static work is done like creating views,
binding data to lists, etc.
• Takes Bundle containing its previous frozen state, if
there was one.
• Called only once
• Syntax:
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
2) onStart()
• It is called when the activity is visible to the user.
• invoked after onCreate() when activity is first started.
• Followed by onResume(). Called many times
• Syntax: protected void onStart()
{ super.onStart();
}
3) onRestart()
• invoked after the activity has been stopped and prior to its
starting stage
• Thus it is always followed by onStart() when any activity is
revived from background to on screen.
• Syntax: protected void onRestart()
{ super.onRestart();
}
4) onResume()
• invoked when the activity starts interacting with the user
• the activity is at the top of the activity stack
• Always followed by onPause() when the activity goes into the
background
• Syntax: protected void onResume ()
{ super.onResume();
}
5) onPause()
• user no longer actively interacts with the activity, but it is still
visible on screen.
• When activity B is launched in front of activity A, this callback
will be invoked on A.
• Syntax: protected void onPause()
{ super.onPause();
}
6) onStop()
• invoked when the activity is not visible to the user
• followed by onRestart() when the activity is revoked from the
background
• followed by onDestroy() when the activity is closed or finished
• never be called, in low memory situations
• Syntax: protected void onStop ()
{ super.onStop();
}
7) onDestroy()
• Perform any final cleanup before an activity is destroyed
• because the activity is finishing or because the system is
temporarily destroying activity to save space
• Syntax: protected void onDestroy()
{ super.onDestroy ();
}
Android Life Cycle Example
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {


@Override
protected void onStop() {
@Override
super.onStop();
protected void onCreate(Bundle savedInstanceState) {
Log.d("lifecycle","onStop invoked");
super.onCreate(savedInstanceState);
}
setContentView(R.layout.activity_main);
@Override
Log.d("lifecycle","onCreate invoked");
protected void onRestart() {
}
super.onRestart();
@Override
Log.d("lifecycle","onRestart invoked");
protected void onStart() {
}
super.onStart();
@Override
Log.d("lifecycle","onStart invoked");
protected void onDestroy() {
}
super.onDestroy();
@Override
Log.d("lifecycle","onDestroy invoked");
protected void onResume() {
}
super.onResume();
}
Log.d("lifecycle","onResume invoked");
}
@Override
protected void onPause() {
super.onPause();
Log.d("lifecycle","onPause invoked");
Broadcast Receiver
• A Broadcast Receiver in Android is a special component that acts
like a listener for system-wide events or messages sent by other
applications.
• It allows your app to respond to these events even when it's not
actively running in the foreground.
• Broadcast receivers, unlike Activities, have no user interface..
• It’s used for Asynchronous Inter-Process communication.
• Functionality:
 Listens for specific events or messages (broadcasts) sent by the
system or other apps.
 These broadcasts can signal various things like:
– Device state changes (battery low, network connection
change, date change)
– System events (boot completed, app installed/uninstalled)
– Custom messages sent by other apps
• Benefits:
– Enables your app to react to events even when it's not
actively running in the foreground.
– Promotes loose coupling between apps, allowing them to
communicate without directly knowing each other's details.
– Improves responsiveness and efficiency by allowing certain
tasks to be triggered only when specific events occur.
• Two types of Broadcast Receivers:
1. Static Broadcast Receivers: Declared in the app's manifest file
and remain active even when the app is closed.
2. Dynamic Broadcast Receivers: Registered programmatically
within the app and only active when the app is running
• 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 itself
is not running. The registration is done in the manifest file,
using <receiver> tags.
<receiver android:name=".MyBroadcastReceiver"
android:exported="true">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE""/>
</intent-filter> </receiver>
– Dynamic Broadcast Receivers: These types of receivers work
only if the app is active or minimized. The registration is done in
Java code.
The registration is done using Context.registerReceiver() method.

IntentFilter filter=new IntentFilter(Intent.ACTION_POWER_CONNECTED);


registerReceiver(new MyReceiver(), filter);
System Event Description
Intent.ACTION_BOOT_COMPLETED This is broadcast once, after the
system has finished booting.
Requires
the android.permission.RECEIVE_
BOOT_COMPLETED permission

Intent.ACTION_POWER_CONNECT Power got connected to the


ED device.
Intent.ACTION_POWER_DISCONNE Power got disconnected to
CTED the device.
Intent.ACTION_BATTERY_LOW Indicates low battery condition on
the device.

Intent.ACTION_BATTERY_OKAY Battery status good again

android.net.conn.CONNECTIVITY_CHA mobile network or wifi


NGE connection is changed(or reset)
android.intent.action.BATTERY_CHAN keeps track of the battery’s
GED charging state, percentage, and
other information about the
battery
step-by-step process of using a Broadcast
Receiver in Android:
1. Create the Broadcast Receiver:
– Make a new class that extends the abstract class BroadcastReceiver.
– Override the onReceive(Context context, Intent intent) method.
This method is called whenever the receiver receives a broadcast.
2. Register the Broadcast Receiver:
– There are two main ways to register a Broadcast Receiver:
– Declaring in the Manifest : add a <receiver> element
– Registering programmatically :
usehe registerReceiver(BroadcastReceiver receiver, IntentFilter
filter) method.
3. Unregistering the Broadcast Receiver (Optional):
– When you no longer need the receiver, call
the unregisterReceiver(BroadcastReceiver receiver) method
Broadcast Receiver Lifecycle
• The lifecycle of a broadcast receiver in Android is much simpler
and consists of two main stages:
1. Registration: The broadcast receiver is registered to listen for
specific broadcasts. This can be done either by declaring it in the
AndroidManifest.xml file or by registering it programmatically
within the app.
2. Receiving Broadcasts: When a broadcast that the receiver is
listening for is sent, the onReceive() method of the receiver is
called. The receiver can then process the information contained
in the broadcast intent.

Once the onReceive() method returns,


the broadcast receiver is no longer
active and does not participate in the
processing of any subsequent
broadcasts.
<receiver> element
• Declares a broadcast receiver as one of the application's
components. Static broadcast receivers are declared in the
manifest file with this element.
• syntax: <receiver android:directBootAware=["true" | "false"]
android:enabled=["true" | "false"]
android:exported=["true" | "false"]
android:icon="drawable resource“
android:label="string resource"
android:name="string“
android:permission="string"
android:process="string" >
...
</receiver>
• android:directBootAware -whether or not it can run before the
user unlocks the device. The default value is "false"
• android:enabled -Whether or not the broadcast receiver can be
instantiated by the system — "true" if it can be, and "false" if not.
The default value is "true". The <application> and <receiver>
attributes must both be "true" for the broadcast receiver to be
enabled.
• android:exported- Whether the broadcast receiver can receive
messages from non-system sources outside its application —
"true" if it can, and "false" if not.
• android:permission -The name of a permission that broadcasters
must have to send a message to the broadcast receiver.
• android:process-It has the same name as the application
package.
Implementing BroadcastReceiver
• Two steps to set up a Broadcast Receiver in android application
1. Creating a BroadcastReceiver
2. Registering a BroadcastReceiver

1) Create a class which extends BroadcastReceiver and


implement onReceive(Context, Intent).
public class MyReceiver extends BroadcastReceiver
{
public MyReceiver() { }
@Override
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context, "Action: " + intent.getAction(),
Toast.LENGTH_SHORT).show();
}
}.
Implementing BroadcastReceiver
2) Specify the <receiver> element in app's manifest
<receiver android:name=".MyReceiver“
android:enabled="true" >
<intent-filter>
<action android:name="android.intent.action.POWER_CONNECTED" />
</intent-filter> </receiver>

or programmatically
IntentFilter filter=new
IntentFilter(Intent.ACTION_POWER_CONNECTED);
registerReceiver(new MyReceiver(), filter);
BroadcastReceiver Example

• Contents of activity_main.xml file


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content“
android:text=“Charger Info“ />

</RelativeLayout>
• Contents of MainActivity.java file
package com.example.broadcastapp;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;

public class MainActivity extends Activity {

MyReceiver receiver;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

receiver=new MyReceiver();

IntentFilter filter=new IntentFilter();


filter.addAction(Intent.ACTION_POWER_CONNECTED));
filter.addAction(Intent.ACTION_POWER_DISCONNECTED);
• Contents of MyReceiver.java file
package com.example.broadcastapp;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver


{
@Override
public void onReceive(Context context, Intent intent)
{
String intentAction = intent.getAction();

switch(intentAction) {
case Intent.ACTION_POWER_CONNECTED:
Toast.makeText(context, "Charger Connected", Toast.LENGTH_SHORT).show();
break;
case Intent.ACTION_POWER_DISCONNECTED:
Toast.makeText(context, "Charger Disconnected", Toast.LENGTH_SHORT).show();
break;
}
}
}
5.3 Content Provider
• Android application hides its data from other applications.
• Content provider is only required if we need to share data
between multiple applications
• A ContentProvider acts as a central hub for managing and
sharing data. It offers a standardized interface that allows
– Sharing data: Multiple applications can access and
interact with the same data source.
– Data protection: ContentProvider controls access by
defining access permissions , ensuring data privacy and
integrity. This safeguards sensitive information.
• A content provider acts like a single point of access for your
application's data. It can store data in various formats like
SQLite databases, files, or even over a network.
• Works like Client-server model. Applications seeking data
from your content provider act as clients. They use
the ContentResolver class to send requests like queries and
receive results.
• Content provider component is not activated by an Intent.
• Content providers also provides set of predefined methods
for operations like adding, retrieving, updating, and
deleting data using insert(), update(), delete(), and query()
methods.
• Benefits of using ContentProvider:
– Secure data sharing: Controlled access prevents
unauthorized data modifications by other applications.
– Inter-process communication: Enables data exchange
between different apps running on the same device.
– Flexibility in data storage:ContentProviders can handle
various data structures (SQLite, files, etc.).
• How to implement?
– A content provider is implemented as a subclass of
Android ContentProvider class.
– Register Content Provider using <provider> tag.
public class My Application extends ContentProvider
{}
• The provider implements methods like:
1. onCreate() :called when the provider is
started.
2. query() :receives a request from a
client. The result is returned as a Cursor
object.
3. insert():inserts a new record into the
content provider.
4. delete() deletes an existing record from
the content provider.
5. update() updates an existing record
from the content provider.
6. getType() returns the MIME type of the
data at the given URI.
• To retrieve data from ContentProvider, call query()
cursor = contentResolver.query(
CONTENT_URI, // The content URI of the table
projection, // The columns to return for each row
selectionClause, // Selection criteria(where clause)
selectionArgs, // Selection criteria(group byclause)
sortOrder // The sort order
)

• Content URIs:
• A content URI is a URI that identifies data in a provider.
• Content URIs include the symbolic name of the entire provider
(its authority) and a name that points to a table (a path)
• Syntax: <prefix>://<authority>/<data_type>/<id>
Ex: "content://com.example.MyApplication.StudentsProvider/students/4
• To insert data into ContentProvider, call insert()

cursor = contentResolver.insert(CONTENT_URI, newValues )

• To update data from ContentProvider, call update()

cursor = contentResolver.update (CONTENT_URI, updateValues ,


selectionclause,selectionArgs)

• To delete data from ContentProvider, call delete()

cursor = contentResolver.delete (CONTENT_URI,


selectionclause,selectionArgs )
• For ex: Consider two apps: App1 & App2
– App2 might need some data from App1.
– But App2 cannot access App1’s data because that data is private.
– content providers become very useful.

• App2 can request for App1’s data


by using a ContentResolver.
• App1 can expose it’s private data in
secured manner using a
ContentProvider.
• ContentProvider implemented in
App1 will respond back with a
format called Cursor.
• This is called inter-process
communication.
• Example of ContentProvider ( Accessing data from Contact App)
MainActivity.java
package com.example.contentproviderapp;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

EditText etName;
TextView tvResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

etName=(EditText) findViewById(R.id.editText1);
public void search(View v)
{
String name=etName.getText().toString();

String projection[]=new String[]


{ContactsContract.CommonDataKinds.Phone.NUMBER,ContactsContract.CommonDataKi
nds.Phone.DISPLAY_NAME};

String selection= ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+"


like'%" + name +"%'";

ContentResolver cr=this.getContentResolver();

Cursor c = (Cursor)
cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection,
selection, null, null);

String s = "";
while (c.moveToNext()) {
s="Name="+c.getString(1)+"\nPhone Number="+c.getString(0);
}
tvResult.setText(s);
}
• activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical“ >

<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>

<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="search"
android:text="Search Contact" />

<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />

</LinearLayout>
• Permission in Manifest file (To access data from Contact App)

<uses-permission
android:name="android.permission.READ_CONTACTS" />
Fragments
• A Fragment is a part of an activity which enable more
modular activity design.
• Fragment is a kind of sub-activity. A Fragment represents a
reusable portion of app's UI.
• Supports more dynamic and flexible UI designs on large
screens. Fragments can be added, removed, or replaced at
runtime within an activity.
• We can combine multiple Fragments in Single Activity to build
a multi panel UI and reuse a Fragment in multiple Activities.
• They encapsulate:
– Layout: Each fragment defines its own visual appearance
using an XML layout file.
– Logic: A fragment can handle its own events, user
interactions, and data.
– Lifecycle: Fragments have their own lifecycle stages tied to
• Fragment is inserted into activity layout file by using
<fragment> tag. The android:name attribute in
the <fragment> specifies the Fragment class
• With the help of Fragment’s we can divide the screens
in different parts and controls different parts
separately.
• Creation of Fragment:
public class FirstFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup
container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_first, container, false);
}
}
In tablets, there is only one activity that is Activity 1. In Activity 1, there are two
fragments, Fragment A and Fragment B. When we select an item from Fragment A, it gets
open in Fragment B of the same activity.
In the case of mobiles, there are two activities that are:
Activity 1 with Fragment A and Activity 2 with Fragment B.
When we select an item from Fragment A, it gets open in the Fragment B of Activity 2.
• Basic Fragment Code In XML:
<fragment
android:id="@+id/fragment1"
android:name="com.example.fragmentdemo.FirstFragment"
android:layout_width="match_parent"
android:layout_height="300dp” />

• Types of Fragments
1. Single frame fragments − Single frame fragments are
using for hand hold devices like mobiles, here we can
show only one fragment as a view.
2. List fragments − fragments having special list view is
called as list fragment
3. Fragments transaction − Using fragment transaction, we
can move one fragment to another fragment.
Fragment Lifecycle
1) onAttach(Activity) it is called only once when fragment is attached with
activity.
2) onCreate(Bundle) This method is to create a Fragment.
3) onCreateView(LayoutInflater, The fragment creates its user interface by inflating a layout
ViewGroup, Bundle) file or constructing a view programmatically.

4) onActivityCreated(Bundle) It is invoked after the completion of onCreate()


method when the host activity is created.
5) onStart() makes the fragment visible.
6) onResume() makes the fragment interactive.
7) onPause() The fragment is being paused. called when fragment is
no longer interactive.
8) onStop() called when fragment is no longer visible.
9) onDestroyView() The fragment's view hierarchy is being destroyed.

10) onDestroy() The fragment is being destroyed.. Allows the fragment to


do final clean up of fragment state.
11) onDetach() It is called immediately prior to the fragment no
longer being associated with its activity.
• Example of Fragment
• (MainActivity.java)
package com.example.fragmentdemo;
import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
• Example of Fragment
• (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="This is main activity" />

<fragment
android:id="@+id/fragment1"
android:name="com.example.fragmentdemo.FirstFragment"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_marginTop="300dp“ />

</RelativeLayout>
• Example of Fragment
• (fragment_first.xml)
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F5F5DC" >

<Button
android:id="@+id/bt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="50dp"
android:onClick="submit"
android:text="First Fragment" />

</FrameLayout>
• Example of Fragment
• (FirstFragment.java)
package com.example.fragmentdemo;

import android.os.Bundle;
v=inflater.inflate(R.layout.fragment_first,
import android.app.Fragment; container, false);
import android.view.LayoutInflater; b=(Button)v.findViewById(R.id.bt);
import android.view.View; b.setOnClickListener(new
import android.view.ViewGroup;
import android.widget.Button; View.OnClickListener() {
import android.widget.Toast; @Override
public void onClick(View v) {
Toast.makeText(getActivity(),"this
public class FirstFragment extends
Fragment {
is fragments
Button b; button",Toast.LENGTH_LONG).show();
View v; }
@Override });
public View return v;
onCreateView(LayoutInflater }
inflater, ViewGroup }
container,Bundle
savedInstanceState) {
// Inflate the layout for this
fragment
5.4 Service
• Android service is an application component that
is designed for running long-running operations in the
background.
• Service doesn’t has any user interface.
• Another application component can start a service, and
it continues to run in the background even if the user
switches to another application.
• For ex, a service can handle playing music, network
transactions, interacting content providers etc, all from
background.
• A service is implemented as a subclass of Service class
and service needs to be declared in
the AndroidManifest.xml file
• Three different types of services:
1. Foreground : Foreground services are those services that are
visible to the users. The users can interact with them at ease
and track what’s happening. These services continue to run
even when users are using other applications. Example of this
is Music Player and Downloading.
2. Background: These services run in the background, such that
the user can’t see or access them. These are the tasks that
don’t need the user to know them. Example of this is Syncing ,
Storing data or compact its storage.
3. Bound: A service is bound when an application component
binds to it by calling bindService(). Many components can bind
to one service at a time, but once they all unbind, the service
will destroy. A bound service offers a client-server interface.
Example of this is inter-process communication (IPC).
Android Platform Services
• The Android platform provides and runs predefined system
services.
• These built-in services handle various core functionalities essential
for the overall operation of the device.
• Every Android application can use them, given the right
permissions.
• Examples of Android Platform Services:
– Telephony Manager: Handles core telephony functions like call
management and network information.
– Location Manager: Provides location data to apps through GPS,
Wi-Fi, and cell tower signals.
– Job Scheduler: Automates tasks within the system based on
specific conditions like device connectivity or time.
• These system services are usually exposed via a specific Manager
class.
• Access to them can be gained via the getSystemService() method.
• The Context class defines several constants for accessing these
services.
• Example:
SensorManager
sMgr=(SensorManager)getSystemService(SENSOR_SERVICE);

Here SensorManager object is created to access the various Sensors


in Android
Creating new Service
• A service is implemented as a subclass of Service
public class MyService extends Service
{
public int onStartCommand(Intent intent, int flags, int startId)
{
return Service.START_NOT_STICKY;
}
public IBinder onBind(Intent intent) //must always implement
{
return null;
}
}
• A service needs to be declared in the AndroidManifest.xml file
syntax:
<service android:name=".ServiceClassName“
android:enabled=“true” android:exported=“true” />
Service Lifecycle
• Android services life-cycle can follow two different paths:
1. Started Service 2. Bound Service
1) Started Service
 A service is started when application component (like
activity) starts it by calling startService() method.
 It performs a single operation and doesn’t return any result
to the caller.
 It runs in the background indefinitely even if the
component that started is destroyed.
 This service can be stopped only in one of the two cases:
1. By using the stopService() method.
2. By stopping itself using the stopSelf() method.
 For ex, to play music in the background, call startService()
method.
2) Bound Service
 A service is bound only if an application component binds to
it using bindService().
 It offers a client-server interface that allows the
components to interact with the service. The components
can send requests to services and get results.
 This service runs in the background as long as another
application is bound to it. It can be unbound using
onUnbind().
 For ex, to get information of the current song being played,
bind the service that provides information about the current
song.
Service Lifecycle
Methods of Android Service Lifecycle
1 onCreate()
Invoked when the service is first created
before onStartCommand() or onBind(). This call is required to
perform one-time set-up.
2 onStartCommand()
This callback is invoked when service is started by any component
by calling startService(). It basically indicates that the service has
started and can now run indefinetly.
It return one of the foll. Values and indicate how the system
should behave when a started service is forced to stop:
• START_STICKY: The system will restart your Service after it has
been killed by the system and previous intent is not redeliverd.
• START_NOT_STICKY: The system will not restart your Service
after it has been killed by the system
• START_REDELIVER_INTENT: It is like START_STICKY, but the
system will retain the Intent used for starting the Service and
redeliver it when restarting.
Service Lifecycle
3 onBind()
It is invoked when any component bind with the service by
calling bindService(). Needs to return IBinder which will be used
for Interprocess Communication. If dont want service to bind with
any component just return null. Always needs to be
implemented.
4 onUnbind() Invoked when all the clients are disconnected from
the service.
5 onRebind() Invoked when new clients are connected to the
service. It is called after onUnbind()
6 onDestroy() This is a final clean up call from the system. This is
invoked just before the service is being destroyed.
• Example of Service/Lifecycle of service
• (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F5F5DC" >

<Button
android:id="@+id/bt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:layout_marginLeft="50dp"
android:onClick="start"
android:text="Start Service" />

<Button
android:id="@+id/bt2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:layout_marginLeft="200dp"
android:onClick="stop"
android:text="Stop Service" />

</RelativeLayout>
• (MainActivity.java)
package com.example.servicedemo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void start(View v)
{
Intent i1=new Intent(this,MyService.class);
startService(i1);
}
public void stop(View v)
{
Intent i1=new Intent(this,MyService.class);
stopService(i1);
}
• (MyService.java)
package com.example.servicedemo;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service {

MediaPlayer mp;

public IBinder onBind(Intent intent) {


return null;
}
public void onCreate() {
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
mp = MediaPlayer.create(this, R.raw.ganpatiaarti);
}
public int onStartCommand(Intent intent, int flags, int startId)
{
mp.setLooping(false); // Set looping
mp.start();
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
@Override
public void onDestroy() {
Toast.makeText(this, "Service Stopped",
Toast.LENGTH_LONG).show();
mp.stop();
}
}

• (AndroidManifest.xml)
Add foll. Service tag in manifest file.
<service
android:name=".MyService"
android:enabled="true“
android:exported="true” />
5.5 Android System Architecture
• Android is structured as a software stack.
• Android is an open source, Linux-based software stack .
• The android system consists of five layers and each layer consists
of some core components.
• Android architecture or Android software stack is categorized
into following parts:
1. Linux kernel and HAL (Hardware Abstract Layer)
2. Libraries (middleware),
3. Android Runtime
4. Application Framework
5. Applications
1) Linux kernel and HAL
– The foundation of Android platform is the Linux
kernel.
– It provides a level of abstraction between the
device hardware using Hardware Abstraction
Layer(HAL). The HAL provides standard interfaces
that expose device hardware capabilities to the
higher-level Application framework.
– Linux kernel is responsible for device drivers,
power management, memory management, device
management and resource access.
2) Libraries (Native Libraries)
– Many Android system components and services,
such as ART and HAL, are built from native code
that require native libraries written in C and C++.
– On top of Linux kernel there is a set of libraries are:
Library Explanation
SQLite This library is used to access data
SSL This is used to provide internet security

OpenGL drawing and manipulating 2D and 3D graphics


Media It is used to provides different media codecs which
framework allow the recording and playback of different media
formats
WebKit It is the browser engine used to display internet
content or HTML content
FreeType Provides font support.
3)Android Runtime
– It provides most important part of android called
Dalvik Virtual Machine.
– Dalvik Virtual Machine is designed and optimized
for Android.
– Dalvik Virtual machine uses core functions of Linux
such as memory management and multi threading
and enables each android app to run its own
process.
– The Android runtime also provides a set of core
libraries which enable Android application
developers to write Android applications using
standard Java programming language.
4)Application Framework
– Android applications directly interacts with
application framework.
– Application framework manages the basic functions
of android device such as resource management,
voice call management etc.
– Application Framework layer provides many
higher-level services to applications in the form of
Java classes..
– The Android framework includes the following key
services -
Application Framework Explanation

Activity Manager Used to manage complete activity life cycle of


applications
Content Providers Used to manage the data sharing between two
applications
Telephony Manager Used to manages all voice calls
Location Manager Used to manage the Locations obtained using GPS or
cell tower

Resource Manager Used to manage the different types of resources used in


android app.

Notifications Manager Allows applications to display alerts and notifications to


the user.

View System An extensible set of views used to create apps UI ,


including lists, grids, text boxes, buttons,
5)Applications
– All the Android application are at the top layer.
– Application layer consists of many core Java-based
applications, such as calendar, web browser, SMS
application, E-mail, etc.
– The application layer runs within the Android run
time .
Android Multimedia Framework
• Multimedia is concerned with processing of
audio/video/images input and output.
• The Android multimedia framework includes support
for playing variety of common media types, so that we
can easily integrate audio, video and images into
applications.
• media framework is at the libraries section of android
architecture.
• Features of multimedia framework:
– Storing audio and video section of media
– Playback audio and video
– Record audio and video
• The following classes are used to play sound and video
in the Android framework:
1. MediaPlayer: It is the primary API for playing sound
and video.
2. AudioManager:This manages audio sources and
audio output on a device.

• The goal of multimedia framework is to provide


consistent interface for Java services.
• The multimedia framework consists of core dynamic
libraries such as libmdeia.jni, libmedia,
libmediaplayerservice, and so on
• Fig1. shows the Android multimedia framework
architecture
• From fig1. we can see Java classes calls the native C Library
Libmedia through Media JNI(Java Native Interface).
• Libmedia library communicates with Media Server process
through Android’s Binder IPC mechanism.
• Media Server process creates corresponding multimedia service
according to the Java multimedia applications.
• The whole communication between Libmedia and Media
Server forms the client/server model.
• Media Server process calls OpenCore multimedia engine to
realize multimedia functions and OpenCore engine refers to the
PVPlayer and PVAuthor.
• First Java applications sets the URI of the media to PVPlayer
through Java Framework, JNI and Native C. There is no data
stream flows.
• PVPlayer processes media streams with foll. steps:
1. Demux the media data to separate video/audio data
stream,
2. Decode video/audio data,
3. Sync video/audio time
4. Send the decoded data out
• OpenCore Multimedia Engine:
– PacketVideo is the OpenCore. It is multimedia framework. It
includes two functionalities:
– PVPlayer: It provides Media Player , audio/video streaming
and playback functionality.
– PVAuthor: It provides streaming media video/audio
recording capability and still image capture.
Playing Audio and Video
• MediaPlayer class is used for playing sound and video.
• MediaPlayer class is available in android.media package.
• Creation of MediaPlayer takes the foll. Syntax
MediaPlayer mp = MediaPlayer.create(this, R.raw.song);
• The second parameter is the name of the song that we
want to play. We have to make a new folder under our
project with name raw and place the music file into it.
• To start or stop the music, start() and pause() methods of
MediaPlayer can be used. For ex
mp.start();
mp.pause();
• On call to start() method, the music will start playing
from the beginning.
• If start() method is called again after the pause() method, the
music would start playing from where it is left and not from the
beginning.
• In order to start music from the beginning, we have to
call reset() method. For ex, mp.reset();
• To play media file from internal or external URI
Step 1: MediaPlayer mp = new MediaPlayer();
Step 2: mp.setDataSource(mediaPath); //setDataSource
Step 3: mp.prepare(); //prepare
Step 4: mp.start();// start

• To play media file from available local raw resource (saved in


app's res/raw/ directory):
Step1: MediaPlayer
mp=MediaPlayer.create(this,R.raw.song); //no need to call
prepare(), create() will do this
Step 2: mp.start(); // start
Methods of Media Player
1 boolean isPlaying()
just returns true/false indicating the song is playing or not
2 void seekTo(position)
takes an integer, and move song to that particular position
millisecond
3 int getCurrentPosition()
returns the current position of song in milliseconds
4 int getDuration()
returns the total time duration of song in milliseconds
5 void reset()
resets the media player
6 void start()
starts the media player
7 void pause()
pauses the media player
Methods of Media Player
8 void release()
releases any resource attached with MediaPlayer object
9 void setVolume(float leftVolume, float rightVolume)
sets the up down volume for this player
10 void setDataSource(FileDescriptor fd)
sets the data source of audio/video file
11 void selectTrack(int index)
takes an integer, and select the track from the list on that
particular index
12 void prepare()
It prepares the player for playback synchronously.
13 void setLooping(boolean looping)
sets the player for looping or non-looping.
Fig: State Diagram of
MediaPlayer
• The ovals represent the states of MediaPlayer
• The arcs represent the playback control operations There are two
types of arcs. The arcs with a single arrow head represent
synchronous method calls, while those with a double arrow head
represent asynchronous method calls.
• When a MediaPlayer object is just created using new or
after reset() is called, it is in the Idle state; and after release() is
called, it is in the End state.
• once an error occurs, the MediaPlayer object enters
the Error state
• MediaPlayer is in Prepared state if the creation
using create method is successful. A MediaPlayer object must first
enter the Prepared state before playback can be started. An
IllegalStateException is thrown if prepare() or prepareAsync() is
called in any other state.
• To start the playback, start() must be called. After start() returns
successfully, the MediaPlayer object is in the Started state.
• When the call to pause() returns, the MediaPlayer object
enters the Paused state. When the call to start() returns, the
paused MediaPlayer object goes back to the Started state.
• Calling stop() stops playback and causes a MediaPlayer to enter
the Stopped state.
• Once in the Stopped state, playback cannot be started until
prepare() or prepareAsync() are called .
• MediaPlayer can continue playing the Audio or Video playback
from the specified position using seekTo(pos)
• When the playback reaches the end of stream, the playback
completes.
• While in the PlaybackCompleted state, calling start() can restart
the playback from the beginning of the audio/video source.
• Example of playing audio file
• (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<Button
android:id="@+id/bt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginTop="175dp"
android:text="Play" />

<Button
android:id="@+id/bt2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="175dp"
android:text="Pause" />

<Button
android:id="@+id/bt3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="175dp"
android:layout_marginLeft="250dp"
android:text="Stop" />

</RelativeLayout>
• Example of playing audio file (MainActivity.java)
package com.example.playaudio;
public void pause(View v)
import android.app.Activity; {
import android.media.MediaPlayer; mp.pause();
import android.os.Bundle; }
import android.view.View; public void stop(View v)
{
public class MainActivity extends Activity { mp.stop();
}
MediaPlayer mp; }
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState); • Create raw folder in res
setContentView(R.layout.activity_main); folder and store audio file
(ex: ganapatiaarti.mp3) in
mp=MediaPlayer.create(this,R.raw.jaiganesh);
raw folder.
}
public void start(View v)
{
mp.start(); }
Playing Video
• By using VideoView component
and MediaController class we can easily implement the
video player in android applications to play the videos
with multiple playback options, such as play, pause,
forward, backward, etc.
• MediaController class in android will provide a playback
options for video player, such as play, pause, backward,
forward, etc.
• VideoView class provides methods to play and control
the video player. The VideoView class combines
MediaPlayer class with a SurfaceView to actually display
the video.
• Methods of VideoView
public void sets the media controller to the video
setMediaController(MediaController view.
controller)
public void setVideoURI (Uri uri) sets the URI of the video file.

public void setVideoPath(String sets the path of the video file.


path)

Public boolean isPlaying() Checks if video is playing

public void start() starts the video view.

public void stopPlayback() stops the playback.

public void pause() pauses the playback.

public void suspend() suspends the playback.

public void resume() resumes the playback.

public void seekTo(int millis) seeks to specified time in miliseconds.


 Steps to play video file
• Step1: Create VideoView object
videoView=findViewById(R.id.videoview);

• Step2: Create MediaController object


MediaController mCtrl=new MediaController(this);
mCtrl.setMediaPlayer(videoView);

• Step3: set video URI


Uri uri = Uri.parse("android.resource://"+getPackageName()
+"/"+
R.raw.kadhi_tu);
videoView.setVideoURI(uri);

• Step4: set media controller and start the videoview


videoView.setMediaController(mCtrl);
videoView.requestFocus();
videoView.start();
• Example of playing video file
• (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<VideoView

android:id="@+id/videoview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerVertical="true"/>

</RelativeLayout>

• Create raw folder in res folder and store video file (ex:
kadhi_tu.mp4) in raw folder.
• Example of playing Video file
• (MainActivity.java)
package com.example.playvideoapp;

import androidx.appcompat.app.AppCompatActivity;

import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;

public class MainActivity extends AppCompatActivity {

VideoView videoView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

videoView=findViewById(R.id.videoview);

MediaController mCtrl=new MediaController(this);


mCtrl.setMediaPlayer(videoView);

Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.kadhi_tu);

videoView.setVideoURI(uri);
videoView.setMediaController(mCtrl);
videoView.requestFocus();
videoView.start();
}
}
TextToSpeech
• Android allows us to convert text into voice.
• TextToSpeech is android speech synthesis class
• Text to speech (TTS) makes an android device read the text and
convert it to audio out via the speaker.
• Android TTS supports multiple languages.
• It is included in android.speech.tts package.
• It has features to control speed, pitch of speech as well as type of
language. It can also be effectively used in mobile APPs dedicated
to visually impaired people or in educational app for kids or can be
used in pronunciation learning app, etc
TextToSpeech
• TextToSpeech needs to be initialized first. And need to implement
the TextToSpeech.OnInitListener interface and override the method
onInit()
• Constructor
• TextToSpeech(Context context, TextToSpeech.OnInitListener listener)
• For ex:
TextToSpeech ttobj=new TextToSpeech(getApplicationContext(), new
TextToSpeech.OnInitListener()
{
@Override
public void onInit(int status) {
}
});
• Status may take one of the foll. Value:
TextToSpeech.SUCCESS or TextToSpeech.ERROR
• In listener method We have to specify the properties for
TextToSpeech object , such as its language ,pitch e.t.c.
• Language can be set by calling setLanguage() method.
• We can use one of the foll. Values to set the language

Locale.UK Locale.US
Locale.CANADA Locale.ENGLISH
Locale.GERMAN Locale.ITALIAN
Locale.JAPANESE Locale.CHINESE
Locale.FRENCH Locale.KOREAN

• A Locale object represents a specific geographical, political, or


cultural region.
• Methods of TextToSpeech class
addSpeech(String text, String filename)
adds a mapping between a string of text and a sound file.
setLanguage(Locale loc)
sets a language.
getLanguage()
returns a Locale instance describing the language.
stop()
stop the speak.
isSpeaking()
checks whether the TextToSpeech engine is busy speaking.
setPitch(float pitch)
sets the speech pitch for the TextToSpeech engine. Default
value is 1.0f
setSpeechRate(float speechRate)
sets the speech rate. Default value is 1.0f
• Methods of TextToSpeech class
shutdown()
releases the resources used by the TextToSpeech engine.
speak(CharSequence text, int queueMode, Bundle params)
Speaks the text using the specified queuing strategy and
speech parameters.
Queue mode may take one on the foll. Value
1.QUEUE_ADD:
Queue mode where the new entry is added at the end of the
playback queue.
2. QUEUE_FLUSH:
Queue mode where all entries in the playback queue are
dropped and replaced by the new entry.
• Example of TextToSpeech
• (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<EditText
android:id="@+id/et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Text"
android:layout_marginTop="50dp"
android:ems="10“ />
<Button
android:id="@+id/bt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:layout_centerHorizontal="true"
android:onClick="texttospeech"
android:text=“Text To Speech“ />

</RelativeLayout>
• Example of TextToSpeech
• (MainActivity.java)
package com.example.texttosppech;

import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.Locale;

public class MainActivity extends Activity {

Button bt;
EditText et;
TextToSpeech ttsobj;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

et = findViewById(R.id.et);

ttsobj = new TextToSpeech(this, new TextToSpeech.OnInitListener() {


@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
ttsobj.setLanguage(Locale.UK);
}
}
});
}
public void texttospeech(View v) {
String text = et.getText().toString();
ttsobj.setPitch(2.0f);
ttsobj.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}

@Override
protected void onDestroy() {
super.onDestroy();
if (ttsobj != null) {
ttsobj.stop();
ttsobj.shutdown();
}

}
}
Sensors
• Most of the Android-powered devices have built-in sensors that
measure motion, orientation, and various environmental conditions.
• Some of these sensors are hardware-based and some are software-
based.
• Android platform supports three broad categories of sensors.
1. Motion Sensors:
These sensors measure acceleration forces and rotational forces along
three axes. It includes accelerometers, gravity sensors, gyroscopes, and
rotational vector sensors.
2. Environmental sensors:
These sensors measure various environmental parameters, such as
ambient air temperature and pressure, illumination, and humidity. It
includes barometers (used to measure air pressure), photometers, and
thermometers.
3. Position sensors:
These sensors measure the physical position of a device. It includes
orientation sensors and magnetometers.
Sensor Framework:
• Android allows us to get the raw data from these sensors by using
sensor framework
• To express data values or to collect data, the sensors in Android
devices uses a 3-axis coordinate system i.e. X, Y, and Z-axis
• The sensor framework is part of the android.hardware package and
includes SensorManager, Sensor, SensorEvent classes and
SensorEvenListener interface.
• SensorManager class is used to access the various Sensors in
Android. This class provides various methods for accessing and
listing sensors, registering and unregistering sensor event listeners,
and acquiring orientation information.
• Sensor class is used to create an instance of a specific sensor. This
class provides various methods to determine a sensor's
capabilities.
• SensorEvent class is used to create a sensor event object, which
provides information about a sensor event. A sensor event object
includes information such as the raw sensor data, the type of
sensor that generated the event, the accuracy of the data, and the
timestamp for the event.
• SensorEventListener interface has two callback methods that
receive notifications (sensor events) when sensor values change or
when sensor accuracy changes.
• Methods of SensorManager
1 getDefaultSensor(int type)
This method get the default sensor for a given type.
2 getInclination(float[] I)
This method computes the geomagnetic inclination angle in radians from
the inclination matrix.
3 registerListener(SensorListener listener, int sensors, int rate)
This method registers a listener for the sensor
4 unregisterListener(SensorEventListener listener, Sensor sensor)
This method unregisters a listener for the sensors with which it is
registered.
5 getOrientation(float[] R, float[] values)
This method computes the device's orientation based on the rotation
matrix.
6 getAltitude(float p0, float p)
This method computes the Altitude in meters from the atmospheric
pressure and the pressure at sea level.
7 getSensorList(int type)
return a list of sensors containing their name and version number
• Sensor types supported by the Android platform
Sensor Type Description Common Uses
TYPE_ACCELEROM Hardwar Measures the acceleration force Motion detection
ETER e that is applied to a device on all (shake, tilt, etc.).
three physical axes (x, y, and z),
including the force of gravity.
TYPE_AMBIENT_T Hardwar Measures the ambient room Monitoring air
EMPERATURE e temperature in degrees Celsius (°C). temperatures.
TYPE_GRAVITY Software Measures the force of gravity in Motion detection
or m/s 2
that is applied to a device on (shake, tilt, etc.).
Hardwar
e all three physical axes (x, y, z).
TYPE_GYROSCOPE Hardwar Measures a device's rate of rotation Rotation detection
e in rad/s around each of the three (spin, turn, etc.).
physical axes (x, y, and z).
TYPE_LIGHT Hardwar Measures the ambient light level Controlling screen
e (illumination) in lx. brightness.
TYPE_MAGNETIC_ Hardwar Measures the ambient geomagnetic Creating a compass.
FIELD e field for all three physical axes (x, y,
z) in μT.
TYPE_PRESSURE Hardwar Measures the ambient air pressure Monitoring air
e in hPa or mbar. pressure changes.
• Sensor types supported by the Android platform
Sensor Type Description Common Uses
TYPE_ORIENTATIO Software Measures degrees of rotation that a Determining device
N device makes around all three position.
physical axes (x, y, z).
TYPE_PROXIMITY Hardwar Measures the proximity of an object Phone position
e in cm relative to the view screen of during a call.
a device. This sensor is typically
used to determine whether a
handset is being held up to a
person's ear.
TYPE_RELATIVE_H Hardwar Measures the relative ambient Monitoring
UMIDITY e humidity in percent (%). dewpoint, absolute,
and relative
humidity.
TYPE_ROTATION_ Software Measures the orientation of a Motion detection
VECTOR or device by providing the three and rotation
Hardwar
e elements of the device's rotation detection.
vector.
Creation of Sensors
• Step1: Instantiate the Sensormanager as follows:
SensorManager sensorMgr =
(SensorManager)getSystemService(Context.SENSOR_SERVICE);
• Step2: use the Sensor class to instantiate the specific Sensor.
Sensor light =sensorMgr.getDefaultSensor(Sensor.TYPE_LIGHT);
• Step3:Register its listener
sensorMgr.registerListener(this,
light,SensorManager.SENSOR_DELAY_NORMAL);
• Step4:To listen to sensor events, implement SensorEventListener
interface in the activity and override two methods
onAccuracyChanged() and onSensorChanged()
• public void onAccuracyChanged(Sensor sensor, int accuracy) { }
public void onSensorChanged(SensorEvent event) { }
• Example of Sensor( Retrieving list of available sensors)
• (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
android:id="@+id/tv2"
android:layout_width="match_parent"
android:layout_height="match_paren"
android:layout_marginTop="151dp"
android:text=" List of Sensors available" />
</RelativeLayout>
• Example of Sensor( Retrieving list of available sensors)
• (MainActivity.java)
package com.example.sensorlistapp;

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
import java.util.List;

public class MainActivity extends Activity {

TextView tv;
SensorManager sensorMgr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

tv=findViewById(R.id.tv2);
sensorMgr=(SensorManager)getSystemService(SENSOR_SERVICE);

List<Sensor> list=sensorMgr.getSensorList(Sensor.TYPE_ALL);
for(int i=0;i<list.size();i++)
tv.append (list.get(i).getName()+"\n");
}
AsyncTask
• It is Asynchronous Task. AsyncTask is used to enable proper and
easy use of the UI thread.
• Android AsyncTask going to do background operation on
background thread and whose result is published on the UI thread
(main thread).
• AsyncTask help us to make communication between background
thread to main thread.
• AsyncTasks should ideally be used for short operations (a few
seconds at the most.)
• AsyncTask is defined using 3 generic types and 4 methods.
• 3 Generic Types of AsyncTask
1. Params : The type of the parameters sent to the task upon
execution
2. Progress : The type of the progress units published during the
background computation
3. Result : The type of the result of the background computation
• 4 methods of AsyncTask:
1. doInBackground(Params) :
– It is invoked on the background thread immediately after onPreExecute() finishes
its execution.
– Main purpose of this method is to perform the background operations
– we can send results multiple times to the UI thread by publishProgress()
method.
– The result of the operations must be returned and passed to the
onPostExecutes().
– These values will be published on the main UI thread in the
onProgressUpdate(Progress) method.
2. onPreExecute() :
– It invoked on the main UI thread before the task is executed.
3. onPostExecute(Result) :
– invoked on the main UI thread after the background operation finishes in the
doInBackground method
4. onProgressUpdate(Progress) :
– invoked on the main UI thread after a call to publishProgress(Progress)
– This method receives progress updates from doInBackground ()
– this method can use this progress update to update the UI thread
 Rules of AsyncTask:
– The AsyncTask instance must be created and invoked in the UI
thread. AsyncTask class is firstly executed using execute()
method.
– The methods overridden in the AsyncTask class should never be
called. They’re called automatically
– AsyncTask can be called only once. Executing it again will throw
an exception
• It eases the tension of developers from
1. Thread creation and termination.
2. UI thread synchronization and management.
 Creation of AsyncTask
• To use AsyncTask, create subclass of it. The parameters are the
following AsyncTask <TypeOfVarArgParams, ProgressValue,
ResultValue>.
• Syntax of AsyncTask class:
class MyAsyncTask extends AsyncTask<String, Integer, String>
{
protected Long doInBackground(String... params) {}
protected void onProgressUpdate(Integer... progress) {}
protected void onPostExecute(String result) {}
}
• Executions of AsyncTask class from main thread
MyAsyncTask dt=new MyAsyncTask();
dt.execute(“5”);
• Example of AsyncTask
• (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
<TextView android:id="@+id/bt"
android:id="@+id/tv1" android:layout_width="wrap_content"
android:layout_width="wrap_content" android:layout_height="0dp"
android:layout_height="wrap_content" android:layout_centerHorizontal="true"
android:layout_marginTop="110dp" android:layout_marginTop="200dp"
android:text="Enter time in seconds="/> android:text="Execute" />
<EditText
<TextView
android:id="@+id/et"
android:layout_width="wrap_content"
android:id="@+id/tv2"
android:layout_height="wrap_content" android:layout_width="wrap_content"
android:layout_marginLeft="150dp" android:layout_height="wrap_content"
android:layout_marginTop="100dp" android:layout_marginTop="250dp" />
android:ems="10" </RelativeLayout>
android:inputType="number" />
• Example of AysncTask
• (MainActivity.java)
package com.example.asyncapp;

import android.app.Activity;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.*;;

public class MainActivity extends Activity {

Button bt;
EditText et;
TextView tv2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et=findViewById(R.id.et);
bt=findViewById(R.id.bt);
tv2=findViewById(R.id.tv2);

bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MyAsyncTask task=new MyAsyncTask();
task.execute(et.getText().toString());
}
});
class MyAsyncTask extends @Override
AsyncTask<String,String,String> protected void
{ onProgressUpdate(String... values)
{
ProgressDialog pd; tv2.setText(values[0]);
String res;
}
@Override
@Override
protected void onPostExecute(String
protected void onPreExecute() {
result) {
pd=
pd.dismiss();
ProgressDialog.show(MainActivity.this,"Progress
tv2.setText(result);
Dialog","Wait for "+et.getText().toString()+" seconds");
}
}
@Override
}
protected String doInBackground(String... param) {
}

int time=Integer.parseInt(param[0])*1000;
try
{
Thread.sleep(time);
res="Slept for "+param[0]+" seconds";
}catch(InterruptedException ie){}

return res;
}
5.6 Camera
• The Android framework includes support for various cameras and
camera features available on devices, allowing us to capture
pictures and videos in applications.
• There are the two ways, in which we can use camera in our
application:
1. Using existing android camera application(Camera Intent)
2. Using Camera API provided by android

 Using existing android camera application


• MediaStore.ACTION_IMAGE_CAPTURE constant is used to capture
an image without creating instance of camera.
• This constant is passed as action to intent which launches an
existing camera application
• Ex:
Intent camIntent = new
Intent(MediaStore.ACTION_IMAGE_CAPTURE);
 Using Camera API provided by android
• Camera API classes are used to take pictures and to control device
cameras
• Camera API works in following ways:
1) Camera: It is the primary API for controlling device cameras. It is
used to take pictures or videos when you are building a camera
application.
2) SurfaceView: It is used to present a live camera preview to the
user.
3) MediaRecorder: It used to record video from the camera.
4) Intent: An intent action type
of MediaStore.ACTION_IMAGE_CAPTURE or MediaStore.ACTION_
VIDEO_CAPTURE can be used to capture images or videos without
directly using the Camera object.
 Manifest Declarations:
 Camera Permission - Application must request permission to use a
device camera
Adding Permission in the manifest file as
<uses-permission android:name="android.permission.CAMERA"/>

 Camera Features - Application must also declare use of camera features.


<uses-feature> tag is used to declare camera features used by
application

<uses-feature android:name="android.hardware.camera"
android:required="true" />

If android:required=”true”, application can not be installed on the devices


that doesn’t have camera feature.
android:required=”false”, application can be installed on the devices that
doesn’t have camera feature. Camera feature is optional.
 Storage Permission - If application saves images or videos to the
device's external storage
Adding storage permission in the manifest file as
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

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

 Audio Recording Permission - For recording audio with video


capture, application must request the audio capture permission.
<uses-permission
android:name="android.permission.RECORD_AUDIO" />
• The procedure for invoking a camera intent follows these general
steps:
• Compose a Camera Intent - Create an Intent that requests an
image or video, using one of these intent types:
– MediaStore.ACTION_IMAGE_CAPTURE
– MediaStore.ACTION_VIDEO_CAPTURE -
• Start the Camera Intent - Use the startActivityForResult() method
to execute the camera intent. After you start the intent, the
Camera application user interface appears on the device screen
and the user can take a picture or video.
• Receive the Intent Result - Set up an onActivityResult() method in
application to receive the callback and data from the camera
intent. When the user finishes taking a picture or video (or cancels
the operation), the system calls this method.
• Example of Image capture through Camera
• (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
android:id="@+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />

<Button
android:id="@+id/bt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true“
android:onClick=“takephoto”
android:text="Take a Photo"/>

</RelativeLayout>
• Example of Image capture through Camera
• (MainActivity.java)
package com.example.cameraapp;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class MainActivity extends Activity {

final int CAMERA_REQUEST = 5;

ImageView imageView;
Button photoButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

imageView = findViewById(R.id.imageView1);
photoButton = this.findViewById(R.id.bt);
public void takephoto(View v)
{

Intent camIntent = new


Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camIntent, CAMERA_REQUEST);

@Override
protected void onActivityResult(int requestCode, int resultCode,
@Nullable Intent data) {

if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {


Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}

}
Audio Capture
• The Android multimedia framework includes support for capturing
and encoding a variety of common audio and video formats.
• Record audio using the MediaRecorder APIs and Play it using
MediaPlayer APIs.
 Manifest Declarations
 Storage Permission - If application saves audios to the device's
external storage
Adding storage permission in the manifest file as
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

 Audio Recording Permission - For recording audio,application must


request the audio capture permission.
<uses-permission
android:name="android.permission.RECORD_AUDIO" />
 Steps to perform audio capture:
• Create a new instance of android.media.MediaRecorder.
Ex: MediaRecorder audiorec = new MediaRecorder();

• Set the audio source using setAudioSource().


Ex: audiorec.setAudioSource(MediaRecorder.AudioSource.MIC);

• Set output file format using setOutputFormat().


Ex: audiorec.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);

• Set output file name using setOutputFile().

• Set the audio encoder using setAudioEncoder().


Ex: audiorec.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);

• Call prepare() on the MediaRecorder instance.


• To start audio capture, call start().
• To stop audio capture, call stop().
• When you are done with the MediaRecorder instance, call release() on it.
• Example of Audio capture
• permission to be added in Manifest file

<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE"/>
• Example of audio capture and play
• (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<Button
android:id="@+id/btstart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:onClick="startRecord"
android:text="Record"/>

<Button
android:id="@+id/btstop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:layout_marginLeft="100dp"
android:onClick="stopRecord"
android:text="Stop"/>
<Button
android:id="@+id/btplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:layout_marginLeft="200dp"
android:onClick="playAudio"
android:text="Play"/>

<Button
android:id="@+id/btplaystop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:layout_marginLeft="300dp"
android:onClick="stopAudio"
android:text="Stop Player"/>

</RelativeLayout>
• Example of audio capture and play
• (MainActivity.java)
package com.example.audiocapture;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

MediaRecorder audiorec;
String mFileName;
MediaPlayer mp;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startRecord(View v)
{
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecord.3gp";
audiorec = new MediaRecorder();
audiorec.setAudioSource(MediaRecorder.AudioSource.MIC);
audiorec.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
audiorec.setOutputFile(mFileName);
audiorec.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
audiorec.prepare();
} catch (Exception e) { }
audiorec.start();

Toast.makeText(getApplicationContext(), "Recording Started", Toast.LENGTH_LONG).show();


}
public void stopRecord(View v)
{
if (audiorec == null)
Toast.makeText(getApplicationContext(), "Record playing finished", Toast.LENGTH_LONG).show();
else {
audiorec.stop();
audiorec.release();
audiorec = null;
Toast.makeText(getApplicationContext(), "Recording Stopped", Toast.LENGTH_LONG).show();
}
}
public void playAudio(View V)
{
mp = new MediaPlayer();
try {
mp.setDataSource(mFileName);
mp.prepare();
mp.start();
Toast.makeText(getApplicationContext(), "Recording Started playing", Toast.LENGTH_LONG).show();
}
catch (Exception e) { }
}
public void stopAudio(View v)
{
if(mp==null)
Toast.makeText(getApplicationContext(), "Record playing finished", Toast.LENGTH_LONG).show();
else {
mp.stop();
Toast.makeText(getApplicationContext(), "Recording Stopped playing", Toast.LENGTH_LONG).show();
}
}

}
5.7 Bluetooth
• The Android platform includes support for the Bluetooth network
stack.
• It allows a device to wirelessly exchange data with other Bluetooth
devices.
• The application framework provides access to the Bluetooth
functionality through the Android Bluetooth APIs
• Using the Bluetooth APIs, an Android application can perform the
following:
– Scan for other Bluetooth devices
– Query the local Bluetooth adapter for paired Bluetooth devices
– Connect to other devices through service discovery
– Transfer data to and from other devices
– Manage multiple connections
• Android provides BluetoothAdapter class to communicate with
Bluetooth. Create an object of this calling by calling the static
method getDefaultAdapter().
• BluetoothAdapter class provide 4 constants:

ACTION_REQUEST_ENABLE Used to enable the Bluetooth of your


device
ACTION_REQUEST_DISCOVERABL Used for turn on discovering of
E bluetooth. Default value of visible time
is 120 seconds.
ACTION_STATE_CHANGED Used to notify that Bluetooth state has
been changed
ACTION_FOUND Used for receiving information about
each device that is discovered
• BluetoothAdapter class has foll. methods:
enable() enables the adapter if not enabled
isEnabled() returns true if adapter is enabled
disable() disables the adapter
getName() returns the name of the Bluetooth adapter
setName(String name) changes the Bluetooth name
getState() returns the current state of the Bluetooth
Adapter.
startDiscovery() starts the discovery process of the Bluetooth
for 120 seconds.
getBondedDevices() Returns list of paired devices
• Steps to turn on and off bluetooth of device:
1. Create an object of BluetoothAdapter class using static method
getDefaultAdapter().
BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter();

2. Enable the Bluetooth of device using intent with Bluetooth


constant ACTION_REQUEST_ENABLE
Intent turnOn = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);

3. Disable Bluetooth of device using disable()


ba.disable()
• Example of Bluetooth
• permission to be added in Manifest file

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

android.permission.BLUETOOTH :
Allows applications to connect to paired bluetooth devices.

android.permission.BLUETOOTH_ADMIN:
Allows applications to discover and pair bluetooth devices.
• Example of Bluetooth(activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="35dp"
android:layout_centerHorizontal="true"
android:text="Bluetooth" />

<Button
android:id="@+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Turn On"
android:layout_alignParentLeft="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="50dp"
android:onClick="on" />
<Button
android:id="@+id/b2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Visible"
android:layout_alignParentLeft="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="100dp"
android:onClick="visible" />
<Button
android:id="@+id/b3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="150dp"
android:text="List Devices"
android:onClick="display" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="250dp"
android:id="@+id/tv1"
android:layout_marginLeft="20dp"
android:text="List of blutooth devices” />

<Button
android:id="@+id/b4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="200dp"
android:onClick="off"
android:text="Turn off" />
</RelativeLayout>
• Example of Bluetooth(MainActivity.java)
package com.example.bluetoothapp;

import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Set;

public class MainActivity extends Activity {


private BluetoothAdapter ba;
Set<BluetoothDevice> pairedDevices;
TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

tv = findViewById(R.id.tv1);
ba = BluetoothAdapter.getDefaultAdapter();
}

public void on(View v) {


if (ba == null) {
Toast.makeText(getApplicationContext(), "device not supported", Toast.LENGTH_SHORT).show();
finish();
} else {
if (!ba.isEnabled()) {
Intent bluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(bluetooth, 0);
} else {
Toast.makeText(getApplicationContext(), "Already on", Toast.LENGTH_SHORT).show();
public void visible(View v) {
Intent getvisible = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(getvisible, 1);
}

public void display(View v) {


pairedDevices = ba.getBondedDevices();

tv.setText("");
for (BluetoothDevice bt : pairedDevices) {
tv.append("\n" + bt.getName());
}
Toast.makeText(getApplicationContext(), "Showing Paired Devices",
Toast.LENGTH_SHORT).show();

}
public void off(View v) {
ba.disable();
Toast.makeText(getApplicationContext(), "Turn off", Toast.LENGTH_SHORT).show();
}
}
Animation
• Animation is the process of creating motion and shape change.
• Animations can be performed through either XML or android code
• Android includes different animation APIs depending type of
animation.
• For example:
– Animate bitmaps/ drawable animation
– Animate UI visibility and motion/ Property Animation
– Animate layout changes
– Animate between activities
• To animate a bitmap graphic such as an icon or illustration, use the
drawable animation APIs. Ex: animate a play button that
transforms into a pause button when it's tapped.
Property Animation
• To move, reveal, or hide views within the current layout, you can use
the property animation system provided by the android.
animation package. These APIs update the properties of View objects
over a period of time.
• For example, when you change the position properties, the view
moves across the screen. When you change the alpha property, the
view fades in or out.
• The property animation system is a robust framework that allows you
to animate almost anything
• A property animation changes a property's (a field in an object) value
over a specified length of time.
• With the property animation system, we can animate any property of
any object (Views and non-Views) and the object itself is actually
modified.
• Common Property animations:
– Change a view visibility with a crossfade
– Change a view visibility with a circular reveal
Characteristics of an property animation system :
• Duration: specify the duration of an animation. The default length is
300 ms.
• Time interpolation: specify how the values for the property are
calculated . We're only setting the starting point and the ending point.
Everything inbetween is interpolated automatically.
• Repeat count and behavior: can specify whether or not to have an
animation repeat when it reaches the end of a duration and how many
times to repeat the animation. You can also specify whether you want
the animation to play back in reverse. Setting it to reverse plays the
animation forwards then backwards repeatedly, until the number of
repeats is reached.
• Animator sets: group animations into logical sets that play together or
sequentially or after specified delays.
• Frame refresh delay: specify how often to refresh frames of animation.
The default is set to refresh every 10 ms, but the speed in which your
application can refresh frames is ultimately dependent on how busy the
system is overall and how fast the system can service the underlying
• XML animation attributes
• android:duration – Duration of the animation in which the
animation should complete
• android:startOffset – It is the waiting time before an animation
starts. This property is mainly used to perform multiple animations
in a sequential manner
• android:interpolator – It is the rate of change in animation.
• android:fillAfter – When set to true, the animation transformation
is applied after the animation is over. Default value is false.This
attribute should be use with <set> node
• android:repeatMode – This is useful when you want your
animation to be repeat
• android:repeatCount – This defines number of repetitions on
animation. If you set this value to infinite then animation will
repeat infinite times
• Basic steps to perform animation
1. Create xml that defines the animation
Create an xml file which defines type of animation to perform.
This file should be located under anim folder under res directory (res
⇒ anim ⇒ animation.xml).
2. Load the animation
create an object of Animation class. And load the xml
animation using AnimationUtils by calling loadAnimation function.
Animation animFadein =
AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.fade_in);
3. start the animation
Start animation by calling startAnimation on any UI
element by passing the type of animation
txtView.startAnimation(animFadein);
• Example of Animation(activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="@drawable/android_icon"/>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="clockwise"
android:text="Rotate Clockwise"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:onClick="zoomin"
android:text="Zoom In"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="zoomout"
android:text="Zoom Out"/>

</LinearLayout>
• Example of Animation(MainActivity.java)
package com.example.animationdemo;

import android.app. Activity;


import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

public class MainActivity extends Activity {

ImageView image;
Animation animation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView)findViewById(R.id.iv);
}

public void zoomin(View view) {

animation = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.zoomin);
image.startAnimation(animation);
}
public void zoomout(View view) {
animation = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.zoomout);
image.startAnimation(animation);
}
public void clockwise(View view) {
animation = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.clockwise);
image.startAnimation(animation);
}
• Example of Animation(/res/anim/zoomin.xml)
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
android:fillAfter="true" >

<scale
xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000"
android:fromXScale="1"
android:fromYScale="1"
android:pivotX="50%"
android:pivotY="50%"
android:toXScale="0.2"
android:toYScale="0.2" >
</scale>
</set>

• Example of Animation(/res/anim/zoomout.xml)
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
android:fillAfter="true" >

<scale
xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000"
android:fromXScale="1"
android:fromYScale="1"
android:pivotX="50%"
android:pivotY="50%"
android:toXScale=“3"
android:toYScale=“3" >
</scale>
• Example of Animation(/res/anim/clockwise.xml)
<?xml version="1.0" encoding="utf-8"?>
<set
xmlns:android="http://schemas.android.com/apk/res/android">

<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:duration="5000">
</rotate>

</set>
5.8 SQLite Database
• Android applications can have application databases powered by
SQLite
• android.database.sqlite package contains the SQLite database
management classes.
• Applications use these classes to manage private databases
• SQLite is -a Structure query base database,
open source, light weight, no network access , file-based,
cross-platform, Server less, embedded, standalone database.
• It support embedded relational database features.
• SQLite was designed to be a lightweight and simple database
engine that could be easily embedded into other applications
• Android SQLite comes with Android OS. It is “baked into” the
Android runtime, so every Android application can create its own
SQLite databases.

• SQLite is not used to store files.
• SQLite was created in the year 2000 .
• SQLite database files have a maximum size of about 140 TB.
• On a phone, the size of the storage (a few GB) will limit database
file size.
• Steps for using SQLite databases:
1. Create a database
2. Open the database
3. Create a table
4. Create and insert interface for datasets
5. Create a query interface for datasets
6. Close the database
Database - Creation
• To create a database, instantiate the SQLiteDatabase by calling
openDatabase() or openOrCreateDatabase() method.
• Syntax:
1. SQLiteDatabase openOrCreateDatabase(String db,int
mode,CursorFactory obj)

2. SQLiteDatabase openOrCreateDatabase(String db,int


mode,CursorFactory obj, DatabaseErrorHandler errorHandler)

3. SQLiteDatabase openDatabase(String db,CursorFactory obj,int


mode)

4. SQLiteDatabase openDatabase(String db,CursorFactory obj, int


mode, DatabaseErrorHandler errorHandler)

• openDatabase() method only opens the existing database with the


appropriate flag mode.
• openOrCreateDatabase() create a new database if it is not exists.
• Ex:
SQLiteDatabase mydb =
openOrCreateDatabase("studentDB",MODE_PRIVATE,null);
• method is used to create a new database if it is not exists, or to open
the existing database at the provided location.
• MODE_PRIVATE used to declare that the created database file must
be local to the application only.
• Third parameter is a reference for CursorFactory object.

Creation of Table and Inserting data


• Create table or insert data into table using execSQL() method defined in
SQLiteDatabase class. execSQL() also used to update and modify the data in
table.
• Ex:
mydb.execSQL("CREATE TABLE IF NOT EXISTS Student(Name varchar, Rollno int);");
mydb.execSQL("INSERT INTO Student VALUES(‘xyz',1);");
mydb.execSQL("INSERT INTO Student VALUES(‘”+name+”',”+roll+”);");
Fetching from database
• To retrieve data from database object of the Cursor class is
used.
• A Cursor represents the entire result set of the query.
• call a method of SQLiteDatabase 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.
• Ex:
Cursor resultSet = mydb.rawQuery("Select * from Student",null);
resultSet.moveToFirst();
String name = resultSet.getString(0);
Int rollno = resultSet.getInt(1);
• Methods of Cursor class
close() Closes the Cursor,
getColumnCount() Return total number of columns
getColumnIndex(String columnName Returns the index for the given column
) name, or -1 if the column doesn't exist.
getColumnName(int columnIndex) Returns the column name at the given
zero-based column index.
getColumnNames() Returns a string array holding the names
of all of the columns in the result set
getCount() Returns the numbers of rows in the
cursor.
getPosition() Returns the current position of the cursor
in the row set.
getDouble(int columnIndex) Returns the value of the column as a
double.
getLong(int columnIndex) Returns the value of the column as a long.
getInt(int columnIndex) Returns the value of the column as a int.
getFloat(int columnIndex) Returns the value of the column as a float.
move(int offset) Move the cursor by a relative amount,
forward or backward, from the current
position.
moveToFirst() Move the cursor to the first row.
moveToLast() Move the cursor to the last row.
moveToNext() Move the cursor to the next row.

moveToPosition(int position) Move the cursor to an absolute position.


moveToPrevious() Move the cursor to the previous row.
Database Helper class
• For managing all the operations related to the database , an
helper class called SQLiteOpenHelper is used.
• It automatically manages the creation and update of the
database.
• Constructor:
SQLiteOpenHelper (Context context, String name, SQLiteDatabase.
CursorFactory factory, int version)
• Syntax:
public class DBHelper extends SQLiteOpenHelper
{
public DBHelper()
{ super(context,DATABASE_NAME,null,1);
}
public void onCreate(SQLiteDatabase db) {}
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion)
{}
}
Methods Of SQLiteDatabase

Method Description
void execSQL(String sql) executes the sql query not select
query.
long insert(String table, String inserts a record on the database.
nullColumn, ContentValues values) The table specifies the table name,
nullColumn doesn't allow completely
null values. If second argument is
null, android will store null values if
values are empty. The third
argument specifies the values to be
stored.
int update(String table, updates a row.
ContentValues values, String
whereClause, String[] whereArgs)
Cursor query(String table, String[] returns a cursor over the resultset.
columns, String selection, String[]
selectionArgs, String groupBy, String
having, String orderBy)
 Creation of DBHelper by extending SQLiteOpenHelper class
public class DBHelper extends SQLiteOpenHelper
{
private String CREATE_USER_TABLE = "CREATE TABLE User(User_id INTEGER
PRIMARY KEY AUTOINCREMENT,Username varchar,Password varchar)";

private String DROP_USER_TABLE="DROP TABLE IF EXISTS User";

public DBHelper(@Nullable Context context) {


super(context, "LoginDB", null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_USER_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_USER_TABLE);

onCreate(db);
}
 Inserting Record using insert()
public void addUser(String uname,String pwd)
{
SQLiteDatabase db=getWritableDatabase();
ContentValues val=new ContentValues();

val.put("Username",uname);
val.put("Password",pwd);

db.insert("User",null,val);
db.close();
}
 Updating Record using update()
public void updateUser(String uname,String pwd)
{
SQLiteDatabase db=getWritableDatabase();
ContentValues val=new ContentValues();

val.put("Username",uname);
val.put("Password",pwd);

db.update(“User” , val,“User_id = ?", new String[] {“1”});


db.close();
}
 deleting Record using delete()
public void deleteUser() {
SQLiteDatabase db = getWritableDatabase();
db.delete(“User”, ”User_id = ?", new String[] { ”1”});
db.close();
}
 Searching/Fetching Record from cursor using query
public boolean checkUser(String uname,String pwd)
{
SQLiteDatabase db=getReadableDatabase();

String columns[]={"Username","Password"};
String where="Username= ? and Password= ?";
String whereValues[]={uname,pwd};
Cursor cursor=db.query("User",columns,where,whereValues,null,null,null);

if(cursor.getCount()==0) // UserName Not Exist


{
cursor.close();
return false;

}
else {
cursor.moveToFirst();
String un=cursor.getString(0);
String pw=cursor.getString(1);
cursor.close();
return true;
}
• Example of SQLiteDatabse without SQULiteOpenHelper class(activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:text="Student Details"
android:layout_centerHorizontal="true"
android:textSize="30sp" />

<EditText
android:id="@+id/rollno"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="60dp"
android:hint="Enter Roll no...."
android:inputType="number"
android:textSize="20sp" />

<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Name..."
android:layout_marginTop="90dp"
android:inputType="text"
android:textSize="20sp" />
<EditText
<Button
android:id="@+id/marks" android:id="@+id/view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:hint="Enter Marks..." android:layout_height="wrap_content"
android:layout_marginTop="120dp"
android:inputType="number"
android:layout_marginTop="240dp"
android:textSize="20sp" /> android:layout_marginLeft="50dp"
<Button android:text="View"
android:id="@+id/add"
android:layout_width="wrap_content" android:textSize="20sp"
android:layout_height="wrap_content" android:onClick="view" />
android:layout_marginTop="180dp"
android:layout_marginLeft="20dp"
android:text="Add" <Button
android:textSize="20sp"
android:onClick="add" />
android:id="@+id/viewall"
android:layout_width="wrap_content"
<Button android:layout_height="wrap_content"
android:id="@+id/delete"
android:layout_width="wrap_content" android:layout_marginTop="240dp"
android:layout_height="wrap_content" android:layout_marginLeft="150dp"
android:layout_marginTop="180dp"
android:layout_marginLeft="110dp" android:text="View All"
android:text="Delete" android:textSize="20sp"
android:textSize="20sp"
android:onClick="delete" /> android:onClick="viewall" />

<Button </RelativeLayout>
android:id="@+id/update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="180dp"
android:layout_marginLeft="200dp"
android:text="Update"
android:textSize="20sp"
android:onClick="update" />
• Example of SQLiteDatabse without SQULiteOpenHelper
class(MainActivity.java)
package com.example.dbdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

SQLiteDatabase db;

EditText etroll,etname,etmarks;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

etroll=findViewById(R.id.rollno);
etname=findViewById(R.id.name);
etmarks=findViewById(R.id.marks);

db=openOrCreateDatabase("StudentDB", Context.MODE_PRIVATE,null);

db.execSQL("CREATE TABLE IF NOT EXISTS Student(RollNo int,Name varchar,Marks int);");


public void add(View v) {
if (etroll.getText().toString().trim().length() == 0 ||
etname.getText().toString().trim().length() == 0 ||
etmarks.getText().toString().trim().length() == 0) {
showMessage("Error", "Please enter all values");
return;
}
else
{
int roll = Integer.parseInt(etroll.getText().toString().trim());
String name = etname.getText().toString().trim();
int marks = Integer.parseInt(etmarks.getText().toString().trim());

db.execSQL("INSERT INTO Student values("+roll+",'"+name+"',"+marks+");");

showMessage("Success","Record Added Successfully");


clearText();
}
}
public void delete(View v) {

if(etroll.getText().toString().trim().length()==0)
{
showMessage("Error","Please Enter Rollno of the record to be deleted");
return;
}
else
{
int roll=Integer.parseInt(etroll.getText().toString().trim());
db.execSQL("DELETE FROM Student WHERE RollNo="+roll);
showMessage("Success","Record Deleted Successfully");
}
clearText();

}
public void update(View v) {

if(etroll.getText().toString().trim().length()==0)
{
showMessage("Error","Please Enter Rollno of the record to be updated");
return;
}
else
{
int roll=Integer.parseInt(etroll.getText().toString().trim());
String name = etname.getText().toString().trim();
db.execSQL("UPDATE Student SET Name='"+name+"' WHERE RollNo="+roll);
showMessage("Success","Record updated Successfully");
}
clearText();
}
public void view(View v) {

if(etroll.getText().toString().trim().length()==0)
{
showMessage("Error","Please Enter Rollno of the record to be viewed");
return;
}
else
{
int roll=Integer.parseInt(etroll.getText().toString().trim());
Cursor resultset=db.rawQuery("SELECT * FROM Student WHERE RollNo="+roll,null);
if(resultset.getCount()==0)
{
showMessage("Error", "No records found");
return;
}
else {
String data=new String();
while (resultset.moveToNext()) {
data+="RollNo="+resultset.getInt(0);
data+="\nName="+resultset.getString(1);
data+="\nMarks="+resultset.getInt(2);
}
showMessage("Student Details",data);
}
}
clearText();
}
public void viewall(View v) {

Cursor resultset=db.rawQuery("SELECT * FROM Student",null);


if(resultset.getCount()==0)
{
showMessage("Error", "No records found");
return;
}
else {
String data=new String();
while (resultset.moveToNext()) {
data+="RollNo="+resultset.getInt(0);
data+="\nName="+resultset.getString(1);
data+="\nMarks="+resultset.getInt(2);

data+="\n";
}
showMessage("All Student Details",data);
}
}
void showMessage(String title,String msg)
{
AlertDialog.Builder alert=new AlertDialog.Builder(this);
alert.setCancelable(true);
alert.setTitle(title);
alert.setMessage(msg);
alert.show();
}
void clearText()
{
etroll.setText("");
etname.setText("");
etmarks.setText("");
}
}
Transactions
• A sequence of operations performed as a single logical unit of
work is known as transaction.
• Database operation which are held between the beginning and
end transaction statements are considered as a single logical
transaction.
• During the transaction the database is inconsistent state. Only
once the database is committed the state is changed from
inconsistent state to consistent state .
• In order to maintain consistency in a database, before and after
the transaction, transactions must be atomic, consistent, isolated
and durable(ACID)
• If the database were in an inconsistent state before a transaction,
it would remain in the inconsistent state after the transaction.
• SQLiteDatabase class contains the following methods to support
transaction processing:
1. void beginTransaction(): Begins a transaction
2. void setTransactionSuccessful(): Indicates that the transaction
should be committed
3. void endTransaction(): Ends the transaction causing a commit
if setTransactionSuccessful() has been called
 Using Transaction:
• A transaction is started with the beginTransaction() method.
• Once a transaction is started, calls to any of the data manipulation method
calls (insert(), update(), delete()) may be made.
• Once all of the manipulation calls have been made, the transaction is ended
with endTransaction().
• To mark the transaction as successful, allowing all the operations to be
committed, setTransactionSuccessful() must be called before the call
to endTransaction() is made.
• If endTransaction() is called without a call to setTransactionSuccessful(), the
transaction will be rolled back
• For Ex: SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
// insert/update/delete
db.setTransactionSuccessful();
}
finally { db.endTransaction(); }
 ACID properties
• For maintaining the integrity of data, the DBMS system you have
to ensure ACID properties.
• ACID stands for Atomicity, Consistency, Isolation, and Durability.

You might also like