Unit 2
Unit 2
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.
❖ Activities
❖ Intents
❖ Content Providers
❖ Broadcast Receivers
❖ Services
1. Activity
2. Services
}
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.
Introduction to Activity:
…….
</activity>
…….
</application>
</manifest>
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
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.
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();
...
}
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
<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.
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:
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);
<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().
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!";
(or)
(or)
Toast.makeText(getApplicationContext(),”Hello toast!”,
Toast.LENGTH_“SHORT).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);
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.
Bound
1.onBind()
2. bindService()
3. serviceConnection()
4. onstartCommand()
5. onService Connected()
Android services life-cycle can have two forms of services and they follow two paths, that
are:
• Started Service
• Bounded Service
1. Started Service
2. Bound Service
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.
• 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()
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.
package com.tutorialspoint;
import android.app.Service;
import android.os.IBinder;
import android.content.Intent;
import android.os.Bundle;
/** 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.
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.
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.
<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;
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
<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" />
<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.
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.
Following are the six abstract methods and their description which are essential to override as
the part of ContenProvider class:
<string name="app_name">Content_Provider_In_Android</string>
</resources>.
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;
static {
@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 a database
private static class DatabaseHelper extends SQLiteOpenHelper {
// defining a constructor
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
db.execSQL(CREATE_DB_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
<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>
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;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
InputMethodManager imm =
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
0);
return true;
values.put(MyContentProvider.name, ((EditText)
findViewById(R.id.textName)).getText().toString());
getContentResolver().insert(MyContentProvider.CONTENT_URI,
values);
}
public void onClickShowDetails(View view) {
// content URI
Cursor cursor =
getContentResolver().query(Uri.parse("content://com.demo.user.provider/users"), null, null,
null, null);
if(cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
strBuild.append("\n"+cursor.getString(cursor.getColumnIndex("id"))+ "-"+
cursor.getString(cursor.getColumnIndex("name")));
cursor.moveToNext();
resultView.setText(strBuild);
else {
<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>
<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
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.
There are many methods in SQLiteDatabase class. Some of them are as follows:
Example:
Content.java
package example.javatpoint.com.sqlitetutorial;
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;
// 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);
}
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
//2nd argument is String containing nullColumnHack
db.close(); // Closing database connection
}
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());
}
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
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;
@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"));