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

Unit 5

The document discusses Android intents, activities, fragments, and broadcast receivers. Intents are messages passed between Android components and are used to start activities, services, and broadcast receivers. The document covers explicit and implicit intents as well as system-generated and custom intents. It also describes the Android activity lifecycle methods and how fragments allow dividing an activity into modular sections.

Uploaded by

Vinayak Patil
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Unit 5

The document discusses Android intents, activities, fragments, and broadcast receivers. Intents are messages passed between Android components and are used to start activities, services, and broadcast receivers. The document covers explicit and implicit intents as well as system-generated and custom intents. It also describes the Android activity lifecycle methods and how fragments allow dividing an activity into modular sections.

Uploaded by

Vinayak Patil
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 83

Unit No.

5
Activity and multimedia with
database
Intent
• Android Intent is the message that is passed between components such as activities, content providers,
broadcast receivers, services etc.

• It is generally used with startActivity() method to invoke activity, broadcast receivers etc.

• The dictionary meaning of intent is intention or purpose. So, it can be described as the intention to do
action.

• The LabeledIntent is the subclass of android.content.Intent class.

• Android intents are mainly used to:


Start the service
Launch an activity
Display a web page
Display a list of contacts
Broadcast a message
Dial a phone call etc.
Types of Android Intents

There are two types of intents in android: implicit and explicit.


1) Implicit Intent
Implicit Intent doesn't specifiy the component. In such case, intent provides information of available
components provided by the system that is to be invoked.
For example, you may write the following code to view the webpage.
Intent intent=new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.javatpoint.com"));
startActivity(intent);

2) Explicit Intent
Explicit Intent specifies the component. In such case, intent provides the external class to be
invoked.
Intent i = new Intent(getApplicationContext(), ActivityTwo.class);
startActivity(i);
Activity Lifecycle:-
• Android Activity Lifecycle is controlled by 7 methods
of android.app.Activity class. The android Activity is
the subclass of ContextThemeWrapper class.

• An activity is the single screen in android. It is like


window or frame of Java.

• By the help of activity, you can place all your UI


components or widgets in a single screen.

• The 7 lifecycle method of Activity describes how


activity will behave at different states.
Android Activity Lifecycle methods

Method Description
onCreate called when activity is first created.
onStart called when activity is becoming visible to the user.
onResume called when activity will start interacting with the user.
onPause called when activity is not visible to the user.
onStop called when activity is no longer visible to the user.
onRestart called after your activity is stopped, prior to start.
onDestroy called before the activity is destroyed.
Method Description
onCreate called when activity is first created.
not visible yet Syntax Of onCreate()
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); //the activity is being created.
}

onStart called when activity is becoming visible to the user.


visible Syntax of onStart()
@Override
protected void onStart()
{
super.onStart(); //the activity is about to become visible.
}
Method Description
onResume called when activity will start interacting with the user.
visible Syntax of onResume()
@Override
protected void onResume()
{
super.onResume();//the activity has become visible
}
onPause called when activity is not visible to the user.
invisible Syntax of onPause()
@Override
protected void onPause()
{
super.onPause(); //the activity is paused.
}
Method Description
onRestart called after your activity is stopped, prior to start.
not visible Syntax of onRestart()
@Override
protected void onRestart()
{
super.onRestart(); //the activity is between stopped and started.
}
onStop called when activity is no longer visible to the user.
hidden Syntax of onStop()
@Override
protected void onStop()
{
super.onStop(); //the activity is stopped.
}
Method Description
onDestroy called before the activity is destroyed.
(gone from Syntax of onDestroy()
memory) @Override
protected void onDestroy()
{
super.onDestroy(); //the activity is about to be destroyed
}
Broadcast Lifecycle

The Android system controls the life cycle of a broadcast receiver. It starts the receiver when an intent is
broadcast and then kills it once the onReceive() method returns. The system may also kill a receiver if it
has been idle for too long.
Broadcast Receiver

