0% found this document useful (0 votes)
10 views49 pages

Unit 2

This document provides an overview of mobile application development focusing on Android, covering key components such as Activities, Intents, Content Providers, Broadcast Receivers, and Services. It details the Android Activity Lifecycle, including callback methods and their purposes, as well as how to pass data between activities using Intents. Additionally, it explains the use of Toasts for user feedback and the structure of XML manifest files in Android applications.

Uploaded by

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

Unit 2

This document provides an overview of mobile application development focusing on Android, covering key components such as Activities, Intents, Content Providers, Broadcast Receivers, and Services. It details the Android Activity Lifecycle, including callback methods and their purposes, as well as how to pass data between activities using Intents. Additionally, it explains the use of Toasts for user feedback and the structure of XML manifest files in Android applications.

Uploaded by

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

SCHOOL OF COMPUTING

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

UNIT- II Mobile Application Development – SBSA3003

UNIT 2
BUILDING BLOCKS AND DATABASES:
Introduction to Activities and Intents - Understanding Activity life cycle, Linking Activities, Passing Data,
Toast, Displaying a Dialog Window and Notifications. Content Provider, Services, Broadcast receivers,
accessing databases, Location and sensors, Multimedia audio, video and camera, Deploying and publishing
application.
Android Application Components

Application components are the basic building blocks of an application and these components
will act as an entry point to allow system or user to access our app. Basic core application
components that can be used in Android application.

❖ Activities

❖ Intents

❖ Content Providers

❖ Broadcast Receivers

❖ Services.

Android Components.

Basic core application components that can be used in Android application.

❖ Activities

❖ Intents

❖ Content Providers

❖ Broadcast Receivers

❖ Services

1. Activity

An activity is implemented as a subclass of activity class

public class MainActivity extends Activity{

2. Services

A Services is implemented as a subclass of Service class

Public class Myservice extends Service{

A Broadcast Receiver is implemented as a subclass of Broadcast Receiver class and


each message is broadcasted as an Intent object

Public class MyReceiver extends BroadcastReceiver{

}
3. A Content provider is implemented as a subclass of ComtentProvider class and must
implement a standard set of APIs that enable other applications to perform
transactions.

Public class MyContentProvider extends ContentProvider{ }

Introduction to Activity:

1. An Activity is an application component that provides a screen with which users


can interact in order to do something, such as dial the phone, take a photo, send
an email, or view a map.
2. Each activity is given a window in which to draw its user interface.
3. The window typically fills the screen, but may be smaller than the screen and
float on top of other windows.
Subclass of Activity class.
An activity is implemented as a subclass of class Activity.
public class MainActivity extends Activity {
}

Manifest XML FILE

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


<manifest …..>
<application …..>
<activity android:name=".MainActivity" >
…….

…….

</activity>

…….

</application>
</manifest>

Android Activity Lifecycle:

Android system initiates its program with in an Activity starting with a call
on onCreate() callback method. There is a sequence of callback methods that start up an
activity and a sequence of callback methods that tear down an activity.
Figure 2.1 Activity Sequence
Activity State
1.Doesn‟t exist State
2. Foreground State
3. Background State
4.Pause State

Figure 2.2 Activity Lifecycle

1. Running State

An activity is in the running state if it‟s shown in the foreground of the users‟ screen. Activity
is in the running state when the user is interacting with it.
2. Paused State

When an activity is not in the focus but is still alive for the user, it‟s in a paused state. The
activity comes in this state when some other activity comes in with a higher position in the
window.
3. Resumed State

It is when an activity goes from the paused state to the foreground that is an active state.
4. Stopped State

When an activity is no longer in the activity stack and not visible to the users.
Android Activity. Methods. Android activities go through four states during their entire
lifecycle. These activities have callback methods() to describe each activity in each of the
four stages. These methods need to be overridden by the implementing subclass. In Android,
we have the following 7 callback methods that activity uses to go through the four states:

1. onCreate()
2. onStart()
3. onPause()
4. onRestart()
5. onResume()
6. onStop()
7. onDestroy()
1. onCreate()

The Android oncreate() method is called at the very start when an activity is created. An
activity is created as soon as an application is opened. This method is used in order to create
an Activity.

@Override protected void onCreate(Bundle savedInstanceState)


{
super.onCreate(savedInstanceState);
...
}
2. onStart()

The Android onstart() method is invoked as soon as the activity becomes visible to the users.
This method is to start an activity. The activity comes on the forescreen of the users when this
method is invoked.

Syntax:
@Override protected void onStart()
{
super.onStart();
...
}

3. onPause()

The Android onPause() method is invoked when the activity doesn‟t receive any user input
and goes on hold. In the pause state, the activity is partially visible to the user. This is done
when the user presses the back or home buttons. Once an activity is in the pause state, it can
be followed by either onResume() or onStopped() callback method.
Syntax:
@Override protected void onPause()
{
super.onPause();
...
}

4. onRestart()

The Android onRestart() method is invoked when activity is about to start from the stop state.
This method is to restart an activity that had been active some time back. When an activity
restarts, it starts working from where it was paused.

Syntax:
@Override protected void onRestart()
{
super.onRestart();
...
}

5. onResume()

The Android onResume() method is invoked when the user starts interacting with the user.
This callback method is followed by onPause(). Most of the functionalities of an application
are implemented using onResume().
Syntax:
@Override protected void onResume()
{
super.onResume();
...
}

6. onStop()

The Android onStop() method is invoked when the activity is no longer visible to the user.
The reason for this state is either activity is getting destroyed or another existing activity
comes back to resume state.
Syntax:
@Override protected void onStop()
{
super.onStop();
...
}

7. onDestroy()

The Android onDestroy() is the method that is called when an activity finishes and the user
stops using it. It is the final callback method received by activity, as after this it is destroyed.
Syntax:
@Override protected void onDestroy()
{
super.onDestroy();
...
}

Figure 2.3 Android Activity Lifecycle

Android Activity Lifecycle Example

MainActivity.java

package example.javatpoint.com.activitylifecycle;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("lifecycle","onCreate invoked");
}
@Override
protected void onStart() {
super.onStart();
Log.d("lifecycle","onStart invoked");
}
@Override
protected void onResume() {
super.onResume();
Log.d("lifecycle","onResume invoked");
}
@Override
protected void onPause() {
super.onPause();
Log.d("lifecycle","onPause invoked");
}
@Override
protected void onStop() {
super.onStop();
Log.d("lifecycle","onStop invoked");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d("lifecycle","onRestart invoked");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("lifecycle","onDestroy invoked");
}
}

