Combinepdf
Combinepdf
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:
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.
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:
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,
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.
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.
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
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.
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)
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.
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.
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.
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.
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.
The Android SDK includes the Android device emulator. Android emulator lets you
develop and test out the application without using a physical device.
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
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.
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 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
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
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.
Each fragment has its own life cycle methods that is affected by activity life cycle
because fragments are embedded in activity.
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
Page 18
9) onStop() is called when fragment is no
longer visible.
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
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.
onResume called when activity will start interacting with the user.
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>
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.
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.
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.
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.
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.
The Android system invokes this method when all the clients
onUnbind()
get disconnected from a particular service interface.
Page 29
Methods Description
<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>
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>
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;
}
}
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 ) );
}
}
}
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 −
There is one additional steps in case you are going to implement your custom intents
then you will have to create and broadcast those intents.
Broadcast-Receiver
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
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.
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.
intent.setAction("com.tutorialspoint.CUSTOM_INTENT");
sendBroadcast(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.
Run the application to launch Android emulator and verify the result of
7
the changes done in the application.
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
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
Intent Type
<intent-filter
android:icon="drawable resource"
android:label="string resource"
Page 43
android:priority="integer" >
...
</intent-filter>
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.
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>
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>
package com.example.intentfilter
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
Page 47
intent.putExtra(Intent.EXTRA_TEXT, "Dummy test message")
startActivity(intent)
}
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.
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.
Example
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>
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";
// creating a database
private static class DatabaseHelper extends SQLiteOpenHelper {
// defining a constructor
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
Page 55
db.execSQL(CREATE_DB_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
<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>
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");
}
}
}
Page 60
</application>
</manifest>
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>
XML
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>
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");
}
}
}
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>
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
Constructor Description
There are many methods in SQLiteOpenHelper class. Some of them are as follows:
Method Description
Page 65
first time.
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.
Page 66
Cursor query(String table, returns a cursor over the resultset.
String[] columns, String
selection, String[]
selectionArgs, String
groupBy, String having, String
orderBy)
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:
Follow the following steps to view the database and its data stored in android sqlite:
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:
Page 72
```java
// MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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
Database - Creation
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
Database - Insertion
we can create table or insert data into table using execSQL method defined in
SQLiteDatabase class. Its syntax is given below
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
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.
resultSet.moveToFirst();
There are other functions available in the Cursor class that allows us to effectively
retrieve the data. That includes
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
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 DBHelper(){
super(context,DATABASE_NAME,null,1);
Example
Page 76
Steps Description
Run the application and choose a running android device and install
10
the application on it and verify the results.
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;
DBHelper mydb;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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
dataBundle.putInt("id", id_To_Search);
intent.putExtras(dataBundle);
startActivity(intent);
});
@Override
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
@Override
super.onOptionsItemSelected(item);
Page 79
switch(item.getItemId()) {
dataBundle.putInt("id", 0);
intent.putExtras(dataBundle);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
if (keycode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
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;
int from_Where_I_Am_Coming = 0;
TextView name ;
TextView phone;
TextView email;
TextView street;
TextView place;
int id_To_Update = 0;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_contact);
Page 81
place = (TextView) findViewById(R.id.editTextCity);
if(extras !=null) {
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
// Inflate the menu; this adds items to the action bar if it is present.
if(extras !=null) {
if(Value>0){
getMenuInflater().inflate(R.menu.display_contact, menu);
} else{
Page 83
getMenuInflater().inflate(R.menu.menu_main menu);
return true;
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:
builder.setMessage(R.string.deleteContact)
mydb.deleteContact(id_To_Update);
Toast.LENGTH_SHORT).show();
startActivity(intent);
})
});
AlertDialog d = builder.create();
d.show();
return true;
default:
return super.onOptionsItemSelected(item);
Page 85
}
if(extras !=null) {
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();
startActivity(intent);
} else{
} 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.LENGTH_SHORT).show();
startActivity(intent);
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;
Page 87
public static final String CONTACTS_COLUMN_NAME = "name";
@Override
db.execSQL(
"(id integer primary key, name text,phone text,email text, street text,place
text)"
);
@Override
onCreate(db);
Page 88
public boolean insertContact (String name, String phone, String email, String
street,String place) {
SQLiteDatabase db = this.getWritableDatabase();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("street", street);
contentValues.put("place", place);
return true;
SQLiteDatabase db = this.getReadableDatabase();
return res;
SQLiteDatabase db = this.getReadableDatabase();
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);
return true;
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts",
"id = ? ",
SQLiteDatabase db = this.getReadableDatabase();
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));
Page 90
res.moveToNext();
return array_list;
<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"
<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>
<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>
Page 97
<resources>
<string name="action_settings">Settings</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="yes">Yes</string>
<string name="no">No</string>
</resources>
<item android:id="@+id/item1"
android:icon="@drawable/add"
android:title="@string/Add_New" >
</item>
Page 98
</menu>
<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>
<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>
</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:
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