0% found this document useful (0 votes)
152 views103 pages

Combinepdf

The document provides instructions for setting up an Android development environment and Android Studio on Windows and Linux. It outlines 3 key steps: 1) Install Android Studio and required SDK components 2) Install the Android 9 SDK through the SDK Manager 3) Configure the ANDROID_HOME environment variable to point to the SDK location

Uploaded by

Mansi Agrawal
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)
152 views103 pages

Combinepdf

The document provides instructions for setting up an Android development environment and Android Studio on Windows and Linux. It outlines 3 key steps: 1) Install Android Studio and required SDK components 2) Install the Android 9 SDK through the SDK Manager 3) Configure the ANDROID_HOME environment variable to point to the SDK location

Uploaded by

Mansi Agrawal
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/ 103

To run and test your React Native application on the android device you need to set

up the Android Environment. Setting up your development environment can be


somewhat tedious if you’re new to Android development. If you’re already familiar
with Android development, there are a few things you may need to configure. In
either case, please make sure to carefully follow the next few steps. Here are 3 Steps
to Setting up Android Development Environment & Android Studio. If you want to
install the same on Mac OS then you can visit Setting up Android Development
Environment & Android Studio in Mac OS.
1. Install Android Studio
Download and install Android Studio. Choose a “Custom” setup when prompted to
select an installation type. Make sure the boxes next to all of the following are
checked:
Android SDK
Android SDK Platform
Performance (Intel ® HAXM)
Android Virtual Device
Then, click “Next” to install all of these components.
Once setup has finalized and you’re presented with the Welcome screen, proceed to
the next step.
2. Install the Android SDK
Android Studio installs the latest Android SDK by default. Building a React Native
app with native code, however, requires the Android 9 (Pie) SDK in particular.
Additional Android SDKs can be installed through the SDK Manager in Android
Studio.
The SDK Manager can be accessed from the “Welcome to Android Studio” screen.
Click on “Configure”, then select “SDK Manager”.

The SDK Manager can also be found within the Android Studio “Preferences” dialog,
under Appearance & Behavior → System Settings → Android SDK.
Select the “SDK Platforms” tab from within the SDK Manager, then check the box
next to “Show Package Details” in the bottom right corner. Look for and expand
the Android 9 (Pie) entry, then make sure the following items are all checked:
Android SDK Platform 28
Intel x86 Atom_64 System Image or Google APIs Intel x86 Atom System Image

Page 1
Next, select the “SDK Tools” tab and check the box next to “Show Package Details”
here as well. Look for and expand the “Android SDK Build-Tools” entry, then make
sure that 28.0.3 is selected.
Finally, click “Apply” to download and install the Android SDK and related build
tools.
3. Configure the ANDROID_HOME environment variable
The React Native tools require some environment variables to be set up in order to
build apps with native code.
3.1. For Windows User
Open the System pane under System and Security in the Windows Control Panel,
then click on Change settings. Open the Advanced tab and click on Environment
Variables. Click on New to create a new ANDROID_HOME user variable that points
to the path to your Android SDK:

The SDK is installed, by default, at the following location:


c:\Users\YOUR_USERNAME\AppData\Local\Android\Sdk
You can find the actual location of the SDK in the Android Studio “Preferences”
dialog, under Appearance & Behavior → System Settings → Android SDK. Open a
new Command Prompt window to ensure the new environment variable is loaded
before proceeding to the next step.
Add platform-tools to Path
Open the System pane under System and Security in the Windows Control Panel,
then click on Change settings…. Open the Advanced tab and click on Environment
Variables…. Select the Path variable, then click Edit. Click New and add the path to
platform-tools to the list.
The default location for this folder is:
c:\Users\YOUR_USERNAME\AppData\Local\Android\Sdk\platform-tools
3.2. For Linux Users
Assuming you have the SDK extracted at ~/Android/Sdk
Add the following lines to your $HOME/.bash_profile(If you unable to find then try
for $HOME/.bashrc ) config file:
export ANDROID_HOME=$HOME/Android/Sdk
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/tools/bin
export PATH=$PATH:$ANDROID_HOME/platform-tools
To test if you have set it up correctly run the below commands on a terminal window
Run
echo $ANDROID_HOME
//will print the path to your SDK /home/Android/Sdk
Run

Page 2
which android
//will print /home/<user>/Android/Sdk/tools/android
Run
android
//If it opens up Android SDK Manager, you are good to go.
This is how you can install the Android Studio and can set up the Android
Development Environment. Next, You will need an Android device to run your React
Native Android app. This can be either a physical Android device or more
commonly, you can use an Android Virtual Device which allows you to emulate an
Android device on your computer. To create an Android Virtual Device you can
follow how to create an Android Virtual Device and different ways to launch
the Emulator.
If you are facing any problem or if you have any doubt about the topic you can
comment below or contact us here.

Android architecture contains different number of components to support any


android device needs. Android software contains an open-source Linux Kernel
having collection of number of C/C++ libraries which are exposed through an
application framework services.
Among all the components Linux Kernel provides main functionality of operating
system functions to smartphones and Dalvik Virtual Machine (DVM) provide
platform for running an android application.
The main components of android architecture are following:-
 Applications
 Application Framework
 Android Runtime
 Platform Libraries
 Linux Kernel
Pictorial representation of android architecture with several main components
and their sub components –

Applications –
Applications is the top layer of android architecture. The pre-installed applications
like home, contacts, camera, gallery etc and third party applications downloaded

Page 3
from the play store like chat applications, games etc. will be installed on this layer
only.
It runs within the Android run time with the help of the classes and services
provided by the application framework.
Application framework –
Application Framework provides several important classes which are used to
create an Android application. It provides a generic abstraction for hardware
access and also helps in managing the user interface with application resources.
Generally, it provides the services with the help of which we can create a
particular class and make that class helpful for the Applications creation.
It includes different types of services activity manager, notification manager, view
system, package manager etc. which are helpful for the development of our
application according to the prerequisite.
Application runtime –
Android Runtime environment is one of the most important part of Android. It
contains components like core libraries and the Dalvik virtual machine(DVM).
Mainly, it provides the base for the application framework and powers our
application with the help of the core libraries.
Like Java Virtual Machine (JVM), Dalvik Virtual Machine (DVM) is a register-
based virtual machine and specially designed and optimized for android to ensure
that a device can run multiple instances efficiently. It depends on the layer Linux
kernel for threading and low-level memory management. The core libraries
enable us to implement android applications using the standard JAVA or Kotlin
programming languages.
Platform libraries –
The Platform Libraries includes various C/C++ core libraries and Java based
libraries such as Media, Graphics, Surface Manager, OpenGL etc. to provide a
support for android development.
 Media library provides support to play and record an audio and video formats.
 Surface manager responsible for managing access to the display subsystem.
 SGL and OpenGL both cross-language, cross-platform application program
interface (API) are used for 2D and 3D computer graphics.
 SQLite provides database support and FreeType provides font support.
 Web-Kit This open source web browser engine provides all the functionality to
display web content and to simplify page loading.
 SSL (Secure Sockets Layer) is security technology to establish an encrypted
link between a web server and a web browser.
Linux Kernel –
Linux Kernel is heart of the android architecture. It manages all the available
drivers such as display drivers, camera drivers, Bluetooth drivers, audio drivers,
memory drivers, etc. which are required during the runtime.
The Linux Kernel will provide an abstraction layer between the device hardware
and the other components of android architecture. It is responsible for
management of memory, power, devices etc.
The features of Linux kernel are:

Page 4
 Security: The Linux kernel handles the security between the application and
the system.
 Memory Management: It efficiently handles the memory management
thereby providing the freedom to develop our apps.
 Process Management: It manages the process well, allocates resources to
processes whenever they need them.
 Network Stack: It effectively handles the network communication.
 Driver Model: It ensures that the application works properly on the device and
hardware manufacturers responsible for building their drivers into the Linux
build.

Developing an Android project, you have to install the Android plug-ins for
Eclipse and at least have some knowledge of Java programming.

After installing all the plug-ins for an Android file, you can begin to develop an
Android application.

Android uses packages not only to arrange the code in an application but to manage
the application themselves.

The above diagram shows the basic building blocks of an Android application.
Android application in Eclipse or in any development tool have a pre-defined
structure with code and resource organized into a number of folders.

Page 5
Every Android project contains several folders, like:

Folder Name Description


src The 'src' stands for Source Code. It contains the Java Source
files.
gen The 'gen' stands for Generated Java Library. This library is for
Android internal use only.
Android 2.2 The Android Framework Library is stored here.
assets It is used to store raw asset files.
libs It contains private libraries.
res The 'res' stands for Resource file. It can store resource files
such as pictures, XML files, etc. It contains some additional
folders such as Drawable, Layout and Values.

anim: It is used for XML files that are compiled into animation
objects.
color: It is used for XML files that describe colors.
drawable: It is used to store various graphics files. In Android
project structure,

there are three types of drawable folders,


1. drawable-mdpi
2. drawable-hdpi
3. drawable-ldpi

The above drawable folders are required in order to adapt to


different screen resolutions.

layout: It is used for placing the XML layout files, which defines
how various Android objects such as textbox, buttons, etc. are
organized on the screen.

menu: It is used for defining the XML files in the application


menu.

raw: The 'raw' stands for Raw Asset Files. These files are
referenced from the application using a resource identifier in
the R class.
For example, good place for media is MP3 or Ogg files.

values: It is used for XML files which stores various string


values, such as titles, labels, etc.