activity_main.xml

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


<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.co
m/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="example.javatpoint.com.activitylifecycle.MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Introduction to Intents:

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.

Uses of Intent in Android


There are three fundamental uses of intents:
1. To start an Activity
An represents a single screen in an app. You can start a new instance of an Activity by
passing an Intent to startActivity(). The Intent describes the activity to start and carries any
necessary data along.
2. To start a Service
A Service is a component that performs operations in the background and does not have a
user interface. You can start a service to perform a one-time operation(such as downloading a
file) by passing an Intent to startService(). The Intent describes which service to start and
carries any necessary data.
3. To deliver a Broadcast
A broadcast is a message that any app can receive. The system delivers various broadcasts for
system events, such as when the system boots up or the device starts charging. You can
deliver a broadcast to other apps by passing an Intent
to sendBroadcast() or sendOrderedBroadcast().
Types of Intents
In Android, there are two types of Intents:

1. Explicit Intents
2. Implicit Intents

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

Example:

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

Android Implicit Intent Example:


activity_main.xml

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


<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.co
m/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="example.javatpoint.com.implicitintent.MainActivity">

<EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="60dp"
android:ems="10"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.575"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="8dp"
android:layout_marginLeft="156dp"
android:layout_marginTop="172dp"
android:text="Visit"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editText" />
</android.support.constraint.ConstraintLayout>
MainActivity.java
package example.javatpoint.com.implicitintent;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {

Button button;
EditText editText;

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

button = findViewById(R.id.button);
editText = findViewById(R.id.editText);

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String url=editText.getText().toString();
Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
});
}
}
Linking Activity:
⮚ To start an Activity
An Activity represents a single screen in an app.start a new instance of an Activity by
passing an Intent to startActivity()
⮚ To start a Service
A Service is a component that performs operations in the background and does not
have a user interface. You can start a service to perform a one-time operation(such as
downloading a file) by passing an Intent to startService()
⮚ To deliver a Broadcast
A broadcast is a message that any app can receive. The system delivers various
broadcasts for system events, such as when the system boots up or the device starts
charging. You can deliver a broadcast to other apps by passing an Intent to
sendBroadcast() or sendOrderedBroadcast().