• Broadcast Receivers simply respond to broadcast messages from other applications or from the
system itself. These messages are sometime called events or intents.
• For example, applications can also initiate broadcasts to let other applications know that some
data has been downloaded to the device and is available for them to use, so this is broadcast
receiver who will intercept this communication and will initiate appropriate action.
There are following two important steps to make BroadcastReceiver works for the system
broadcasted intents −
● Creating the Broadcast Receiver.
● Registering Broadcast Receiver
There is one additional steps in case you are going to implement your custom intents then you will
have to create and broadcast those intents.
Creating the Broadcast Receiver

A broadcast receiver is implemented as a subclass of BroadcastReceiver class and overriding the


onReceive() method where each message is received as a Intent object parameter.

public class MyReceiver extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
}
}
Registering Broadcast Receiver
An application listens for specific broadcast intents by registering a broadcast receiver in AndroidManifest.xml file.
Consider we are going to register MyReceiver for system generated event ACTION_BOOT_COMPLETED which is fired by
the system once the Android system has completed the boot process.
Broadcast-Receiver

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name="MyReceiver">

<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED">
</action>
</intent-filter>

</receiver>
</application>
Now whenever your Android device gets booted, it will be intercepted by BroadcastReceiver MyReceiver and
implemented logic inside onReceive() will be executed.
Intent filter
An intent filter declares the capabilities of its parent component — what an activity or service can
do and what types of broadcasts a receiver can handle.

What is difference between intent and intent filter in android?


An intent is an object that can hold the os or other app activity and its data in uri form. It is started
using startActivity(intent-obj)
IntentFilter can fetch activity information on os or other app activities.
There are several system generated events defined as final static fields in the Intent class. The following table lists a few
important system events.
Sr.No Event Constant & Description
android.intent.action.BATTERY_CHANGED
1
Sticky broadcast containing the charging state, level, and other information about the battery.
android.intent.action.BATTERY_LOW
2
Indicates low battery condition on the device.
android.intent.action.BATTERY_OKAY
3
Indicates the battery is now okay after being low.
android.intent.action.BOOT_COMPLETED
4
This is broadcast once, after the system has finished booting.
android.intent.action.BUG_REPORT
5
Show activity for reporting a bug.
android.intent.action.CALL
6
Perform a call to someone specified by the data.
android.intent.action.CALL_BUTTON
7
The user pressed the "call" button to go to the dialer or other appropriate UI for placing a call.
android.intent.action.DATE_CHANGED
8
The date has changed.
android.intent.action.REBOOT
9
Have the device reboot.
Broadcasting Custom Intents
If you want your application itself should generate and send custom intents then you will have to create and send
those intents by using the sendBroadcast() method inside your activity class. If you use
the sendStickyBroadcast(Intent) method, the Intent is sticky, meaning the Intent you are sending stays around after
the broadcast is complete.
public void broadcastIntent(View view) {
Intent intent = new Intent();
intent.setAction("com.tutorialspoint.CUSTOM_INTENT");
sendBroadcast(intent);
}
This intent com.tutorialspoint.CUSTOM_INTENT can also be registered in similar way as we have registered
system generated intent.
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name="MyReceiver">

<intent-filter>
<action android:name="com.tutorialspoint.CUSTOM_INTENT">
</action>
</intent-filter>
</receiver>
</application>
Fragments
Android Fragment is the part of activity, it is also known as sub-activity. There can be
more than one fragment in an activity.
Fragments represent multiple screen inside one activity.
• A Fragment is a piece of an activity which enable more modular activity design.
• a fragment is a kind of sub-activity.
• A fragment has its own layout and its own behavior with its own life cycle callbacks.
• You can add or remove fragments in an activity while the activity is running.
• You can combine multiple fragments in a single activity to build a multi-pane UI.
• A fragment can be used in multiple activities.
• Fragment life cycle is closely related to the life cycle of its host activity which means when
the activity is paused, all the fragments available in the activity will also be stopped.
• A fragment can implement a behavior that has no user interface component.
• Fragments were added to the Android API in Honeycomb version of Android which API
version 11.
• You create fragments by extending Fragment class and You can insert a fragment into your
activity layout by declaring the fragment in the activity's layout file, as
a <fragment> element.
• The FragmentManager class is responsible to make interaction between fragment objects.
Fragment Life Cycle
● onAttach()The fragment instance is associated with an activity instance.The fragment and the
activity is not fully initialized. Typically you get in this method a reference to the activity which uses
the fragment for further initialization work.
● onCreate() The system calls this method when creating the fragment. You should initialize
essential components of the fragment that you want to retain when the fragment is paused or
stopped, then resumed.
● onCreateView() The system calls this callback when it's time for the fragment to draw its user
interface for the first time. To draw a UI for your fragment, you must return a View component
from this method that is the root of your fragment's layout. You can return null if the fragment does
not provide a UI.