Page 6
xml: It is used for configuring the application components.
AndroidManifest.xml This file indicates the Android definition file. This file contains
the information about the Android application such as minimum
Android version, permission to access Android device
capabilities such as Internet access permission, phone
permission etc.
default.properties This file contains the project settings, such as build the target.
Do not edit this file manually. It should be maintained in a
Source Revision Control System.
Proguard.cfg This file defines how ProGuard optimizes and makes your code
unclear.
MainLayout.xml This file describes the layout of the page. So all the components
such as textboxes, labels, radio buttons, etc. are displaying on
the application screen.
Activity class The application occupies the entire device screen which needs
at least one class inherits from the Activity class. OnCreate()
method initiates the application and loads the layout page.

Android Emulator

The Android emulator is an Android Virtual Device (AVD), which represents a


specific Android device. We can use the Android emulator as a target device to
execute and test our Android application on our PC. The Android emulator provides
almost all the functionality of a real device. We can get the incoming phone calls and
text messages. It also gives the location of the device and simulates different
network speeds. Android emulator simulates rotation and other hardware sensors. It
accesses the Google Play store, and much more

Testing Android applications on emulator are sometimes faster and easier than
doing on a real device. For example, we can transfer data faster to the emulator than
to a real device connected through USB.

Page 7
The Android emulator comes with predefined configurations for several Android
phones, Wear OS, tablet, Android TV devices.

Requirement and recommendations

The Android emulator takes additional requirements beyond the basic system
requirement for Android Studio. These requirements are given below:
o SDK Tools 26.1.1 or higher
o 64-bit processor
o Windows: CPU with UG (unrestricted guest) support
o HAXM 6.2.1 or later (recommended HAXM 7.2.0 or later)

Install the emulator

The Android emulator is installed while installing the Android Studio. However some
components of emulator may or may not be installed while installing Android Studio.
To install the emulator component, select the Android Emulator component in
the SDK Tools tab of the SDK Manager.

Run an Android app on the Emulator

We can run an Android app form the Android Studio project, or we can run an app
which is installed on the Android Emulator as we run any app on a device.

To start the Android Emulator and run an application in our project:

1. In Android Studio, we need to create an Android Virtual Device (AVD) that the
emulator can use to install and run your app. To create a new AVD:-

1.1 Open the AVD Manager by clicking Tools > AVD Manager.

1.2 Click on Create Virtual Device, at the bottom of the AVD Manager dialog.
Then Select Hardware page appears.

Page 8
1.3 Select a hardware profile and then click Next. If we don?t see the hardware
profile we want, then we can create or import a hardware profile. The System
Image page appears.

1.4 Select the system image for the particular API level and click Next. This leads to
open a Verify Configuration page.

1.5 Change AVD properties if needed, and then click Finish.

2. In the toolbar, choose the AVD, which we want to run our app from the target
device from the drop-down menu.

Page 9
3. Click Run.

Launch the Emulator without first running an app

To start the emulator:


1. Open the AVD Manager.
2. Double-click an AVD, or click Run

While the emulator is running, we can run the Android Studio project and select the
emulator as the target device. We can also drag an APKs file to install on an
emulator, and then run them.

Start the emulator from the command line

The Android SDK includes the Android device emulator. Android emulator lets you
develop and test out the application without using a physical device.

Starting the emulator

Using the emulator command, we will start an emulator. It is an alternative to run


our project or start through the AVD Manager.

Here is the basic command-line syntax for starting a virtual device:


1. $ emulator -avd avd_name [ {-option [value]} ... ]

or
1. $ emulator @avd_name [ {-option [value]} ... ]

For example, if we execute the emulator from Android Studio on a Mac, the default
command line will be similar as follows:
1. $ /Users/user_name/Library/Android/sdk/emulator/emulator -
avd Nexus_5X_API_23 -netdelay none -netspeed full

To display the list of AVD names, enter the following command:


1. $ emulator -list-avds

Run and stop an emulator, and clear data

From the Virtual Device page, we can perform the following operation on emulator:

Page 10
o To run an Android emulator that uses an AVD, double-click the AVD, or
click Launch
o To stop the running emulator, right-click and select Stop, or click Menu ▼ and
select Stop.
o If we want to clear the data from an emulator and return it to the initial state
when it was first defined, then right-click an AVD and select Wipe Data. Or
click menu ▼ and select Wipe Data.

In android development, we need an android device to run the application. So,


developers of Android Studio provide an option to install android virtual device to
run it. In this article, we will learn how to install Android Virtual Device (AVD).
Follow the below steps to install Android Virtual Device.
Step 1: Go to Tools > AVD Manager.

Step 2: Now click on Create Virtual Device.

Page 11
Step 3: A pop-up window will be there and here we select the category Phone
because we are creating android app for mobile and select the model of mobile
phone we want to install.

Step 4: Here we select the android version to download like Q, Pie, Oreo etc and
click Next button.

Step 5: Click the finish button to complete the installation.

Step 6: Now we can select the virtual device we want to run as emulator can click
on the run icon.

Page 12
Step 7: Finally our virtual device is ready to run our android app.

UI screen components

A typical user interface of an android application consists of action bar and the
application content area.
 Main Action Bar
 View Control
 Content Area
 Split Action Bar

These components have also been shown in the image below −

Understanding Screen Components

The basic unit of android application is the activity. A UI is defined in an xml file.
During compilation, each element in the XML is compiled into equivalent Android
GUI class with attributes represented by methods.

Page 13
View and ViewGroups

An activity is consist of views. A view is just a widget that appears on the screen. It
could be button e.t.c. One or more views can be grouped together into one
GroupView. Example of ViewGroup includes layouts.

Types of layout

There are many types of layout. Some of which are listed below −
 Linear Layout
 Absolute Layout
 Table Layout
 Frame Layout
 Relative Layout

Linear Layout

Linear layout is further divided into horizontal and vertical layout. It means it can
arrange views in a single column or in a single row. Here is the code of linear
layout(vertical) that includes a text view.
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”vertical” >
<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”@string/hello” />
</LinearLayout>

AbsoluteLayout

The AbsoluteLayout enables you to specify the exact location of its children. It can
be declared like this.
<AbsoluteLayout
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android=”http://schemas.android.com/apk/res/android” >
<Button
android:layout_width=”188dp”
android:layout_height=”wrap_content”
android:text=”Button”
android:layout_x=”126px”
android:layout_y=”361px” />
</AbsoluteLayout>

Page 14
TableLayout

The TableLayout groups views into rows and columns. It can be declared like this.
<TableLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_height=”fill_parent”
android:layout_width=”fill_parent” >
<TableRow>
<TextView
android:text=”User Name:”
android:width =”120dp”
/>
<EditText
android:id=”@+id/txtUserName”
android:width=”200dp” />
</TableRow>
</TableLayout>

RelativeLayout

The RelativeLayout enables you to specify how child views are positioned relative to
each other.It can be declared like this.
<RelativeLayout
android:id=”@+id/RLayout”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android=”http://schemas.android.com/apk/res/android” >
</RelativeLayout>

FrameLayout

The FrameLayout is a placeholder on screen that you can use to display a single
view. It can be declared like this.
<?xml version=”1.0” encoding=”utf-8”?>
<FrameLayout
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignLeft=”@+id/lblComments”
android:layout_below=”@+id/lblComments”
android:layout_centerHorizontal=”true” >
<ImageView
android:src = “@drawable/droid”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content” />
</FrameLayout>

Page 15
Apart form these attributes, there are other attributes that are common in all views
and ViewGroups. They are listed below −
Sr.No View & description

layout_width
1
Specifies the width of the View or ViewGroup

layout_height
2
Specifies the height of the View or ViewGroup

layout_marginTop
3
Specifies extra space on the top side of the View or ViewGroup

layout_marginBottom
4
Specifies extra space on the bottom side of the View or ViewGroup

layout_marginLeft
5
Specifies extra space on the left side of the View or ViewGroup

layout_marginRight
6
Specifies extra space on the right side of the View or ViewGroup

layout_gravity
7
Specifies how child Views are positioned

layout_weight
8 Specifies how much of the extra space in the layout should be
allocated to the View

Units of Measurement

When you are specifying the size of an element on an Android UI, you should
remember the following units of measurement.
Sr.No Unit & description

dp
1 Density-independent pixel. 1 dp is equivalent to one pixel on a 160
dpi screen.

sp
2 Scale-independent pixel. This is similar to dp and is recommended
for specifying font sizes

pt
3 Point. A point is defined to be 1/72 of an inch, based on the physical
screen size.

Page 16
px
4
Pixel. Corresponds to actual pixels on the screen
Screen Densities
Sr.No Density & DPI

Low density (ldpi)


1
120 dpi

Medium density (mdpi)


2
160 dpi

High density (hdpi)


3
240 dpi

Extra High density (xhdpi)


4
320 dpi
Optimizing layouts
Here are some of the guidelines for creating efficient layouts.
 Avoid unnecessary nesting
 Avoid using too many Views
 Avoid deep nesting

Android Fragments

Android Fragment is the part of activity, it is also known as sub-activity. There can
be more than one fragment in an activity. Fragments represent multiple screen
inside one activity.

Android fragment lifecycle is affected by activity lifecycle because fragments are


included in activity.

Each fragment has its own life cycle methods that is affected by activity life cycle
because fragments are embedded in activity.

The FragmentManager class is responsible to make interaction between fragment


objects.

Android Fragment Lifecycle

The lifecycle of android fragment is like the activity lifecycle. There are 12 lifecycle
methods for fragment.

Page 17
Android Fragment Lifecycle Methods
No. Method Description

1) onAttach(Activity) it is called only once when it is


attached with activity.

2) onCreate(Bundle) It is used to initialize the fragment.

3) onCreateView(LayoutInflater, creates and returns view


ViewGroup, Bundle) hierarchy.

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


of onCreate() method.

5) onViewStateRestored(Bundle) It provides information to the


fragment that all the saved state of
fragment view hierarchy has been
restored.

6) onStart() makes the fragment visible.