Launchable Android Provided Activities:


Open a browser window
public static void invokeWebBrowser(Activity activity)
{ Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.google.com"));
activity.startActivity(intent); }
Call a telephone number
public static void call(Activity activity)
{ Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:555-555-5555"));
activity.startActivity(intent); }
Present a phone dialer
public static void dial(Activity activity)
{ Intent intent = new Intent(Intent.ACTION_DIAL);
activity.startActivity(intent);
Building an intent:
⮚ Component name
⮚ Action
⮚ Data
⮚ Category
⮚ Extras
⮚ Flags
Bundling an Intent:
• Code to add bundleable objects
Bundle more = new Bundle(); // a bundle contains key/value pairs
more.putString("someKey", "someString");
intent.putExtra("bundleKey", more); // A bundle of extra items
intent.putExtra("anotherKey", 3.5); // A single extra item
• Updating the bundle
– If a bundle exists, Android adds additional key/data pairs
– If a bundle doesn't exist, create one and copy key/data pairs to it
• Overloaded putExtra() methods for adding
– booleans, ints, doubles, floats, strings, arrays, serializable objects, parcelable
objects, bundles, additional intents
Passing Data:
• Activity is used to represent the data to user and allows user interaction.
• In an android application, we can have multiple activities and that can interact with
each other.
• During activity interaction we might required to pass data from one activity to other.
• Data is passed as extras and are key/value pairs.
The key is always a String and the value you can use the primitive data types int, float, chars,
etc.
Syntax for sending and Retriving data:
• Sending data
Intent intent = new Intent(context, Your Activity Class . class);
intent.putExtra(KEY, <your value here>); startActivity(intent);
• Retrieving data Intent intent = getIntent();
String stringData= intent.getStringExtra(KEY);
int numberData = intent . getIntExtra(KEY , default Value) ;
boolean booleanData = intent.getBooleanExtra(KEY, defaultValue);
char charData = intent.getCharExtra(KEY, defaultValue);

Example:
public class MainActivity extends Activity implements OnClickListener {
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btnPassData);
btn.setOnClickListener(this);
}
@Override
public void onClick(View view) { Intent intent = new
Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("message", "Hello From Main Activity” );
startActivity(intent);}}
public class SecondActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another);
Intent intent = getIntent();
String msg = intent.getStringExtra("message"); Toast toast = Toast.makeText(this,
msg,Toast . LENGTH_ LONG);
toast.show();
}
}
Toasts:
• A toast provides simple feedback about an operation in a small popup. It only fills the
amount of space required for the message and the current activity remains visible and
interactive,Toasts automatically disappear after a timeout.
• First, instantiate a Toast object with one of the makeText() methods.
• This method takes three parameters: the application Context, the text message, and
the duration for the toast. It returns a properly initialized Toast object.
• You can display the toast notification with show()
• Context context = getApplicationContext(); CharSequence text = "Hello toast!";

int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context, text, duration); toast.show();

(or)

Toast.makeText(context, text, duration).show();

(or)

Toast.makeText(getApplicationContext(),”Hello toast!”,
Toast.LENGTH_“SHORT).show();

Positioning your Toast:


• A standard toast notification appears near the bottom of the
screen, centered horizontally.
• You can change this position with the setGravity(int, int, int) method.
• This accepts three parameters: a Gravity constant, an x-position offset, and a y-
position offset.
• Exmaple toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
Custom Toast:
• To create a customized layout for your toast notification.
• To create a custom layout, define a View layout, in XML or in your application
code, and pass the root View object to the setView(View) method.
Example:
<LinearLayout
android:id="@+id/toast_layout_root" android:orientation="horizontal"
android:layout_width="fill_parent" android:layout_height="fill_parent”>
<TextView
android:id="@+id/text" android:layout_width="wrap_content"
android:layout_height="wrap_content“ />
</LinearLayout>
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup) findViewById(R.id.toast_layout_root));
TextView text = (TextView) layout.findViewById(R.id.text); text.setText("This is a
custom toast");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG); toast.setView(layout);
toast.show();

Displaying Dialog Window:


• A dialog is a small window that prompts the user to make a decision or enter
additional information.
• Creating alert dialog is very easy.
• The Dialog class is the base class for dialogs, but you should avoid instantiating
Dialog directly.
• Instead, use one of the following subclass AlertDialog class
• Three regions of an alert dialog
• Title
This is optional and should be used only when the content area is
occupied by a detailed message.
• Content area
This can display a message.
• Action buttons
There should be no more than three action buttons in a dialog.
• Different action buttons
– Positive
• Use this to accept and continue with the action (the "OK" action).
– Negative
• Use this to cancel the action.
– Neutral
• Use this when the user may not want to proceed with
the action, but doesn't necessarily want to cancel.
• It appears between the positive and negative buttons.
• For example, the action might be "Remind me later."
• Different alert dialogue methods
• one button(ok button) - setPositiveButton()
• two buttons(yes or no buttons) - setNegativeButton()
• three buttons(yes, no and cancel buttons) -
setNeutralButton()
Example:
AlertDialog.Builder alertDialog = new AlertDialog .Builder (AlertDialog Activity.this) ;
// Setting Dialog Title
alertDialog.setTitle("Confirm Delete...");
// Setting Dialog Message
alertDialog.setMessage ("you want delete this” );
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.delete);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES", new Dialog Interface . OnClick Listener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to invoke YES event Toast.makeText(getApplicationContext(), "You
clicked on YES", Toast.LENGTH_SHORT).show();
}});
// Setting Negative "NO" Button alertDialog.setNegativeButton("NO", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to invoke NO event Toast.makeText(getApplicationContext(), "You
clicked
on NO", Toast.LENGTH_SHORT).show();
dialog.cancel();
}});
// Showing Alert Message
alertDialog.show();

Notification
• A notification is a message you can display to the user outside of your application's
normal UI.
• When you tell the system to issue a notification, itfirst
appears as an icon in the notification area.
• To see the details of the notification, the user opens
the notification drawer.
• Both the notification area and the notification drawer are system-controlled areas that
the user can view at any time.
Android Toast class provides a handy way to show users alerts but problem is that these
alerts are not persistent which means alert flashes on the screen for a few seconds and then
disappears.
Step 1 - Create Notification Builder
• A first step is to create a notification builder using
NotificationCompat.Builder.build().
• Use Notification Builder to set various Notification properties like its small and large
icons, title, priority etc.
• Syntax
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);

Step 2 - Setting Notification Properties:


• To set its Notification properties using Builder object as per your requirement.
– A small icon, set by setSmallIcon()
– A title, set by setContentTitle()
– Detail text, set by setContentText()
• Example mBuilder.setSmallIcon(R.drawable.notification_icon);
mBuilder.setContentTitle("Notification Alert, Click Me!");
mBuilder.setContentText("Hi, This is Android Notification Detail!");

Step 3 - Attach Actions:


• The action is defined by a PendingIntent containing an Intent that starts an Activity in
your application.
• A PendingIntent object helps you to perform an action on your applications behalf,
often at a later time, without caring of whether or not your application is running.
• We take help of stack builder object which will contain an artificial back stack for
the started Activity.
This ensures that navigating backward from the Activity leads out of your application to
the Home scrren.
Intent resultIntent = new Intent(this, ResultActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.this);
stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0,PendingIntent.FLAG
_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);

Step 4 - Issue the notification:


• Finally, you pass the Notification object to the system by calling
NotificationManager.notify() to send your notification.
• Make sure you call
NotificationCompat.Builder.build() method on builder object before notifying it.
• Example
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE)
mNotificationManager.notify(notificationID, mBuilder.build());
Example:
Button b; b=(Button)findViewById(R.id.notify_btn);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub Notify_method("Test notify message");
}
private void Notify_method(String string) {
NotificationManager notificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.abc,"New Message",
System.currentTimeMillis());
Intent notificationIntent = new
Intent(MainActivity.this,NotifyDisplay.class);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this,
0,notificationIntent, 0);
notification.setLatestEventInfo(MainActivity.this, "Notification",string,
pendingIntent);
notificationManager.notify(9999, notification);
}
});

Services:
• A service is a component that runs in the background to perform long-running
operations without needing to interact with the user and it works even if application
is destroyed.
• A service can essentially take two states
– 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.
• Android Services are the application components that run in the background. Service
is process that doesn‟t need any direct user interaction.
• As they perform long-running processes without user intervention, they have no User
Interface.
• They can be connected to other components and do inter-process communication
(IPC).
Figure 2.4 Android Services

1. Foreground Services

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.

2. Background Services

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

3. Bound Services

Bound service runs as long as some other application component is bound to it. Many
components can bind to one service at a time, but once they all unbind, the service will
destroy.