● onActivityCreated() The onActivityCreated() is called after the onCreateView() method when the
host activity is created. Activity and fragment instance have been created as well as the view
hierarchy of the activity. At this point, view can be accessed with the findViewById() method.
example. In this method you can instantiate objects which require a Context object
● onResume()Fragment becomes active.
● onPause() The system calls this method as the first indication that the user is leaving the
fragment. This is usually where you should commit any changes that should be persisted beyond
the current user session.
● onStop()Fragment going to be stopped by calling onStop()
● onDestroyView()Fragment view will destroy after call this method
● onDestroy() onDestroy() called to do final clean up of the fragment's state but Not guaranteed
to be called by the Android platform.
Types of Fragments

● Single frame fragments − Single frame fragments are using for hand hold devices like mobiles,
here we can show only one fragment as a view.
● List fragments − fragments having special list view is called as list fragment
● Fragments transaction − Using with fragment transaction. we can move one fragment to
another fragment.
How to use Fragments?

steps to create Fragments.


● First of all decide how many fragments you want to use in an activity. For example let's we want to
use two fragments to handle landscape and portrait modes of the device.
● Next based on number of fragments, create classes which will extend the Fragment class. The
Fragment class has above mentioned callback functions. You can override any of the functions
based on your requirements.
● Corresponding to each fragment, you will need to create layout files in XML file. These files will
have layout for the defined fragments.
● Finally modify activity file to define the actual logic of replacing fragments based on your
requirement.
Service

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

A service can essentially take two states −

Sr.No. State & Description


1 Started
A service is started when an application component, such as an activity, starts it by
calling startService(). Once started, a service can run in the background indefinitely, even if the
component that started it is destroyed.

2 Bound
A service is bound when an application component binds to it by calling bindService(). A bound
service offers a client-server interface that allows components to interact with the service, send
requests, get results, and even do so across processes with interprocess communication (IPC).
A service life cycle
To create an service, you create a Java class that extends the Service base class or one of its existing subclasses. The
Service base class defines various callback methods and the most important are given below.
Sr.No. Callback & Description
1 onStartCommand()
The system calls this method when another component, such as an activity, requests that the service be
started, by calling startService(). If you implement this method, it is your responsibility to stop the
service when its work is done, by calling stopSelf() or stopService() methods.

2 onBind()
The system calls this method when another component wants to bind with the service by
calling bindService(). If you implement this method, you must provide an interface that clients use to
communicate with the service, by returning an IBinder object. You must always implement this method,
but if you don't want to allow binding, then you should return null.

3 onUnbind()
The system calls this method when all clients have disconnected from a particular interface published by
the service.
4 onRebind()
The system calls this method when new clients have connected to the service, after it had previously
been notified that all had disconnected in its onUnbind(Intent).

5 onCreate()
The system calls this method when the service is first created using onStartCommand() or onBind(). This
call is required to perform one-time set-up.

6 onDestroy()
The system calls this method when the service is no longer used and is being destroyed. Your service
should implement this to clean up any resources such as threads, registered listeners, receivers, etc.
Camera
The following two ways, in which you can use camera in your application
● Using existing android camera application in our application
● Directly using Camera API provided by android in our application

• Using existing android camera application in our application

You will use MediaStore.ACTION_IMAGE_CAPTURE to launch an existing camera application installed