7) onResume() makes the fragment interactive.

8) onPause() is called when fragment is no


longer interactive.

Page 18
9) onStop() is called when fragment is no
longer visible.

10) onDestroyView() allows the fragment to clean up


resources.

11) onDestroy() allows the fragment to do final


clean up of fragment state.

12) onDetach() It is called immediately prior to


the fragment no longer being
associated with its activity.

Android Fragment Example

Let's have a look at the simple example of android fragment.

activity_main.xml
File: activity_main.xml
1. <?xml version="1.0" encoding="utf-8"?>
2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="fill_parent"
6. android:layout_height="fill_parent"
7. tools:context="example.javatpoint.com.fragmentexample.MainActivity">
8. <fragment
9. android:id="@+id/fragment1"
10. android:name="example.javatpoint.com.fragmentexample.Fragment1"
11. android:layout_width="0px"
12. android:layout_height="match_parent"
13. android:layout_weight="1"
14. />
15. <fragment
16. android:id="@+id/fragment2"
17. android:name="example.javatpoint.com.fragmentexample.Fragment2"
18. android:layout_width="0px"
19. android:layout_height="match_parent"
20. android:layout_weight="1"
21. />
22. </LinearLayout>
File: fragment_fragment1.xml
1. <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"

Page 19
4. android:layout_height="match_parent"
5. android:background="#F5F5DC"
6. tools:context="example.javatpoint.com.fragmentexample.Fragment1">
7. <!-- TODO: Update blank fragment layout -->
8. <TextView
9. android:layout_width="match_parent"
10. android:layout_height="match_parent"
11. android:text="@string/hello_blank_fragment" />
12.
13. </FrameLayout>
File: fragment_fragment2.xml
1. <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:background="#F0FFFF"
6. tools:context="example.javatpoint.com.fragmentexample.Fragment2">
7. <!-- TODO: Update blank fragment layout -->
8. <TextView
9. android:layout_width="match_parent"
10. android:layout_height="match_parent"
11. android:text="@string/hello_blank_fragment" />
12.
13. </FrameLayout>

MainActivity class
File: MainActivity.java
1. package example.javatpoint.com.fragmentexample;
2. import android.support.v7.app.AppCompatActivity;
3. import android.os.Bundle;
4. public class MainActivity extends AppCompatActivity {
5. @Override
6. protected void onCreate(Bundle savedInstanceState) {
7. super.onCreate(savedInstanceState);
8. setContentView(R.layout.activity_main);
9. }
10. }

File: Fragment1.java
1. package example.javatpoint.com.fragmentexample;
2. import android.os.Bundle;
3. import android.support.v4.app.Fragment;
4. import android.view.LayoutInflater;
5. import android.view.View;

Page 20
6. import android.view.ViewGroup;
7. public class Fragment1 extends Fragment {
8. @Override
9. public void onCreate(Bundle savedInstanceState) {
10. super.onCreate(savedInstanceState);
11. }
12. @Override
13. public View onCreateView(LayoutInflater inflater, ViewGroup container,
14. Bundle savedInstanceState) {
15. // Inflate the layout for this fragment
16. return inflater.inflate(R.layout.fragment_fragment1, container, false);
17. }
18. }

File: Fragment2.java
1. package example.javatpoint.com.fragmentexample;
2. import android.os.Bundle;
3. import android.support.v4.app.Fragment;
4. import android.view.LayoutInflater;
5. import android.view.View;
6. import android.view.ViewGroup;
7. public class Fragment2 extends Fragment {
8. @Override
9. public void onCreate(Bundle savedInstanceState) {
10. super.onCreate(savedInstanceState);
11. }
12. @Override
13. public View onCreateView(LayoutInflater inflater, ViewGroup container,
14. Bundle savedInstanceState) {
15. // Inflate the layout for this fragment
16. return inflater.inflate(R.layout.fragment_fragment2, container, false);
17. }
18. }

Output:

Page 21
Android Activity Lifecycle

Android Activity Lifecycle is controlled by 7 methods of android.app.Activity class.


The android Activity is the subclass of ContextThemeWrapper class.

An activity is the single screen in android. It is like window or frame of Java.

By the help of activity, you can place all your UI components or widgets in a single
screen.

The 7 lifecycle method of Activity describes how activity will behave at different
states.

Android Activity Lifecycle methods

Let's see the 7 lifecycle methods of android activity.


Method Description

onCreate called when activity is first created.

onStart called when activity is becoming visible to the user.

onResume called when activity will start interacting with the user.

onPause called when activity is not visible to the user.

onStop called when activity is no longer visible to the user.

onRestart called after your activity is stopped, prior to start.

onDestroy called before the activity is destroyed.

Page 22
File: activity_main.xml
1. <?xml version="1.0" encoding="utf-8"?>
2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.a
ndroid.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.activitylifecycle.MainActivity">
8. <TextView
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:text="Hello World!"
12. app:layout_constraintBottom_toBottomOf="parent"
13. app:layout_constraintLeft_toLeftOf="parent"
14. app:layout_constraintRight_toRightOf="parent"
15. app:layout_constraintTop_toTopOf="parent" />
16. </android.support.constraint.ConstraintLayout>

Android Activity Lifecycle Example

It provides the details about the invocation of life cycle methods of activity. In this
example, we are displaying the content on the logcat.
File: MainActivity.java
1. package example.javatpoint.com.activitylifecycle;
2. import android.app.Activity;
3. import android.os.Bundle;
4. import android.util.Log;
5. public class MainActivity extends Activity {

Page 23
6. @Override
7. protected void onCreate(Bundle savedInstanceState) {
8. super.onCreate(savedInstanceState);
9. setContentView(R.layout.activity_main);
10. Log.d("lifecycle","onCreate invoked");
11. }
12. @Override
13. protected void onStart() {
14. super.onStart();
15. Log.d("lifecycle","onStart invoked");
16. }
17. @Override
18. protected void onResume() {
19. super.onResume();
20. Log.d("lifecycle","onResume invoked");
21. }
22. @Override
23. protected void onPause() {
24. super.onPause();
25. Log.d("lifecycle","onPause invoked");
26. }
27. @Override
28. protected void onStop() {
29. super.onStop();
30. Log.d("lifecycle","onStop invoked");
31. }
32. @Override
33. protected void onRestart() {
34. super.onRestart();
35. Log.d("lifecycle","onRestart invoked");
36. }
37. @Override
38. protected void onDestroy() {
39. super.onDestroy();
40. Log.d("lifecycle","onDestroy invoked");
41. }
42. }

Output:

You will not see any output on the emulator or device. You need to open logcat.

Page 24
Now see on the logcat: onCreate, onStart and onResume methods are invoked.

Now click on the HOME Button. You will see onPause method is invoked.

After a while, you will see onStop method is invoked.

Now see on the emulator. It is on the home. Now click on the center button to launch
the app again.

Page 25
Now click on the lifecycleactivity icon.

Now see on the logcat: onRestart, onStart and onResume methods are invoked.

If you see the emulator, application is started again.

Page 26
Now click on the back button. Now you will see onPause methods is invoked.

After a while, you will see onStop and onDestroy methods are invoked.

The onCreate() and onDestroy() methods are called only once throughout the
activity lifecycle.

Services in Android are a special component that facilitates an application to run in


the background in order to perform long-running operation tasks. The prime aim
of a service is to ensure that the application remains active in the background so
that the user can operate multiple applications at the same time. A user-interface is
not desirable for android services as it is designed to operate long-running
processes without any user intervention. A service can run continuously in the
background even if the application is closed or the user switches to another
application. Further, application components can bind itself to service to carry
out inter-process communication(IPC). There is a major difference between
android services and threads, one must not be confused between the two. Thread
is a feature provided by the Operating system to allow the user to perform
operations in the background. While service is an android component that
performs a long-running operation about which the user might not be aware of as it
does not have UI.
Types of Android Services

1. Foreground Services:

Page 27
Services that notify the user about its ongoing operations are termed as
Foreground Services. Users can interact with the service by the notifications
provided about the ongoing task. Such as in downloading a file, the user can keep
track of the progress in downloading and can also pause and resume the process.
2. Background Services:
Background services do not require any user intervention. These services do not
notify the user about ongoing background tasks and users also cannot access them.
The process like schedule syncing of data or storing of data fall under this service.
3. Bound Services:
This type of android service allows the components of the application like activity
to bound themselves with it. Bound services perform their task as long as any
application component is bound to it. More than one component is allowed to bind
themselves with a service at a time. In order to bind an application component with
a service bindService() method is used.

The Life Cycle of Android Services


In android, services have 2 possible paths to complete its life cycle namely Started
and Bounded.
1. Started Service (Unbounded Service):
By following this path, a service will initiate when an application component calls
the startService() method. Once initiated, the service can run continuously in the
background even if the component is destroyed which was responsible for the start
of the service. Two option are available to stop the execution of service:
 By calling stopService() method,
 The service can stop itself by using stopSelf() method.
2. Bounded Service:
It can be treated as a server in a client-server interface. By following this path,
android application components can send requests to the service and can fetch
results. A service is termed as bounded when an application component binds
itself with a service by calling bindService() method. To stop the execution of this
service, all the components must unbind themselves from the service by
using unbindService() method.

To carry out a downloading task in the background, the startService() method will be
called. Whereas to get information regarding the download progress and to pause or

Page 28
resume the process while the application is still in the background, the service must
be bounded with a component which can perform these tasks.

Fundamentals of Android Services


A user-defined service can be created through a normal class which is extending
the class Service. Further, to carry out the operations of service on applications,
there are certain callback methods which are needed to be overridden. The
following are some of the important methods of Android Services:
Methods Description