To bind an application component to the service, bindService() is used.

Bound

• A bound service is the server in a client-server interface. It allows components (such


as activities) to bind to the service, send requests, receive responses, and perform
interprocess communication (IPC).
• A bound service typically lives only while it serves another application component
and does not run in the background indefinitely.
• A bound service is an implementation of the Service class that allows other
applications to bind to it and interact with it.
• To provide binding for a service, you must implement the onBind() callback method.
This method returns an IBinder object that defines the programming interface that
clients can use to interact with the service.
Binding Methods

1.onBind()

2. bindService()

3. serviceConnection()

4. onstartCommand()

5. onService Connected()

Lifecycle of Android Services

Android services life-cycle can have two forms of services and they follow two paths, that
are:

• Started Service
• Bounded Service

1. Started Service

• A service becomes started only when an application component calls startService(). It


performs a single operation and doesn‟t return any result to the caller. Once this
service starts, it runs in the background even if the component that created it destroys.
This service can be stopped only in one of the two cases:

 By using the stopService() method.


 By stopping itself using the stopSelf() method.

2. Bound Service

• A service is bound only if an application component binds to it using bindService(). It


gives a client-server relation that lets the components interact with the service. The
components can send requests to services and get results.
• This service runs in the background as long as another application is bound to it. Or it
can be unbound according to our requirement by using the unbindService() method.

IntentService()

• There‟s an additional service class, that extends Service class, IntentService Class. It
is a base class for services to handle asynchronous requests.
• It enables running an operation on a single background. It executes long-running
programs without affecting any user‟s interface interaction.
• Intent services run and execute in the background and terminate themself as soon as
they are executed completely.

Certain important features of Intent are :

• It queues up the upcoming request and executes them one by one.


• Once the queue is empty it stops itself, without the user‟s intervention in its lifecycle.
• It does proper thread management by handling the requests on a separate thread.

Methods of Android Services

• The service base class defines certain callback methods to perform operations on
applications. When we talk about Android services it becomes quite obvious that
these services will do some operations and they‟ll be used. The following are a few
important methods of Android services :

1. onStartCommand()
2. onBind()
3. onCreate()
4. onUnbind()
5. onDestroy()
6. onRebind()

1. onStartCommand()

The system calls this method whenever a component, say an activity requests „start‟ to a
service, using startService().Once we use this method it‟s our duty to stop the service
using stopService() or stopSelf().

2. onBind()

This is invoked when a component wants to bind with the service by


calling bindService(). In this, we must provide an interface for clients to communicate
with the service. For interprocess communication, we use the IBinder object.

It is a must to implement this method. If in case binding is not required, we should


return null as implementation is mandatory.

3. onUnbind()

The system invokes this when all the clients disconnect from the interface published by
the service.

4. onRebind()

The system calls this method when new clients connect to the service. The system calls it
after the onBind() method.

5. onCreate()

This is the first callback method that the system calls when a new component starts the
service. We need this method for a one-time set-up.

6. onDestroy()
This method is the final clean up call for the system. The system invokes it just before the
service destroys. It cleans up resources like threads, receivers, registered listeners, etc.

Figure 2.5 Service Life Cycle

Example of Service Life cycle:

package com.tutorialspoint;

import android.app.Service;
import android.os.IBinder;
import android.content.Intent;
import android.os.Bundle;

public class HelloService extends Service {

/** indicates how to behave if the service is killed */


int mStartMode;

/** interface for clients that bind */


IBinder mBinder;

/** indicates whether onRebind should be used */


boolean mAllowRebind;

/** Called when the service is being created. */


@Override
public void onCreate() {

/** The service is starting, due to a call to startService() */


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return mStartMode;
}

/** A client is binding to the service with bindService() */


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

/** Called when all clients have unbound with unbindService() */


@Override
public boolean onUnbind(Intent intent) {
return mAllowRebind;
}

/** Called when a client is binding to the service with bindService()*/


@Override
public void onRebind(Intent intent) {

/** Called when The service is no longer used and is being destroyed */
@Override
public void onDestroy() {

}
}

Broadcast Receivers

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.

Here 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.

Figure 2.6 Broadcast-Receiver

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.
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 regsitered 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>
Example: mainactivity.java

package com.example.tutorialspoint7.myapplication;

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

public class MainActivity extends Activity {

/** Called when the activity is first created. */


@Override

public void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

// broadcast a custom intent.

public void broadcastIntent(View view){


Intent intent = new Intent();
intent.setAction("com.tutorialspoint.CUSTOM_INTENT"); sendBroadcast(intent);
}
}

Myreceiver.java

package com.example.tutorialspoint7.myapplication;

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

/**
* Created by TutorialsPoint7 on 8/23/2016.
*/
public class MyReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
}
}