on your phone. Its syntax is given below
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
Intents provided by MediaStore. They are listed as follows

Sr.No Intent type and description


ACTION_IMAGE_CAPTURE_SECURE:-It returns the image captured from the camera , when the
1 device is secured

ACTION_VIDEO_CAPTURE:-It calls the existing video application in android to capture video


2

EXTRA_SCREEN_ORIENTATION:-It is used to set the orientation of the screen to vertical or landscape


3

EXTRA_FULL_SCREEN:-It is used to control the user interface of the ViewImage


4

INTENT_ACTION_VIDEO_CAMERA:-This intent is used to launch the camera in the video mode


5

EXTRA_SIZE_LIMIT:-It is used to specify the size limit of video or image capture size
6
Use the function startActivityForResult() to launch this activity and wait for its result.
Its syntax is given below
startActivityForResult(intent,0)

This method has been defined in the activity class. We are calling it from main activity.
There are methods defined in the activity class that does the same job , but used when you are not calling from
the activity but from somewhere else. They are listed below
There are methods defined in the activity class that does the same job , but used when you are not calling from the activity
but from somewhere else. They are listed below

startActivityForResult(Intent intent, int requestCode, Bundle options)


1
It starts an activity , but can take extra bundle of options with it
startActivityFromChild(Activity child, Intent intent, int requestCode)
2
It launch the activity when your activity is child of any other activity
startActivityFromChild(Activity child, Intent intent, int requestCode, Bundle options)
3
It work same as above , but it can take extra values in the shape of bundle with it
startActivityFromFragment(Fragment fragment, Intent intent, int requestCode)
4
It launches activity from the fragment you are currently inside
startActivityFromFragment(Fragment fragment, Intent intent, int requestCode, Bundle options)
5
It not only launches the activity from the fragment , but can take extra values with it
Bluetooth

Bluetooth is a way to send or receive data between two different devices.


Android platform includes support for the Bluetooth framework that allows a device to wirelessly exchange
data with other Bluetooth devices.

Android provides Bluetooth API to perform these different operations.


● Scan for other Bluetooth devices
● Get a list of paired devices
● Connect to other devices through service discovery
Android provides BluetoothAdapter class to communicate with Bluetooth. Create an object of this calling
by calling the static method getDefaultAdapter().
Its syntax is given below.
private BluetoothAdapter BA;
BA = BluetoothAdapter.getDefaultAdapter();

In order to enable the Bluetooth of your device, call the intent with the following Bluetooth constant
ACTION_REQUEST_ENABLE.
Its syntax is.
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
Sr.No Constant & description
ACTION_REQUEST_DISCOVERABLE
1
This constant is used for turn on discovering of Bluetooth
ACTION_STATE_CHANGED
2
This constant will notify that Bluetooth state has been changed
ACTION_FOUND
3
This constant is used for receiving information about each device that is discovered
Once you enable the Bluetooth , you can get a list of paired devices by calling getBondedDevices() method. It
returns a set of bluetooth devices. Its syntax is.
private Set<BluetoothDevice>pairedDevices;
pairedDevices = BA.getBondedDevices();
A part form the parried Devices , there are other methods in the API that gives more control over Blueetooth.
Sr.No Method & description

1 enable() This method enables the adapter if not enabled

2 isEnabled() This method returns true if adapter is enabled

3 disable() This method disables the adapter

4 getName() This method returns the name of the Bluetooth adapter

5 setName(String name) This method changes the Bluetooth name

6 getState() This method returns the current state of the Bluetooth Adapter.

7 startDiscovery() This method starts the discovery process of the Bluetooth for 120 seconds.
Sensor
Most of the android devices have built-in sensors that measure motion, orientation, and various environmental
condition. The android platform supports three broad categories of sensors.

● Motion Sensors
● Environmental sensors
● Position sensors
Some of the sensors are hardware based and some are software based sensors.