The Android service calls this method when a component(eg:


activity)
requests to start a service using startService(). Once the
onStartCommand()
service is started,
it can be stopped explicitly using stopService() or stopSelf()
methods.

This method is mandatory to implement in android service


and is invoked
whenever an application component calls the bindService()
method in order to
onBind() bind itself with a service. User-interface is also provided to
communicate
with the service effectively by returning an IBinder object.
If the binding of service is not required then the method must
return null.

The Android system invokes this method when all the clients
onUnbind()
get disconnected from a particular service interface.

Once all clients are disconnected from the particular interface


of service and
onRebind()
there is a need to connect the service with new clients, the
system calls this method.

Whenever a service is created either using


onStartCommand() or onBind(),
onCreate() the android system calls this method. This method is
necessary to perform
a one-time-set-up.

Page 29
Methods Description

When a service is no longer in use, the system invokes this


method
just before the service destroys as a final clean up call.
onDestroy() Services must
implement this method in order to clean up resources like
registered listeners,
threads, receivers, etc.

Example of Android Services


Playing music in the background is a very common example of services in
android. From the time when a user starts the service, music play continuously in
the background even if the user switches to another application. The user has to
stop the service explicitly in order to pause the music. Below is the complete step-
by-step implementation of this android service using a few callback methods.
Note: Following steps are performed on Android Studio version 4.0
Step 1: Create a new project
1. Click on File, then New => New Project.
2. Choose Empty activity
3. Select language as Java/Kotlin
4. Select the minimum SDK as per your need.
Step 2: Modify strings.xml file
All the strings which are used in the activity are listed in this file.
 XML

<resources>
<string name="app_name">Services_In_Android</string>
<string name="heading">Services In Android</string>
<string name="startButtonText">Start the Service</string>
<string name="stopButtonText">Stop the Service</string>
</resources>

Step 3: Working with the activity_main.xml file


Open the activity_main.xml file and add 2 Buttons in it which will start and stop
the service. Below is the code for designing a proper activity layout.
 XML

<?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"

Page 30
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_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0"
tools:ignore="MissingConstraints">
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="170dp"
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" />
<Button
android:id="@+id/startButton"
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:text="@string/startButtonText"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Display1"
android:textColor="#FFFFFF"
android:textStyle="bold" />

Page 31
<Button
android:id="@+id/stopButton"
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:text="@string/stopButtonText"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Display1"
android:textColor="#FFFFFF"
android:textStyle="bold" />
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="80dp"
app:srcCompat="@drawable/banner" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

Step 4: Creating the custom service class


A custom service class will be created in the same directory where
the MainActivity class resides and this class will extend the Service class. The
callback methods are used to initiate and destroy the services. To play music,
the MediaPlayer object is used. Below is the code to carry out this task.
 Java
 Kotlin

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.provider.Settings;
import androidx.annotation.Nullable;
public class NewService extends Service {
// declaring object of MediaPlayer
private MediaPlayer player;
@Override
// execution of service will start
// on calling this method

Page 32
public int onStartCommand(Intent intent, int flags, int startId) {
// creating a media player which
// will play the audio of Default
// ringtone in android device
player = MediaPlayer.create( this,
Settings.System.DEFAULT_RINGTONE_URI );
// providing the boolean
// value as true to play
// the audio on loop
player.setLooping( true );
// starting the process
player.start();
// returns the status
// of the program
return START_STICKY;
}
@Override
// execution of the service will
// stop on calling this method
public void onDestroy() {
super.onDestroy();
// stopping the process
player.stop();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}

Step 5: Working with the MainActivity file


Now, the button objects will be declared and the process to be performed on
clicking these buttons will be defined in the MainActivity class. Below is the code
to implement this step.
 Java
 Kotlin

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements

Page 33
View.OnClickListener {
// declaring objects of Button class
private Button start, stop;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
// assigning ID of startButton
// to the object start
start = (Button) findViewById( R.id.startButton );
// assigning ID of stopButton
// to the object stop
stop = (Button) findViewById( R.id.stopButton );
// declaring listeners for the
// buttons to make them respond
// correctly according to the process
start.setOnClickListener( this );
stop.setOnClickListener( this );
}
public void onClick(View view) {
// process to be performed
// if start button is clicked
if(view == start){
// starting the service
startService(new Intent( this, NewService.class ) );
}
// process to be performed
// if stop button is clicked
else if (view == stop){
// stopping the service
stopService(new Intent( this, NewService.class ) );
}
}
}

Step 6: Modify the AndroidManifest.xml file


To implement the services successfully on any android device, it is necessary to
mention the created service in the AndroidManifest.xml file. It is not possible for
a service to perform its task if it is not mentioned in this file. The service name is
mentioned inside the application tag.
 XML

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


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

Page 34
package="com.example.services_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">
<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" />
<!-- Mention the service name here -->
<service android:name=".NewService"/>
</application>
</manifest>

Output:

Page 35
Broadcast Receivers simply respond to broadcast messages from other applications
or from the system itself. These messages are sometime called events or intents. For
example, applications can also initiate broadcasts to let other applications know that
some data has been downloaded to the device and is available for them to use, so
this is broadcast receiver who will intercept this communication and will initiate
appropriate action.

There are following two important steps to make BroadcastReceiver works for the
system broadcasted intents −

Creating the Broadcast Receiver.

Registering Broadcast Receiver

There is one additional steps in case you are going to implement your custom intents
then you will have to create and broadcast those intents.

Creating the Broadcast Receiver

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


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

public class MyReceiver extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
}
}
Registering Broadcast Receiver

An application listens for specific broadcast intents by registering a broadcast


receiver in AndroidManifest.xml file. Consider we are going to
register MyReceiver for system generated event ACTION_BOOT_COMPLETED
which is fired by the system once the Android system has completed the boot
process.

Broadcast-Receiver

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"

Page 36
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

Page 37
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

This example will explain you how to create BroadcastReceiver to intercept custom
intent. Once you are familiar with custom intent, then you can program your
application to intercept system generated intents. So let's follow the following steps
to modify the Android application we created in Hello World Example chapter −

Step Description

Page 38
You will use Android studio to create an Android application and
name it as My Application under a
1 package com.example.tutorialspoint7.myapplication as explained in
the Hello World Example chapter.

Modify main activity file MainActivity.java to


2
add broadcastIntent() method.

Create a new java file called MyReceiver.java under the


3 package com.example.tutorialspoint7.myapplication to define a
BroadcastReceiver.

An application can handle one or more custom and system intents


4 without any restrictions. Every intent you want to intercept must be
registered in your AndroidManifest.xml file using <receiver.../> tag

Modify the default content of res/layout/activity_main.xml file to


5
include a button to broadcast intent.

No need to modify the string file, Android studio take care of


6
string.xml file.

Run the application to launch Android emulator and verify the result of
7
the changes done in the application.

Following is the content of the modified main activity

file MainActivity.java. This file can include each of the fundamental life cycle
methods. We have added broadcastIntent() method to broadcast a custom intent.

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

Page 39
// broadcast a custom intent.
public void broadcastIntent(View view){
Intent intent = new Intent();
intent.setAction("com.tutorialspoint.CUSTOM_INTENT"); sendBroadcast(intent);
}
}
Following is the content of 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();
}
}
Following will the modified content of AndroidManifest.xml file. Here we have
added <receiver.../> tag to include our service:
<?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>

Page 40
</manifest>
Following will be the content of res/layout/activity_main.xml file to
include a button to broadcast our custom intent −

<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"

Page 41
android:layout_below="@+id/imageButton"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Let's try to run our modified Hello World! application we just modified. I assume you
had created your AVD while doing environment set-up. To run the app from Android
studio, open one of your project's activity files and click Run icon from the tool bar.
Android Studio installs the app on your AVD and starts it and if everything is fine
with your set-up and application, it will display following Emulator window −

Now to broadcast our custom intent, let's click on Broadcast Intent button, this will
broadcast our custom intent "com.tutorialspoint.CUSTOM_INTENT" which will be

intercepted by our registered BroadcastReceiver i.e. MyReceiver and as per our


implemented logic a toast will appear on the bottom of the the simulator as follows −

You can try implementing other BroadcastReceiver to intercept system generated


intents like system boot up, date changed, low battery etc.

The intent is a messaging object which tells what kind of action to be performed.
The intent’s most significant use is the launching of the activity. Intent facilitates the
communication between the components.
Note: App components are the basic building blocks of App.
Fundamental use case of Intents
Starting Activity

Page 42
An activity represents the single screen in an app, Bypassing intent instance we
can start an activity.
Example:
 Kotlin

var intent = Intent(this, SecondActivity:: class.java)


startIntent(intent)

You can add extra information by using putExtra().


Starting a Service
A Service is a component that performs operations in the background without a
user interface, which is also called a background process.
Delivering a Broadcast
A broadcast is a message that any app can receive. In android, the system delivers
various broadcast system events like device starts charging, disable or enable
airplane mode, etc.

Intent Type

There are two types of intent


1. Explicit intent: Explicit intent can do the specific application action which is set
by the code like changing activity, In explicit intent user knows about all the
things like after clicking a button which activity will start and Explicit intents are
used for communication inside the application
2. Implicit Intent: Implicit intents do not name a specific component like explicit
intent, instead declare general action to perform, which allows a component
from another app to handle.
For example: when you tap the share button in any app you can see the Gmail,
Bluetooth, and other sharing app options.
Intent Filter
 Implicit intent uses the intent filter to serve the user request.
 The intent filter specifies the types of intents that an activity, service, or
broadcast receiver can respond.
 Intent filters are declared in the Android manifest file.
 Intent filter must contain <action>
Example:
 XML

<intent-filter
android:icon="drawable resource"
android:label="string resource"

Page 43
android:priority="integer" >
...
</intent-filter>

Most of the intent filter are describe by its