AndroidManifest.xml

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


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

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

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


</intent-filter>
</activity>

<receiver android:name="MyReceiver">
<intent-filter>
<action android:name="com.tutorialspoint.CUSTOM_INTENT">
</action>
</intent-filter>

</receiver>
</application>

</manifest>

res/layout/activity_main.xml

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Example of Broadcast"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point "
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_above="@+id/imageButton"
android:layout_centerHorizontal="true"
android:layout_marginBottom="40dp" />

<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button2"
android:text="Broadcast Intent"
android:onClick="broadcastIntent"
android:layout_below="@+id/imageButton"
android:layout_centerHorizontal="true" />

</RelativeLayout>

Content Provider:

A content provider component supplies data from one application to others on request. Such
requests are handled by the methods of the ContentResolver class. A content provider can use
different ways to store its data and the data can be stored in a database, in files, or even over a
network.

Figure 2. 7 Content Provider


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

Details of different parts of Content URI:

 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.

Operations in Content Provider


Four fundamental operations are possible in Content Provider namely Create, Read, Update,
and Delete. 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.

Figure 2. 8 Operations in Content Provider


Creating a Content Provider
Following are the steps which are essential to follow in order 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.

Following are the six abstract methods and their description which are essential to override as
the part of ContenProvider class:

Figure 2.9 Content Provider Methods

Creating a Content Provider:


Step 1: Create a new project
1. Click on File, then New => New Project.
2. Select language as Java/Kotlin.
3. Choose empty activity as a template
4. Select the minimum SDK as per your need.
Step 2: Modify the strings.xml file
All the strings used in the activity are stored here.
<resources>

<string name="app_name">Content_Provider_In_Android</string>

<string name="hintText">Enter User Name</string>

<string name="heading">Content Provider In Android</string>

<string name="insertButtontext">Insert Data</string>

<string name="loadButtonText">Load Data</string>

</resources>.

Step 3: Creating the Content Provider class

1. Click on File, then New => Other => ContentProvider.


2. Name the ContentProvider
3. Define authority (it can be anything for example “com.demo.user.provider”)
4. Select Exported and Enabled option
5. Choose the language as Java/Kotlin
package com.example.contentprovidersinandroid;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import java.util.HashMap;