Whatever the sensor is, android allows us to get the raw data from these sensors and use it in our application.
For this android provides us with some classes.
1. Android provides SensorManager and Sensor classes to use the sensors in our application. In order to use
sensors, first thing you need to do is to instantiate the object of SensorManager class. It can be achieved as
follows.
SensorManager sMgr;
sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE);
2. The next thing you need to do is to instantiate the object of Sensor class by calling the getDefaultSensor()
method of the SensorManager class. Its syntax is given below −
Sensor light;
light = sMgr.getDefaultSensor(Sensor.TYPE_LIGHT);
3. Once that sensor is declared , you need to register its listener and override two methods which are
onAccuracyChanged and onSensorChanged. Its syntax is as follows −
sMgr.registerListener(this, light,SensorManager.SENSOR_DELAY_NORMAL);
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
}
Getting list of sensors supported

You can get a list of sensors supported by your device by calling the getSensorList method, which will return a list
of sensors containing their name and version number and much more information. You can then iterate the list to
get the information.

Its syntax is given below −


sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE);
List<Sensor> list = sMgr.getSensorList(Sensor.TYPE_ALL);
for(Sensor sensor: list){
}
Other methods provided by the SensorManager class for managing sensors framework
Sr.No Method & description
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.
Animation
Animation is the process of creating motion and shape change

Animation in android is possible from many ways.


Tween Animation
Tween Animation takes some parameters such as start value , end value, size , time duration , rotation
angle e.t.c and perform the required animation on that object. It can be applied to any type of object. So in
order to use this , android has provided us a class called Animation.
In order to perform animation in android , we are going to call a static function loadAnimation() of the
class AnimationUtils. We are going to receive the result in an instance of Animation Object. Its syntax is as
follows −
Animation animation = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.myanimation);
Note:- the second parameter, It is the name of the our animation xml file. You have to create a new folder
called anim under res directory and make an xml file under anim folder.
Animation class has many useful functions

Sr.No Method & Description


start()
1
This method starts the animation.

setDuration(long duration)
2
This method sets the duration of an animation.

getDuration()
3
This method gets the duration which is set by above method

end()
4
This method ends the animation.

cancel()
5
This method cancels the animation.
In order to apply this animation to an object , we will just call the startAnimation() method of the
object. Its syntax is −
ImageView image1 = (ImageView)findViewById(R.id.imageView1);
image.startAnimation(animation);
Android Multimedia

 MediaPlayer:Audio
 VideoView: Video
 Recording Media
Android Media Player

• We can play and control the audio files in android by the help of MediaPlayer class.

MediaPlayer class
The android.media.MediaPlayer class is used to control the audio or video files.
Methods of MediaPlayer class

Method Description
public void setDataSource(String path) sets the data source (file path or http url) to use.
public void prepare() prepares the player for playback synchronously.
public void start() it starts or resumes the playback.
public void stop() it stops the playback.
public void pause() it pauses the playback.
public boolean isPlaying() checks if media player is playing.
public void seekTo(int millis) seeks to specified time in miliseconds.
public void setLooping(boolean looping) sets the player for looping or non-looping.
public boolean isLooping() checks if the player is looping or non-looping.
public void selectTrack(int index) it selects a track for the specified index.
public int getCurrentPosition() returns the current playback position.
public int getDuration() returns duration of the file.
public void setVolume(float leftVolume,float
rightVolume) sets the volume on this player.
Android Video Player

By the help of MediaController and VideoView classes, we can play the video files in
android.

MediaController class
The android.widget.MediaController is a view that contains media controls like
play/pause, previous, next, fast-forward, rewind etc.

VideoView class
The android.widget.VideoView class provides methods to play and control the video
player.
The commonly used methods of VideoView class are as follows:

Method Description
public void
setMediaController(MediaController sets the media controller to the video view.
controller)
public void setVideoURI (Uri uri) sets the URI of the video file.
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.
Android MediaRecorder

• MediaRecorder class can be used to record audio and video files.


• After recording the media, create a sound file that can be played later.
• Storing it in the external directory in 3gp format.
Android TextToSpeech