1. <action>,
2. <category> and
3. <data>.
1. <action>

Syntax:
 XML

<action android:name="string" />

Adds an action to an intent filter. An <intent-filter> element must contain one or


more <action> elements. If there are no <action> elements in an intent filter, the
filter doesn’t accept any Intent objects.
Examples of common action:
 ACTION_VIEW: Use this action in intent with startActivity() when you have
some information that activity can show to the user like showing an image in a
gallery app or an address to view in a map app
 ACTION_SEND: You should use this in intent with startActivity() when you have
some data that the user can share through another app, such as an email app or
social sharing app.
2. <category>
Syntax:
 XML

<category android:name="string" />

Adds a category name to an intent filter. A string containing additional information


about the kind of component that should handle the intent.
Example of common categories:
 CATEGORY_BROWSABLE: The target activity allows itself to be started by a
web browser to display data referenced by a link.
3. <data>
Syntax:
 XML

<data android:scheme="string"
android:host="string"

Page 44
android:port="string"
android:path="string"
android:pathPattern="string"
android:pathPrefix="string"
android:mimeType="string" />

Adds a data specification to an intent filter. The specification can be just a data
type, just a URI, or both a data type and a URI.
Note: Uniform Resource Identifier (URI) is a string of characters used to identify a
resource. A URI identifies a resource either by location, or a name, or both.

Implementation of Intent Filter with a Demo App

Step 1: Create a New Project


To create a new project in Android Studio please refer to How to Create/Start a
New Project in Android Studio. Note that select Kotlin as the programming
language.
Step 2: Add dependencies to the build.gradle(Module:app) file
Add the following dependency to the build.gradle(Module:app) file. We are
adding these two dependencies because to avoid using findViewById() in
our MainActivity.kt file. Try this out otherwise use the normal way
like findViewById().
apply plugin: ‘kotlin-android’
apply plugin: ‘kotlin-android-extensions’

Step 3: Working with the activity_main.xml file


Navigate to the app > res > layout > activity_main.xml and add the below code
to that file. Below is the code for the activity_main.xml file.
 XML

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


<androidx.constraintlayout.widget.ConstraintLayout

Page 45
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/sendButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SEND"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.476"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintVertical_bias="0.153" />
<Button
android:id="@+id/buttonView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="View"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.826" />

</androidx.constraintlayout.widget.ConstraintLayout>

Step 4: Working with the AndroidManifest.xml File


Following is the code for the AndroidManifest.xml File.
 XML

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.menuapplication">
<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/Theme.MenuApplication">
<activity android:name=".MainActivity">

Page 46
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<!--SEND INTENT FILTER-->
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>

<!--VIEW INTENT FILTER-->


<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="http"/>
</intent-filter>
</activity>
</application>
</manifest>

Step 5: Working with the MainActivity.kt file


Go to the MainActivity.kt file and refer to the following code. Below is the code
for the MainActivity.kt file. Comments are added inside the code to understand
the code in more detail.
 Kotlin

package com.example.intentfilter
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// send button on click listener
sendButton.setOnClickListener {
var intent = Intent(Intent.ACTION_SEND) // intent
intent.type = "text/plain"
intent.putExtra(Intent.EXTRA_EMAIL, "[email protected]")
intent.putExtra(Intent.EXTRA_SUBJECT, "This is a dummy message")

Page 47
intent.putExtra(Intent.EXTRA_TEXT, "Dummy test message")
startActivity(intent)
}

// View on click listener


buttonView.setOnClickListener {
var intent = Intent(Intent.ACTION_VIEW)
startActivity(intent)
}
}
}

Output with Explanation:

Click on Send Button, you will see a screen like this,

Now choose Gmail app,

Page 48
Now go to our app and click the view button,

our app dummy app. You can any app from these options because we are using a
view intent filter.

In Android, Content Providers are a very important component that serves the
purpose of a relational database to store the data of applications. The role of the
content provider in the android system is like a central repository in which data of
the applications are stored, and it facilitates other applications to securely access
and modifies that data based on the user requirements. Android system allows the
content provider to store the application data in several ways. Users can manage to
store the application data like images, audio, videos, and personal contact
information by storing them in SQLite Database, in files, or even on a network.
In order to share the data, content providers have certain permissions that are used
to grant or restrict the rights to other applications to interfere with the data.

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.

Page 49
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.
If an ID is mentioned in a URI then it is an id-based URI otherwise a directory-
based URI.
Operations in Content Provider
Four fundamental operations 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. Below is a diagram to represent these
processes in pictorial form.

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.

Page 50
 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:
Abstract
Method Description

A method that accepts arguments and fetches the data from the
query()
desired table. Data is retired as a cursor object.

To insert a new row in the database of the content provider.


insert()
It returns the content URI of the inserted row.

This method is used to update the fields of an existing row.


update()
It returns the number of rows updated.

This method is used to delete the existing rows.


delete()
It returns the number of rows deleted.

This method returns the Multipurpose Internet Mail


getType() Extension(MIME)
type of data to the given Content URI.

As the content provider is created, the android system calls


onCreate()
this method immediately to initialise the provider.

Example

The prime purpose of a content provider is to serve as a central repository of data


where users can store and can fetch the data. The access of this repository is given
to other applications also but in a safe manner in order to serve the different
requirements of the user. The following are the steps involved in implementing a
content provider. In this content provider, the user can store the name of persons

Page 51
and can fetch the stored data. Moreover, another application can also access the
stored data and can display the data.
Note: Following steps are performed on Android Studio version 4.0
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.

 XML

<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
This class extends the ContentProvider base class and override the six abstract
methods. Below is the complete code to define a content provider.

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

Page 52
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;
}

Page 53
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);
}

Page 54
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) {

Page 55
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


One Textview, EditText field, two Buttons, and a Textview to display the stored
data will be added in the activity using the below code.
 XML

<?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"

Page 56
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"

Page 57
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


Button functionalities will be defined in this file. Moreover, the query to be
performed while inserting and fetching the data is mentioned here. Below is the
complete code.

 Java
 Kotlin

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;

Page 58
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();

Page 59
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


The AndroidManifest file must contain the content provider name, authorities, and
permissions which enable the content provider to be accessed by other
applications.
 XML

<?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.MyContentProvider
"
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" />

Page 60
</application>
</manifest>

Creating another application to access the 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 strings.xml file
All the strings used in the activity are stored in this file.

 XML

<resources>
<string name="app_name">Accessing_Content_Provider</string>
<string name="heading">Accessing data of Content Provider</string>
<string name="loadButtonText">Load Data</string>
</resources>

Step 3: Designing the activity_main.xml layout


Two TextView are added in the activity, one for heading and one to display the
stored data in a content provider. One Button is also added to receive the
command to display data. Below is the code to implement this design.

 XML

<?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"

Page 61
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" />

<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"

Page 62
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 4: Modify the MainActivity file


The ContentURI of the previous application is mentioned here and the same
functions which were used in the previous app to display the records will also be
used here. Below is the complete code:

 Java
 Kotlin

package com.example.accessingcontentprovider;
import androidx.appcompat.app.AppCompatActivity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
Uri CONTENT_URI = Uri.parse("content://com.demo.user.provider/users");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
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

Page 63
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");
}
}
}

Output: Run on Emulator

Video Player

00:00

00:36
Step 5: Modify the AndroidManifest.xml file
Don’t forget to add <query> permission (API 30 and above).
For more details refer here.
 XML

<queries>
<package android:name="com.example.contentprovidersinandroid"/>
</queries>
<application>
.
.
.
</application>

Android SQLite Tutorial

SQLite is an open-source relational database i.e. used to perform database


operations on android devices such as storing, manipulating or retrieving persistent
data from the database.

Page 64
It is embedded in android bydefault. So, there is no need to perform any database
setup or administration task.

Here, we are going to see the example of sqlite to store and fetch the data. Data is
displayed in the logcat. For displaying data on the spinner or listview, move to the
next page.

SQLiteOpenHelper class provides the functionality to use the SQLite database.

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.

Constructor Description

SQLiteOpenHelper(Context context, String creates an object for


name, SQLiteDatabase.CursorFactory factory, creating, opening and
int version) managing the database.

SQLiteOpenHelper(Context context, String creates an object for


name, SQLiteDatabase.CursorFactory factory, creating, opening and
int version, DatabaseErrorHandler managing the database.
errorHandler) It specifies the error
handler.

Methods of SQLiteOpenHelper class

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

Method Description

public abstract void called only once when


onCreate(SQLiteDatabase db) database is created for the

Page 65
first time.

public abstract void called when database


onUpgrade(SQLiteDatabase db, int needs to be upgraded.
oldVersion, int newVersion)

public synchronized void close () closes the database


object.

public void onDowngrade(SQLiteDatabase called when database


db, int oldVersion, int newVersion) needs to be downgraded.

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:

Method Description

void execSQL(String sql) executes the sql query not select query.

long insert(String table, String inserts a record on the database. The table
nullColumnHack, specifies the table name, nullColumnHack
ContentValues values) doesn't allow completely null values. If
second argument is null, android will store
null values if values are empty. The third
argument specifies the values to be stored.

int update(String table, updates a row.


ContentValues values, String
whereClause, String[]
whereArgs)

Page 66
Cursor query(String table, returns a cursor over the resultset.
String[] columns, String
selection, String[]
selectionArgs, String
groupBy, String having, String
orderBy)

Example of android SQLite database

Let's see the simple example of android sqlite database.