public class MyContentProvider extends ContentProvider {


public MyContentProvider() {
}

// defining authority so that other application can access it


static final String PROVIDER_NAME = "com.demo.user.provider";

// defining content URI


static final String URL = "content://" + PROVIDER_NAME + "/users";

// parsing the content URI


static final Uri CONTENT_URI = Uri.parse(URL);
static final String id = "id";
static final String name = "name";
static final int uriCode = 1;
static final UriMatcher uriMatcher;
private static HashMap<String, String> values;

static {

// to match the content URI


// every time user access table under content provider
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

// to access whole table


uriMatcher.addURI(PROVIDER_NAME, "users", uriCode);

// to access a particular row


// of the table
uriMatcher.addURI(PROVIDER_NAME, "users/*", uriCode);
}
@Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)) {
case uriCode:
return "vnd.android.cursor.dir/users";
default:
throw new IllegalArgumentException("Unsupported URI: " +
uri);
}
}
// creating the database
@Override
public boolean onCreate() {
Context context = getContext();
DatabaseHelper dbHelper = new DatabaseHelper(context);
db = dbHelper.getWritableDatabase();
if (db != null) {
return true;
}
return false;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(TABLE_NAME);
switch (uriMatcher.match(uri)) {
case uriCode:
qb.setProjectionMap(values);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (sortOrder == null || sortOrder == "") {
sortOrder = id;
}
Cursor c = qb.query(db, projection, selection, selectionArgs, null,
null, sortOrder);
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}

// adding data to the database


@Override
public Uri insert(Uri uri, ContentValues values) {
long rowID = db.insert(TABLE_NAME, "", values);
if (rowID > 0) {
Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(_uri, null);
return _uri;
}
throw new SQLiteException("Failed to add a record into " + uri);
}

@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int count = 0;
switch (uriMatcher.match(uri)) {
case uriCode:
count = db.update(TABLE_NAME, values, selection,
selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}

@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int count = 0;
switch (uriMatcher.match(uri)) {
case uriCode:
count = db.delete(TABLE_NAME, selection, selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}

// creating object of database


// to perform query
private SQLiteDatabase db;

// declaring name of the database


static final String DATABASE_NAME = "UserDB";

// declaring table name of the database


static final String TABLE_NAME = "Users";

// declaring version of the database


static final int DATABASE_VERSION = 1;

// sql query to create the table


static final String CREATE_DB_TABLE = " CREATE TABLE " + TABLE_NAME
+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ " name TEXT NOT NULL);";

// creating a database
private static class DatabaseHelper extends SQLiteOpenHelper {

// defining a constructor
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// creating a table in the database


@Override
public void onCreate(SQLiteDatabase db) {

db.execSQL(CREATE_DB_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

// sql query to drop a table


// having similar name
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
Step 4: Design the activity_main.xml layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#168BC34A"
tools:context=".MainActivity">

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

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

<EditText
android:id="@+id/textName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="40dp"
android:fontFamily="@font/roboto"
android:hint="@string/hintText" />

<Button
android:id="@+id/insertButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:background="#4CAF50"
android:fontFamily="@font/roboto"
android:onClick="onClickAddDetails"
android:text="@string/insertButtontext"
android:textAlignment="center"

android:textAppearance="@style/TextAppearance.AppCompat.Display1"
android:textColor="#FFFFFF"
android:textStyle="bold" />

<Button
android:id="@+id/loadButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:background="#4CAF50"
android:fontFamily="@font/roboto"
android:onClick="onClickShowDetails"
android:text="@string/loadButtonText"
android:textAlignment="center"

android:textAppearance="@style/TextAppearance.AppCompat.Display1"
android:textColor="#FFFFFF"
android:textStyle="bold" />

<TextView
android:id="@+id/res"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:clickable="false"
android:ems="10"
android:fontFamily="@font/roboto"
android:textColor="@android:color/holo_green_dark"
android:textSize="18sp"
android:textStyle="bold" />

</LinearLayout>

<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:srcCompat="@drawable/banner" />

</androidx.constraintlayout.widget.ConstraintLayout>

Step 5: Modify the MainActivity file

package com.example.contentprovidersinandroid;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;

import android.content.Context;

import android.database.Cursor;

import android.net.Uri;

import android.os.Bundle;

import android.view.MotionEvent;

import android.view.View;

import android.view.inputmethod.InputMethodManager;

import android.widget.EditText;

import android.widget.TextView;

import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
}

@Override

public boolean onTouchEvent(MotionEvent event) {

InputMethodManager imm =
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);

imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
0);

return true;

public void onClickAddDetails(View view) {

// class to add values in the database

ContentValues values = new ContentValues();

// fetching text from user

values.put(MyContentProvider.name, ((EditText)
findViewById(R.id.textName)).getText().toString());

// inserting into database through content URI

getContentResolver().insert(MyContentProvider.CONTENT_URI,
values);

// displaying a toast message

Toast.makeText(getBaseContext(), "New Record Inserted",


Toast.LENGTH_LONG).show();

}
public void onClickShowDetails(View view) {

// inserting complete table details in this text field

TextView resultView= (TextView) findViewById(R.id.res);

// creating a cursor object of the

// content URI

Cursor cursor =
getContentResolver().query(Uri.parse("content://com.demo.user.provider/users"), null, null,
null, null);

// iteration of the cursor

// to print whole table

if(cursor.moveToFirst()) {

StringBuilder strBuild=new StringBuilder();

while (!cursor.isAfterLast()) {

strBuild.append("\n"+cursor.getString(cursor.getColumnIndex("id"))+ "-"+
cursor.getString(cursor.getColumnIndex("name")));

cursor.moveToNext();

resultView.setText(strBuild);

else {

resultView.setText("No Records Found");

Step 6: Modify the AndroidManifest file


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

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.example.content_provider_in_android">

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:roundIcon="@mipmap/ic_launcher_round"

android:supportsRtl="true"

android:theme="@style/AppTheme">

<provider

android:name="com.example.contentprovidersinandroid.MyContentProvide
r"

android:authorities="com.demo.user.provider"

android:enabled="true"

android:exported="true"></provider>

<activity android:name=".MainActivity">

<intent-filter>

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

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

</intent-filter>

</activity>

<meta-data
android:name="preloaded_fonts"

android:resource="@array/preloaded_fonts" />

</application>

</manifest>

SQLite Database:

What is SQLite?
SQLite is an in-process library that implements a self-contained, serverless, zero-
configuration, transactional SQL database engine. It is a database, which is zero-configured,
which means like other databases you do not need to configure it in your system.
SQLite engine is not a standalone process like other databases, you can link it statically or
dynamically as per your requirement with your application. SQLite accesses its storage files
directly.
Why SQLite?
 SQLite does not require a separate server process or system to operate (serverless).
 SQLite comes with zero-configuration, which means no setup or administration
needed.
 A complete SQLite database is stored in a single cross-platform disk file.
 SQLite is very small and light weight, less than 400KiB fully configured or less than
250KiB with optional features omitted.
 SQLite is self-contained, which means no external dependencies.
 SQLite transactions are fully ACID-compliant, allowing safe access from multiple
processes or threads.
 SQLite supports most of the query language features found in SQL92 (SQL2)
standard.
 SQLite is written in ANSI-C and provides simple and easy-to-use API.
 SQLite is available on UNIX (Linux, Mac OS-X, Android, iOS) and Windows
(Win32, WinCE, WinRT).
SQLite Commands
The standard SQLite commands to interact with relational databases are similar to SQL.
They are CREATE, SELECT, INSERT, UPDATE, DELETE and DROP. These commands
can be classified into groups based on their operational nature
SQLiteOpenHelper class

The android.database.sqlite.SQLiteOpenHelper class is used for database creation and


version management. For performing any database operation, you have to provide the
implementation of onCreate() and onUpgrade() methods of SQLiteOpenHelper class.

Constructors of SQLiteOpenHelper class

There are two constructors of SQLiteOpenHelper class.


Methods of SQLiteOpenHelper class

There are many methods in SQLiteOpenHelper class. Some of them are as follows:

SQLiteDatabase class

It contains methods to be performed on sqlite database such as create, update, delete, select
etc.

Methods of SQLiteDatabase class

There are many methods in SQLiteDatabase class. Some of them are as follows:
Example:

Content.java

package example.javatpoint.com.sqlitetutorial;

public class Contact {


int _id;
String _name;
String _phone_number;
public Contact(){ }
public Contact(int id, String name, String _phone_number){
this._id = id;
this._name = name;
this._phone_number = _phone_number;
}

public Contact(String name, String _phone_number){


this._name = name;
this._phone_number = _phone_number;
}
public int getID(){
return this._id;
}

public void setID(int id){


this._id = id;
}

public String getName(){


return this._name;
}

public void setName(String name){


this._name = name;
}

public String getPhoneNumber(){


return this._phone_number;
}

public void setPhoneNumber(String phone_number){


this._phone_number = phone_number;
}
}

DatabaseHandler.java

package example.javatpoint.com.sqlitetutorial;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;

public class DatabaseHandler extends SQLiteOpenHelper {


private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "contactsManager";
private static final String TABLE_CONTACTS = "contacts";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";

public DatabaseHandler(Context context) {


super(context, DATABASE_NAME, null, DATABASE_VERSION);
//3rd argument to be passed is CursorFactory instance
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACS
+ "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}

// code to add the new contact


void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();


values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone

// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
//2nd argument is String containing nullColumnHack
db.close(); // Closing database connection
}

// code to get the single contact


Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();

Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,


KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();

Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),


cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}

// code to get all contacts in a list view


public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;

SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}

// return contact list


return contactList;
}

// code to update the single contact


public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();


values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());

// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}

// Deleting single contact


public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}

// Getting contacts Count


public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}

MainActivity.java

package example.javatpoint.com.sqlitetutorial;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.util.List;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseHandler db = new DatabaseHandler(this);

// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("Ravi", "9100000000"));
db.addContact(new Contact("Srinivas", "9199999999"));
db.addContact(new Contact("Tommy", "9522222222"));
db.addContact(new Contact("Karthik", "9533333333"));

// Reading all contacts


Log.d("Reading: ", "Reading all contacts..");
List<Contact> contacts = db.getAllContacts();

for (Contact cn : contacts) {


String log = "Id: " + cn.getID() + " ,Name: " + cn.getName() + " ,Phone: " +
cn.getPhoneNumber();
// Writing Contacts to log
Log.d("Name: ", log);
}
}
}

You might also like