In android, you can convert your text into speech by the help of TextToSpeech
class. After completion of the conversion, you can playback or create the sound
file.
Constructor of TextToSpeech class
TextToSpeech(Context context, TextToSpeech.OnInitListener)
Methods of TextToSpeech class

Method Description
converts the text into speech. Queue Mode may be
int speak (String text, int queueMode, HashMap QUEUE_ADD or QUEUE_FLUSH. Request parameters
params) can be null, KEY_PARAM_STREAM,
KEY_PARAM_VALUME etc.
int setSpeechRate(float speed) it sets the speed for the speech.
int setPitch(float speed) it sets the pitch for the speech.
int setLanguage (Locale loc) it sets the locale specific language for the speech.
void shutdown() it releases the resource set by TextToSpeech Engine.
it interrupts the current utterance (whether played or
int stop() rendered to file) and discards other utterances in the
queue.
TextToSpeech.OnInitListener Interface

You need to implement TextToSpeech.OnInitListener interface, for performing event


handling on TextToSpeech engine.

Method of TextToSpeech.OnInitListener Interface


There is only one method in this interface.

Method Description
Called to signal the completion of the
void onInit (int status) TextToSpeech engine initialization. The
status can be SUCCESS or ERROR.
Android SpeechToText

• Android supports Google inbuilt text to speak API using


RecognizerIntent.ACTION_RECOGNIZE_SPEECH
• RecognizerIntent.ACTION_RECOGNIZE_SPEECH is used in the listener that starts an
activity that prompts the user for speech and send it through a speech recognizer.
• The results will be returned via activity results in the onActivityResult() method,
when the intent is started using startActivityForResult().
• In onActivityResult() method a list of strings is returned and the text is replaced with
it in the textview.
SQLite database
SQLite database

SQLite Database is an open-source database provided in Android which is used to store data
inside the user’s device in the form of a Text file.
We can perform so many operations on this data such as adding new data, updating,
reading, and deleting this data.
SQLite is an offline database that is locally stored in the user’s device and we do not have to
create any connection to connect to this database.
How Data is Being Stored in the SQLite Database?

Data is stored in the SQLite database in the form of tables.


When we stored this data in our SQLite database it is arranged in the form of tables that
are similar to that of an excel sheet.
Important Methods in SQLite Database

Method Description
This method is used to get the Array of column names of our SQLite
getColumnNames() table.

getCount() This method will return the number of rows in the cursor.
isClosed() This method returns a Boolean value when our cursor is closed.
getColumnCount() This method returns the total number of columns present in our table.
getColumnName(in This method will return the name of the column when we passed the
t columnIndex) index of our column in it.
getColumnIndex(Str This method will return the index of our column from the name of the
ing columnName) column.
getPosition() This method will return the current position of our cursor in our table.
Database - Package
The main package is android.database.sqlite that contains the classes to manage your own databases

Database - Creation
In order to create a database you just need to call this method openOrCreateDatabase with your database
name and mode as a parameter.
It returns an instance of SQLite database which you have to receive in your own object.
Its syntax is given below
SQLiteDatabase mydatabase = openOrCreateDatabase("your database name",MODE_PRIVATE,null);
functions available in the database package
Sr.No Method & Description
1 openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags, DatabaseErrorHandler
errorHandler)
This method only opens the existing database with the appropriate flag mode. The common flags
mode could be OPEN_READWRITE OPEN_READONLY

2 openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags)


It is similar to the above method as it also opens the existing database but it does not define any
handler to handle the errors of databases

3 openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory)


It not only opens but create the database if it not exists. This method is equivalent to openDatabase
method.

4 openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory)


This method is similar to above method but it takes the File object as a path rather then a string. It is
equivalent to file.getPath()
Database - Insertion
we can create table or insert data into table using execSQL method defined in SQLiteDatabase class.
Its syntax is given below
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS TutorialsPoint(Username VARCHAR,Password
VARCHAR);");
mydatabase.execSQL("INSERT INTO TutorialsPoint VALUES('admin','admin');");
This will insert some values into our table in our database.

Another method that also does the same job but take some additional parameter is given below

execSQL(String sql, Object[] bindArgs)