File: Contact.java
1. package example.javatpoint.com.sqlitetutorial;
2. public class Contact {
3. int _id;
4. String _name;
5. String _phone_number;
6. public Contact(){ }
7. public Contact(int id, String name, String _phone_number){
8. this._id = id;
9. this._name = name;
10. this._phone_number = _phone_number;
11. }
12. public Contact(String name, String _phone_number){
13. this._name = name;
14. this._phone_number = _phone_number;
15. }
16. public int getID(){
17. return this._id;
18. }
19. public void setID(int id){
20. this._id = id;
21. }
22. public String getName(){
23. return this._name;
24. }
25. public void setName(String name){
26. this._name = name;
27. }
28. public String getPhoneNumber(){
29. return this._phone_number;
30. }
31. public void setPhoneNumber(String phone_number){

Page 67
32. this._phone_number = phone_number;
33. }
34. }
File: DatabaseHandler.java

Now, let's create the database handler class that extends SQLiteOpenHelper class
and provides the implementation of its methods.
1. package example.javatpoint.com.sqlitetutorial;
2. import android.content.ContentValues;
3. import android.content.Context;
4. import android.database.Cursor;
5. import android.database.sqlite.SQLiteDatabase;
6. import android.database.sqlite.SQLiteOpenHelper;
7. import java.util.ArrayList;
8. import java.util.List;
9. public class DatabaseHandler extends SQLiteOpenHelper {
10. private static final int DATABASE_VERSION = 1;
11. private static final String DATABASE_NAME = "contactsManager";
12. private static final String TABLE_CONTACTS = "contacts";
13. private static final String KEY_ID = "id";
14. private static final String KEY_NAME = "name";
15. private static final String KEY_PH_NO = "phone_number";
16. public DatabaseHandler(Context context) {
17. super(context, DATABASE_NAME, null, DATABASE_VERSION);
18. //3rd argument to be passed is CursorFactory instance
19. }
20. // Creating Tables
21. @Override
22. public void onCreate(SQLiteDatabase db) {
23. String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS +
"("
24. + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
25. + KEY_PH_NO + " TEXT" + ")";
26. db.execSQL(CREATE_CONTACTS_TABLE);
27. }
28.
29. // Upgrading database
30. @Override
31. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
32. // Drop older table if existed
33. db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
34. // Create tables again
35. onCreate(db);
36. }
37. // code to add the new contact

Page 68
38. void addContact(Contact contact) {
39. SQLiteDatabase db = this.getWritableDatabase();
40. ContentValues values = new ContentValues();
41. values.put(KEY_NAME, contact.getName()); // Contact Name
42. values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
43. // Inserting Row
44. db.insert(TABLE_CONTACTS, null, values);
45. //2nd argument is String containing nullColumnHack
46. db.close(); // Closing database connection
47. }
48. // code to get the single contact
49. Contact getContact(int id) {
50. SQLiteDatabase db = this.getReadableDatabase();
51. Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
52. KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
53. new String[] { String.valueOf(id) }, null, null, null, null);
54. if (cursor != null)
55. cursor.moveToFirst();
56. Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
57. cursor.getString(1), cursor.getString(2));
58. // return contact
59. return contact;
60. }
61. // code to get all contacts in a list view
62. public List<Contact> getAllContacts() {
63. List<Contact> contactList = new ArrayList<Contact>();
64. // Select All Query
65. String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
66. SQLiteDatabase db = this.getWritableDatabase();
67. Cursor cursor = db.rawQuery(selectQuery, null);
68. // looping through all rows and adding to list
69. if (cursor.moveToFirst()) {
70. do {
71. Contact contact = new Contact();
72. contact.setID(Integer.parseInt(cursor.getString(0)));
73. contact.setName(cursor.getString(1));
74. contact.setPhoneNumber(cursor.getString(2));
75. // Adding contact to list
76. contactList.add(contact);
77. } while (cursor.moveToNext());
78. }
79. // return contact list
80. return contactList;
81. }
82. // code to update the single contact

Page 69
83. public int updateContact(Contact contact) {
84. SQLiteDatabase db = this.getWritableDatabase();
85. ContentValues values = new ContentValues();
86. values.put(KEY_NAME, contact.getName());
87. values.put(KEY_PH_NO, contact.getPhoneNumber());
88. // updating row
89. return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
90. new String[] { String.valueOf(contact.getID()) });
91. }
92. // Deleting single contact
93. public void deleteContact(Contact contact) {
94. SQLiteDatabase db = this.getWritableDatabase();
95. db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
96. new String[] { String.valueOf(contact.getID()) });
97. db.close();
98. }
99. // Getting contacts Count
100. public int getContactsCount() {
101. String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
102. SQLiteDatabase db = this.getReadableDatabase();
103. Cursor cursor = db.rawQuery(countQuery, null);
104. cursor.close();
105. // return count
106. return cursor.getCount();
107. }
108. }
File: MainActivity.java
1. package example.javatpoint.com.sqlitetutorial;
2. import android.support.v7.app.AppCompatActivity;
3. import android.os.Bundle;
4. import android.util.Log;
5. import java.util.List;
6. public class MainActivity extends AppCompatActivity {
7. @Override
8. protected void onCreate(Bundle savedInstanceState) {
9. super.onCreate(savedInstanceState);
10. setContentView(R.layout.activity_main);
11. DatabaseHandler db = new DatabaseHandler(this);
12. // Inserting Contacts
13. Log.d("Insert: ", "Inserting ..");
14. db.addContact(new Contact("Ravi", "9100000000"));
15. db.addContact(new Contact("Srinivas", "9199999999"));
16. db.addContact(new Contact("Tommy", "9522222222"));
17. db.addContact(new Contact("Karthik", "9533333333"));
18. // Reading all contacts

Page 70
19. Log.d("Reading: ", "Reading all contacts..");
20. List<Contact> contacts = db.getAllContacts();
21. for (Contact cn : contacts) {
22. String log = "Id: " + cn.getID() + " ,Name: " + cn.getName() + " ,Phone: " +
23. cn.getPhoneNumber();
24. // Writing Contacts to log
25. Log.d("Name: ", log);
26. }
27. }
28. }

Output:

How to view the data stored in sqlite in android studio?

Follow the following steps to view the database and its data stored in android sqlite:

o Open File Explorer.


o Go to data directory inside data directory.
o Search for your application package name.
o Inside your application package go to databases where you will found your
database (contactsManager).
o Save your database (contactsManager) anywhere you like.
o Download any SqLite browser plugins or tool (in my case DB Browser for
SQLite).
o Launch DB Browser for SQLite and open your database (contactsManager).
o Go to Browse Data -> select your table (contacts) you will see the data stored.

Page 71
In Android Studio, a helper class is typically a class that provides utility methods or
functions to assist in performing common tasks or operations. These helper classes
can be created to encapsulate and organize code that is reused throughout your
Android application. They contribute to making your code more modular, readable,
and maintainable.

Here's a simple example of how you might create a helper class in Android Studio:

1. **Create a new Java class:**


In Android Studio, right-click on the package where you want to create the helper
class. Select `New -> Java Class`. Give your class a meaningful name, like
`MyHelperClass`, and click `OK`.
```java
// MyHelperClass.java
public class MyHelperClass {
// You can add static methods here to perform various tasks
public static int addNumbers(int a, int b) {
return a + b;
}
}
```

2. **Using the Helper Class:**


In your main activity or any other class where you want to use the helper class, you
can simply call the methods provided by the helper class.

Page 72
```java
// MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Using the helper class method


int result = MyHelperClass.addNumbers(5, 10);
Log.d("MainActivity", "Result: " + result);
}
}
```
This is just a basic example, and helper classes can become more complex
depending on the requirements of your application. They can handle tasks such as
data validation, formatting, network operations, and more.
It's worth noting that as your project grows, you might also consider using design
patterns like Singleton or Dependency Injection to manage the instances of your
helper classes efficiently. Additionally, Android Jetpack libraries and other third-
party libraries often provide utilities that can serve as helpful helpers for common
tasks.

SQLite is a opensource SQL database that stores data to a text file on a device.
Android comes in with built in SQLite database implementation.SQLite supports all
the relational database features. In order to access this database, you don't need to
establish any kind of connections for it like JDBC,ODBC e.t.c

Database - Package

The main package is android.database.sqlite that contains the classes to manage


your own databases

Database - Creation

In order to create a database you just need to call this method


openOrCreateDatabase with your database name and mode as a parameter. It
returns an instance of SQLite database which you have to receive in your own
object.Its syntax is given below

