Chapter 5MAD
Chapter 5MAD
• 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
<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
<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;
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Explict Intent Example
<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”
or programmatically
IntentFilter filter=new
IntentFilter(Intent.ACTION_POWER_CONNECTED);
registerReceiver(new MyReceiver(), filter);
BroadcastReceiver Example
<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;
MyReceiver receiver;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
receiver=new MyReceiver();
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
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()
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;
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();
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.
<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);
<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;
@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;
MediaPlayer mp;
• (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
<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.
<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;
VideoView videoView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videoView=findViewById(R.id.videoview);
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
<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;
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);
@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;
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.*;;
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
<uses-feature android:name="android.hardware.camera"
android:required="true" />
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE" />
<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;
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)
{
@Override
protected void onActivityResult(int requestCode, int resultCode,
@Nullable Intent data) {
}
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" />
<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;
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();
}
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:
<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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = findViewById(R.id.tv1);
ba = BluetoothAdapter.getDefaultAdapter();
}
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;
ImageView image;
Animation animation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView)findViewById(R.id.iv);
}
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)
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)";
@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);
String columns[]={"Username","Password"};
String where="Username= ? and Password= ?";
String whereValues[]={uname,pwd};
Cursor cursor=db.query("User",columns,where,whereValues,null,null,null);
}
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;
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);
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) {
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.