This method not only insert data , but also used to update or modify already existing data in database
using bind arguments
Database - Fetching
We can retrieve anything from database using an object of the Cursor class.
We will call a method of this class called rawQuery and it will return a resultset with the cursor
pointing to the table. We can move the cursor forward and retrieve the data.
Cursor resultSet = mydatbase.rawQuery("Select * from TutorialsPoint",null);
resultSet.moveToFirst();
String username = resultSet.getString(0);
String password = resultSet.getString(1);
There are other functions available in the Cursor class that allows us to effectively retrieve the data. That includes

Sr.No Method & Description


1 getColumnCount() This method return the total number of columns of the table.

2 getColumnIndex(String columnName) This method returns the index number of a column by


specifying the name of the column
3 getColumnName(int columnIndex) This method returns the name of the column by specifying the
index of the column
4 getColumnNames() This method returns the array of all the column names of the table.

5 getCount() This method returns the total number of rows in the cursor

6 getPosition() This method returns the current position of the cursor in the table

7 isClosed() This method returns true if the cursor is closed and return false otherwise
Database - Helper class
For managing all the operations related to the database , an helper class has been given and is called
SQLiteOpenHelper. It automatically manages the creation and update of the database.
Its syntax is given below
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)
{
}
}
SQLite - Transactions

A transaction is a unit of work that is performed against a database.


Transactions are units or sequences of work accomplished in a logical order,
whether in a manual fashion by a user or automatically by some sort of a
database program.
A transaction is the propagation of one or more changes to the database.
For example, if you are creating, updating, or deleting a record from the
table, then you are performing transaction on the table. It is important to
control transactions to ensure data integrity and to handle database errors.
Properties of Transactions (ACID Properties)
•Atomicity − Ensures that all operations within the work unit are completed
successfully; otherwise, the transaction is aborted at the point of failure and
previous operations are rolled back to their former state.
•Consistency − Ensures that the database properly changes states upon a
successfully committed transaction.
•Isolation − Enables transactions to operate independently of and transparent to
each other.
•Durability − Ensures that the result or effect of a committed transaction persists in
case of a system failure.
Transaction Control
following commands used to control transactions:
•BEGIN TRANSACTION − To start a transaction.
•COMMIT − To save the changes, alternatively you can use END TRANSACTION
command.
•ROLLBACK − To rollback the changes.

Transactional control commands are only used with DML commands INSERT, UPDATE,
and DELETE. They cannot be used while creating tables or dropping them because
these operations are automatically committed in the database.
BEGIN TRANSACTION Command

Transactions can be started using BEGIN TRANSACTION or simply BEGIN command.


Such transactions usually persist until the next COMMIT or ROLLBACK command is
encountered. However, a transaction will also ROLLBACK if the database is closed
or if an error occurs. Following is the simple syntax to start a transaction.

BEGIN;
or
BEGIN TRANSACTION;
COMMIT Command

COMMIT command is the transactional command used to save changes invoked by a


transaction to the database.

COMMIT command saves all transactions to the database since the last COMMIT or
ROLLBACK command.

Following is the syntax for COMMIT command.

COMMIT;
or
END TRANSACTION;
ROLLBACK Command

ROLLBACK command is the transactional command used to undo transactions that


have not already been saved to the database.

ROLLBACK command can only be used to undo transactions since the last COMMIT or
ROLLBACK command was issued.

Following is the syntax for ROLLBACK command.

ROLLBACK;
AsyncTasks in Android
• AsyncTask is an abstract class in Android that offers us the freedom to execute
demanding tasks in the background while keeping the UI thread light and the
application responsive.
• When launched, an Android application operates in a single thread. Due to this single-
thread approach, tasks that take a long time to fetch a response may cause the
program to become unresponsive.
• Android AsyncTask to perform these heavy tasks in the background on a separate
thread and return the results back to the UI thread in order to prevent this.
• As a result, the UI thread is always responsive when AsyncTask is used in an Android
application.
• The purpose of AsyncTask was to make it possible to use the UI thread correctly and
conveniently.
The three generic types utilized in an Android AsyncTask class:
•Params: Parameters sent to the task upon execution
•Progress: Progress units shared during the background computation
•Result: Result obtained from the background computation
The fundamental methods used in an Android AsyncTask class:

doInBackground():
The code that has to be run in the background is contained in the doInBackground() method.
The publishProgress() method in this method allows us to repeatedly deliver results to the UI
thread. We only need to use the return statements to signal that the background processing
has been finished.
onPreExecute():
The code that runs prior to the beginning of the background processing is contained in this
function.
onPostExecute():
After the doInBackground method has finished processing, the onPostExecute() method is
called. This method receives the output of the doInBackground method as its input.
onProgressUpdate():
This method can use the progress updates it receives from the publishProgress method,.
which publishes progress updates from the doInBackground function, to update the UI thread
Content Provider
Content Provider

• In Android, Content Providers are a very important component that serves the
purpose of a relational database to store the data of applications.
• The role of the content provider in the android system is like a central repository in
which data of the applications are stored, and it facilitates other applications to
securely access and modifies that data based on the user requirements.
• Android system allows the content provider to store the application data in several
ways. Users can manage to store the application data like images, audio, videos, and
personal contact information by storing them in SQLite Database, in files, or even on
a network.
• In order to share the data, content providers have certain permissions that are used
to grant or restrict the rights to other applications to interfere with the data.
• sometimes it is required to share data across applications. This is where
content providers become very useful.
• Content providers let you centralize content in one place and have many
different applications access it as needed.
• A content provider behaves very much like a database where you can query it,
edit its content, as well as add or delete content using insert(), update(), delete(),
and query() methods. In most cases this data is stored in an SQlite database.
• A content provider is implemented as a subclass of ContentProvider class and
must implement a standard set of APIs that enable other applications to perform
transactions.

public class My Application extends ContentProvider {


}
Content URI
Content URI(Uniform Resource Identifier) is the key concept of Content providers. To access
the data from a content provider, URI is used as a query string.

Structure of a Content URI: content://authority/optionalPath/optionalID

content:// – Mandatory part of the URI as it represents that the given URI is a Content URI.
authority – Signifies the name of the content provider like contacts, browser, etc. This part
must be unique for every content provider.
optionalPath – Specifies the type of data provided by the content provider. It is essential as
this part helps content providers to support different types of data that are not related to
each other like audio and video files.
optionalID – It is a numeric value that is used when there is a need to access a particular
record. If an ID is mentioned in a URI then it is an id-based URI otherwise a directory-based
URI.
Operations in Content Provider
Four fundamental operations
These operations are often termed as CRUD operations.

• Create: Operation to create data in a content provider.


• Read: Used to fetch data from a content provider.
• Update: To modify existing data.
• Delete: To remove existing data from the storage.
Working of the Content Provider
UI components of android applications like
Activity and Fragments use an object
CursorLoader to send query requests to
ContentResolver.
The ContentResolver object sends requests
(like create, read, update, and delete) to
the ContentProvider as a client.
After receiving a request, ContentProvider
process it and returns the desired result.
Below is a diagram to represent these
processes in pictorial form.
Creating a Content Provider
steps to create a Content Provider:
• Create a class in the same directory where the that MainActivity file resides and this
class must extend the ContentProvider base class.
• To access the content, define a content provider URI address.
• Create a database to store the application data.
• Implement the six abstract methods of ContentProvider class.
• Register the content provider in AndroidManifest.xml file using <provider> tag.
Here is the list of abstract methods which you need to override in Content Provider class to have your Content
Provider working −
• onCreate() As the content provider is created, the
android system calls this method immediately to initialise
the provider.
● query() This method receives a request from a client.
The result is returned as a Cursor object.
● insert()This method inserts a new record into the
content provider.
● delete() This method deletes an existing record from
the content provider.
● update() This method updates an existing record from
the content provider.
● getType() This method returns the MIME (Multipurpose
Internet Mail Extensiontype ) of the data at the given
URI.

You might also like