SQLiteDatabase mydatabase = openOrCreateDatabase("your database


name",MODE_PRIVATE,null);

Apart from this , there are other functions available in the database package , that
does this job. They are listed below

Page 73
Sr.No Method & Description

openDatabase(String path, SQLiteDatabase.CursorFactory factory,


int flags, DatabaseErrorHandler errorHandler)
1 This method only opens the existing database with the appropriate
flag mode. The common flags mode could be OPEN_READWRITE
OPEN_READONLY

openDatabase(String path, SQLiteDatabase.CursorFactory factory,


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

openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory


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

openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory


factory)
4
This method is similar to above method but it takes the File object as
a path rather then a string. It is equivalent to file.getPath()

Database - Insertion

we can create table or insert data into table using execSQL method defined in
SQLiteDatabase class. Its syntax is given below

mydatabase.execSQL("CREATE TABLE IF NOT EXISTS TutorialsPoint(Username


VARCHAR,Password VARCHAR);");

mydatabase.execSQL("INSERT INTO TutorialsPoint VALUES('admin','admin');");

This will insert some values into our table in our database. Another method that also
does the same job but take some additional parameter is given below

Page 74
Sr.No Method & Description

execSQL(String sql, Object[] bindArgs)


1 This method not only insert data , but also used to update or modify
already existing data in database using bind arguments

Database - Fetching

We can retrieve anything from database using an object of the Cursor class. We will
call a method of this class called rawQuery and it will return a resultset with the
cursor pointing to the table. We can move the cursor forward and retrieve the data.

Cursor resultSet = mydatbase.rawQuery("Select * from TutorialsPoint",null);

resultSet.moveToFirst();

String username = resultSet.getString(0);

String password = resultSet.getString(1);

There are other functions available in the Cursor class that allows us to effectively
retrieve the data. That includes

Sr.No Method & Description

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

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

getColumnName(int columnIndex)
3 This method returns the name of the column by specifying the index
of the column

Page 75
getColumnNames()
4
This method returns the array of all the column names of the table.

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

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

isClosed()
7 This method returns true if the cursor is closed and return false
otherwise

Database - Helper class

For managing all the operations related to the database , an helper class has been
given and is called SQLiteOpenHelper. It automatically manages the creation and
update of the database. Its syntax is given below

public class DBHelper extends SQLiteOpenHelper {

public DBHelper(){

super(context,DATABASE_NAME,null,1);

public void onCreate(SQLiteDatabase db) {}

public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion)


{}

Example

Here is an example demonstrating the use of SQLite Database. It creates a basic


contacts applications that allows insertion, deletion and modification of contacts.To
experiment with this example, you need to run this on an actual device on which
camera is supported.

Page 76
Steps Description

You will use Android studio to create an Android application under a


1
package com.example.sairamkrishna.myapplication.

Modify src/MainActivity.java file to get references of all the XML


2
components and populate the contacts on listView.

3 Create new src/DBHelper.java that will manage the database work

Create a new Activity as DisplayContact.java that will display the


4
contact on the screen

Modify the res/layout/activity_main to add respective XML


5
components

Modify the res/layout/activity_display_contact.xml to add respective


6
XML components

Modify the res/values/string.xml to add necessary string


7
components

Modify the res/menu/display_contact.xml to add necessary menu


8
components

Create a new menu as res/menu/mainmenu.xml to add the insert


9
contact option

Run the application and choose a running android device and install
10
the application on it and verify the results.

Following is the content of the modified MainActivity.java.

package com.example.sairamkrishna.myapplication;

import android.content.Context;

Page 77
import android.content.Intent;

import android.support.v7.app.ActionBarActivity;

import android.os.Bundle;

import android.view.KeyEvent;

import android.view.Menu;

import android.view.MenuItem;

import android.view.View;

import android.widget.AdapterView;

import android.widget.ArrayAdapter;

import android.widget.AdapterView.OnItemClickListener;

import android.widget.ListView;

import java.util.ArrayList;

import java.util.List;

public class MainActivity extends ActionBarActivity {

public final static String EXTRA_MESSAGE = "MESSAGE";

private ListView obj;

DBHelper mydb;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

mydb = new DBHelper(this);

ArrayList array_list = mydb.getAllCotacts();

ArrayAdapter arrayAdapter=new
ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);

Page 78
obj = (ListView)findViewById(R.id.listView1);

obj.setAdapter(arrayAdapter);

obj.setOnItemClickListener(new OnItemClickListener(){

@Override

public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)


{

// TODO Auto-generated method stub

int id_To_Search = arg2 + 1;

Bundle dataBundle = new Bundle();

dataBundle.putInt("id", id_To_Search);

Intent intent = new Intent(getApplicationContext(),DisplayContact.class);

intent.putExtras(dataBundle);

startActivity(intent);

});

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.menu_main, menu);

return true;

@Override

public boolean onOptionsItemSelected(MenuItem item){

super.onOptionsItemSelected(item);

Page 79
switch(item.getItemId()) {

case R.id.item1:Bundle dataBundle = new Bundle();

dataBundle.putInt("id", 0);

Intent intent = new Intent(getApplicationContext(),DisplayContact.class);

intent.putExtras(dataBundle);

startActivity(intent);

return true;

default:

return super.onOptionsItemSelected(item);

public boolean onKeyDown(int keycode, KeyEvent event) {

if (keycode == KeyEvent.KEYCODE_BACK) {

moveTaskToBack(true);

return super.onKeyDown(keycode, event);

Following is the modified content of display contact activity DisplayContact.java

package com.example.sairamkrishna.myapplication;

import android.os.Bundle;

import android.app.Activity;

import android.app.AlertDialog;

import android.content.DialogInterface;

Page 80
import android.content.Intent;

import android.database.Cursor;

import android.view.Menu;

import android.view.MenuItem;

import android.view.View;

import android.widget.Button;

import android.widget.TextView;

import android.widget.Toast;

public class DisplayContact extends Activity {

int from_Where_I_Am_Coming = 0;

private DBHelper mydb ;

TextView name ;

TextView phone;

TextView email;

TextView street;

TextView place;

int id_To_Update = 0;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_display_contact);

name = (TextView) findViewById(R.id.editTextName);

phone = (TextView) findViewById(R.id.editTextPhone);

email = (TextView) findViewById(R.id.editTextStreet);

street = (TextView) findViewById(R.id.editTextEmail);

Page 81
place = (TextView) findViewById(R.id.editTextCity);

mydb = new DBHelper(this);

Bundle extras = getIntent().getExtras();

if(extras !=null) {

int Value = extras.getInt("id");

if(Value>0){

//means this is the view part not the add contact part.

Cursor rs = mydb.getData(Value);

id_To_Update = Value;

rs.moveToFirst();

String nam =
rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME));

String phon =
rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_PHONE));

String emai =
rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_EMAIL));

String stree =
rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STREET));

String plac =
rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_CITY));

if (!rs.isClosed()) {

rs.close();

Button b = (Button)findViewById(R.id.button1);

b.setVisibility(View.INVISIBLE);

name.setText((CharSequence)nam);

name.setFocusable(false);

Page 82
name.setClickable(false);

phone.setText((CharSequence)phon);

phone.setFocusable(false);

phone.setClickable(false);

email.setText((CharSequence)emai);

email.setFocusable(false);

email.setClickable(false);

street.setText((CharSequence)stree);

street.setFocusable(false);

street.setClickable(false);

place.setText((CharSequence)plac);

place.setFocusable(false);

place.setClickable(false);

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

Bundle extras = getIntent().getExtras();

if(extras !=null) {

int Value = extras.getInt("id");

if(Value>0){

getMenuInflater().inflate(R.menu.display_contact, menu);

} else{

Page 83
getMenuInflater().inflate(R.menu.menu_main menu);

return true;

public boolean onOptionsItemSelected(MenuItem item) {

super.onOptionsItemSelected(item);

switch(item.getItemId()) {

case R.id.Edit_Contact:

Button b = (Button)findViewById(R.id.button1);

b.setVisibility(View.VISIBLE);

name.setEnabled(true);

name.setFocusableInTouchMode(true);

name.setClickable(true);

phone.setEnabled(true);

phone.setFocusableInTouchMode(true);

phone.setClickable(true);

email.setEnabled(true);

email.setFocusableInTouchMode(true);

email.setClickable(true);

street.setEnabled(true);

street.setFocusableInTouchMode(true);

street.setClickable(true);

place.setEnabled(true);

place.setFocusableInTouchMode(true);

Page 84
place.setClickable(true);

return true;

case R.id.Delete_Contact:

AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setMessage(R.string.deleteContact)

.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int id) {

mydb.deleteContact(id_To_Update);

Toast.makeText(getApplicationContext(), "Deleted Successfully",

Toast.LENGTH_SHORT).show();

Intent intent = new Intent(getApplicationContext(),MainActivity.class);

startActivity(intent);

})

.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int id) {

// User cancelled the dialog

});

AlertDialog d = builder.create();

d.setTitle("Are you sure");

d.show();

return true;

default:

return super.onOptionsItemSelected(item);

Page 85
}

public void run(View view) {

Bundle extras = getIntent().getExtras();

if(extras !=null) {

int Value = extras.getInt("id");

if(Value>0){

if(mydb.updateContact(id_To_Update,name.getText().toString(),

phone.getText().toString(), email.getText().toString(),

street.getText().toString(), place.getText().toString())){

Toast.makeText(getApplicationContext(), "Updated",
Toast.LENGTH_SHORT).show();

Intent intent = new Intent(getApplicationContext(),MainActivity.class);

startActivity(intent);

} else{

Toast.makeText(getApplicationContext(), "not Updated",


Toast.LENGTH_SHORT).show();

} else{

if(mydb.insertContact(name.getText().toString(), phone.getText().toString(),

email.getText().toString(), street.getText().toString(),

place.getText().toString())){

Toast.makeText(getApplicationContext(), "done",

Toast.LENGTH_SHORT).show();

Page 86
} else{

Toast.makeText(getApplicationContext(), "not done",

Toast.LENGTH_SHORT).show();

Intent intent = new Intent(getApplicationContext(),MainActivity.class);

startActivity(intent);

Following is the content of Database class DBHelper.java

package com.example.sairamkrishna.myapplication;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.Hashtable;

import android.content.ContentValues;

import android.content.Context;

import android.database.Cursor;

import android.database.DatabaseUtils;

import android.database.sqlite.SQLiteOpenHelper;

import android.database.sqlite.SQLiteDatabase;

public class DBHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "MyDBName.db";

public static final String CONTACTS_TABLE_NAME = "contacts";

public static final String CONTACTS_COLUMN_ID = "id";

Page 87
public static final String CONTACTS_COLUMN_NAME = "name";

public static final String CONTACTS_COLUMN_EMAIL = "email";

public static final String CONTACTS_COLUMN_STREET = "street";

public static final String CONTACTS_COLUMN_CITY = "place";

public static final String CONTACTS_COLUMN_PHONE = "phone";

private HashMap hp;

public DBHelper(Context context) {

super(context, DATABASE_NAME , null, 1);

@Override

public void onCreate(SQLiteDatabase db) {

// TODO Auto-generated method stub

db.execSQL(

"create table contacts " +

"(id integer primary key, name text,phone text,email text, street text,place
text)"

);

@Override

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

// TODO Auto-generated method stub

db.execSQL("DROP TABLE IF EXISTS contacts");

onCreate(db);

Page 88
public boolean insertContact (String name, String phone, String email, String
street,String place) {

SQLiteDatabase db = this.getWritableDatabase();

ContentValues contentValues = new ContentValues();

contentValues.put("name", name);

contentValues.put("phone", phone);

contentValues.put("email", email);

contentValues.put("street", street);

contentValues.put("place", place);

db.insert("contacts", null, contentValues);

return true;

public Cursor getData(int id) {

SQLiteDatabase db = this.getReadableDatabase();

Cursor res = db.rawQuery( "select * from contacts where id="+id+"", null );

return res;

public int numberOfRows(){

SQLiteDatabase db = this.getReadableDatabase();

int numRows = (int) DatabaseUtils.queryNumEntries(db,


CONTACTS_TABLE_NAME);

return numRows;

public boolean updateContact (Integer id, String name, String phone, String email,
String street,String place) {

SQLiteDatabase db = this.getWritableDatabase();

Page 89
ContentValues contentValues = new ContentValues();

contentValues.put("name", name);

contentValues.put("phone", phone);

contentValues.put("email", email);

contentValues.put("street", street);

contentValues.put("place", place);

db.update("contacts", contentValues, "id = ? ", new String[] { Integer.toString(id)


} );

return true;

public Integer deleteContact (Integer id) {

SQLiteDatabase db = this.getWritableDatabase();

return db.delete("contacts",

"id = ? ",

new String[] { Integer.toString(id) });

public ArrayList<String> getAllCotacts() {

ArrayList<String> array_list = new ArrayList<String>();

//hp = new HashMap();

SQLiteDatabase db = this.getReadableDatabase();

Cursor res = db.rawQuery( "select * from contacts", null );

res.moveToFirst();

while(res.isAfterLast() == false){

array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));

Page 90
res.moveToNext();

return array_list;

Following is the content of the res/layout/activity_main.xml

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

<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:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/textView"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true"

android:textSize="30dp"

android:text="Data Base" />

<TextView

Page 91
android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials Point"

android:id="@+id/textView2"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true"

android:textSize="35dp"

android:textColor="#ff16ff01" />

<ImageView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageView"

android:layout_below="@+id/textView2"

android:layout_centerHorizontal="true"

android:src="@drawable/logo"/>

<ScrollView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/scrollView"

android:layout_below="@+id/imageView"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:layout_alignParentBottom="true"

android:layout_alignParentRight="true"

android:layout_alignParentEnd="true">

Page 92
<ListView

android:id="@+id/listView1"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_centerHorizontal="true"

android:layout_centerVertical="true" >

</ListView>

</ScrollView>

</RelativeLayout>

Following is the content of the res/layout/activity_display_contact.xml

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

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

xmlns:tools="http://schemas.android.com/tools"

android:id="@+id/scrollView1"

android:layout_width="match_parent"

android:layout_height="wrap_content"

tools:context=".DisplayContact" >

<RelativeLayout

android:layout_width="match_parent"

android:layout_height="370dp"

android:paddingBottom="@dimen/activity_vertical_margin"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin">

<EditText

Page 93
android:id="@+id/editTextName"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentLeft="true"

android:layout_marginTop="5dp"

android:layout_marginLeft="82dp"

android:ems="10"

android:inputType="text" >

</EditText>

<EditText

android:id="@+id/editTextEmail"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignLeft="@+id/editTextStreet"

android:layout_below="@+id/editTextStreet"

android:layout_marginTop="22dp"

android:ems="10"

android:inputType="textEmailAddress" />

<TextView

android:id="@+id/textView1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignBottom="@+id/editTextName"

android:layout_alignParentLeft="true"

android:text="@string/name"

Page 94
android:textAppearance="?android:attr/textAppearanceMedium" />

<Button

android:id="@+id/button1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignLeft="@+id/editTextCity"

android:layout_alignParentBottom="true"

android:layout_marginBottom="28dp"

android:onClick="run"

android:text="@string/save" />

<TextView

android:id="@+id/textView2"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignBottom="@+id/editTextEmail"

android:layout_alignLeft="@+id/textView1"

android:text="@string/email"

android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView

android:id="@+id/textView5"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignBottom="@+id/editTextPhone"

android:layout_alignLeft="@+id/textView1"

android:text="@string/phone"

Page 95
android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView

android:id="@+id/textView4"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_above="@+id/editTextEmail"

android:layout_alignLeft="@+id/textView5"

android:text="@string/street"

android:textAppearance="?android:attr/textAppearanceMedium" />

<EditText

android:id="@+id/editTextCity"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignRight="@+id/editTextName"

android:layout_below="@+id/editTextEmail"

android:layout_marginTop="30dp"

android:ems="10"

android:inputType="text" />

<TextView

android:id="@+id/textView3"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignBaseline="@+id/editTextCity"

android:layout_alignBottom="@+id/editTextCity"

android:layout_alignParentLeft="true"

Page 96
android:layout_toLeftOf="@+id/editTextEmail"

android:text="@string/country"

android:textAppearance="?android:attr/textAppearanceMedium" />

<EditText

android:id="@+id/editTextStreet"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignLeft="@+id/editTextName"

android:layout_below="@+id/editTextPhone"

android:ems="10"

android:inputType="text" >

<requestFocus />

</EditText

<EditText

android:id="@+id/editTextPhone"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignLeft="@+id/editTextStreet"

android:layout_below="@+id/editTextName"

android:ems="10"

android:inputType="phone|text" />

</RelativeLayout>

</ScrollView>

Following is the content of the res/value/string.xml

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

Page 97
<resources>

<string name="app_name">Address Book</string>

<string name="action_settings">Settings</string>

<string name="hello_world">Hello world!</string>

<string name="Add_New">Add New</string>

<string name="edit">Edit Contact</string>

<string name="delete">Delete Contact</string>

<string name="title_activity_display_contact">DisplayContact</string>

<string name="name">Name</string>

<string name="phone">Phone</string>

<string name="email">Email</string>

<string name="street">Street</string>

<string name="country">City/State/Zip</string>

<string name="save">Save Contact</string>

<string name="deleteContact">Are you sure, you want to delete it.</string>

<string name="yes">Yes</string>

<string name="no">No</string>

</resources>

Following is the content of the res/menu/main_menu.xml

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

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

<item android:id="@+id/item1"

android:icon="@drawable/add"

android:title="@string/Add_New" >

</item>

Page 98
</menu>

Following is the content of the res/menu/display_contact.xml

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

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

<item

android:id="@+id/Edit_Contact"

android:orderInCategory="100"

android:title="@string/edit"/>

<item

android:id="@+id/Delete_Contact"

android:orderInCategory="100"

android:title="@string/delete"/>

</menu>

This is the defualt AndroidManifest.xml of this project

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

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

package="com.example.sairamkrishna.myapplication" >

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name=".MainActivity"

android:label="@string/app_name" >

Page 99
<intent-filter>

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

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

</intent-filter>

</activity>

<activity android:name=".DisplayContact"/>

</application>

</manifest>

Let's try to run your application. I assume you have connected your actual Android
Mobile device with your computer. To run the app from Android studio , open one of
your project's activity files and click Run icon from the tool bar. Before starting your
application,Android studio will display following window to select an option where
you want to run your Android application.

Select your mobile device as an option and then check your mobile device which
will display following screen −

Page 100
Now open your optional menu, it will show as below image: Optional menu appears
different places on different versions

Click on the add button of the menu screen to add a new contact. It will display the
following screen −

It will display the following fields. Please enter the required information and click on
save contact. It will bring you back to main screen.

Now our contact sai has been added.In order to see that where is your database is
created. Open your android studio, connect your mobile. Go tools/android/android
device monitor. Now browse the file explorer tab. Now browse this
folder /data/data/<your.package.name>/databases<database-name>.

Page 101
In Android Studio, you can interact with server-side applications using various
methods, such as making HTTP requests, using RESTful APIs, or implementing
socket connections. Here's a step-by-step guide on how to interact with server-side
applications in Android Studio:

1. Add Internet Permission: Open your AndroidManifest.xml file and add the
following permission within the `<manifest>` tag:
```xml
<uses-permission android:name="android.permission.INTERNET" />
```
2. Choose a Networking Library: There are several networking libraries available
for Android, such as OkHttp, Retrofit, or Volley. Choose one that suits your needs
and add it to your project by following the library-specific instructions.
3. Make HTTP Requests: Once you have added the networking library, you can start
making HTTP requests to interact with the server. Here's an example of making a
GET request using the Retrofit library:

Define an interface for your API endpoints:


```java
public interface ApiService {
@GET("endpoint")
Call<ResponseModel> getData();
}
```
Create an instance of the Retrofit object:
```java
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://your-server-url.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
```

Create an instance of the API service using the Retrofit object:


```java
ApiService apiService = retrofit.create(ApiService.class);
```
Make the API call and handle the response:
```java
Call<ResponseModel> call = apiService.getData();
call.enqueue(new Callback<ResponseModel>() {
@Override
public void onResponse(Call<ResponseModel> call,
Response<ResponseModel> response) {
// Handle successful response

Page 102
}
@Override
public void onFailure(Call<ResponseModel> call, Throwable t) {
// Handle failure
}
});
```
4. Parse Server Responses: Depending on the server's response format (JSON, XML,
etc.), you may need to parse the response into usable objects. You can use libraries
like Gson or Jackson to deserialize the response into your model classes.

5. Handle Errors and Exceptions: Implement error handling logic for cases like
network connectivity issues, server errors, or timeouts. Display appropriate error
messages to the user or handle the errors gracefully within your application.

Page 103

You might also like