Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
33 views299 pages

191CS53 Mobile Application Development NOTES

The document outlines the course structure for Mobile Application Development at P.S.R. Engineering College, detailing the course code, prerequisites, aims, and outcomes. It covers various topics including Android platform overview, interface tools, file management, and advanced technologies, along with recommended textbooks and references. The course is designed to equip students with the necessary skills to develop mobile applications, focusing on both Android and iOS platforms.
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)
33 views299 pages

191CS53 Mobile Application Development NOTES

The document outlines the course structure for Mobile Application Development at P.S.R. Engineering College, detailing the course code, prerequisites, aims, and outcomes. It covers various topics including Android platform overview, interface tools, file management, and advanced technologies, along with recommended textbooks and references. The course is designed to equip students with the necessary skills to develop mobile applications, focusing on both Android and iOS platforms.
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/ 299

P.S.R.

ENGINEERING COLLEGE
(An Autonomous Institution, Affiliated to Anna University, Chennai)
Sevalpatti (P.O), Sivakasi - 626140.
Virudhunagar Dt.

LECTURE NOTES

COURSE CODE : 191CS53

COURSE NAME : MOBILE APPLICATION DEVELOPMENT

SEMSTER :V

ACADEMIC YEAR : 2024-2025 (ODD SEMESTER)

DEPARTMENT

OF

COMPUTER SCIENCE AND ENGINEERING

PREPARED BY

Dr.C. NATARAJAN
ASP/CSE
L T P C
191CS53 MOBILE APPLICATION DEVELOPMENT
3 0 0 3
Programme: B.E. Computer Science and Engineering Sem: 5 Category: PC
Prerequisites: 191CS42 – Object Oriented Programming
Aim: To provide students with the tools and knowledge necessary to create mobile
applications that can run on mobile devices.
Course Outcomes: The Students will be able to
CO1: Classify the various Android Applications using layout and menus.
CO2: Demonstrate the audio, video and animation application.
CO3: Explain the fundamentals concepts of web database application.
CO4: Develop various types of sensors in Android.
CO5: Interpret applications to hand-held devices.
CO6: Design and Develop the mobile application (Mini Project).
ANDROID OVERVIEW 9
Overview of Android platform- Android SDK features - setting up the mobile app development
environment along with an emulator- Android Application Development Architecture - creating an
applications and activities -Application manifest
INTERFACE TOOLS 9
Creating user interface - Views - creating views - Layouts - Drawable resources - resolution and
density independence - Menus - Intents - Adapters - Using Internet resources - Dialogs.
FILES AND DATABASES 9
Saving Simple Application Data - creating and saving preferences - preferences activity -saving
activity state - loading files - file management tools-sending emails through application - Introducing
Android databases -SQLite - Web Database- Firebase, MySQL-PHP
SMALL COMPUTING TECNOLOGY AND SENSORS 9
Audio, Video Using the Camera - Telephony And SMS - Bluetooth Networks - Managing network
connectivity - WI-FI - Sensors-Sensors and the Sensor Manager - Interpreting sensor values-Using
the compass, Accelerometer and Orientation sensor.
ADVANCED TECHNOLOGY 9
Paranoid Android - Using Wake Locks - AIDL to Support IPC for Services -General API’s- Payment-
gateway, Android jetpack-Technology II-IOS-Introduction to Objective C-IOS features.
Total Periods: 45
Text Book:
1. Jeff Mc Wherter and Scott Gowell, “ Professional Mobile Application Development” Wrox,2012
2. David Mark, Jack Nutting, Jeff LaMarche and Frederic Olsson “Beginning ios 6 Development:
Exploring the iOS SDK”, Apress, 2013
3. “Teach Yourself Android Application Development in 24 Hours”, SAMS publication, 3/e, 2013
References:
1. Anubhav Pradhan, Anil V. Deshpande, “Composing Mobile Apps: Learn. Explore. Apply. Using
Android”, Wiley publication, 2014.
2. Barry Burd, “Android Application Development All in one for Dummies”, John Wiley & Sons
publication,2011.
3. http://developer.android.com/develop/index.htm
4. https://www.tutorialspoint.com/android
5. http://www.androidhive.info/
6. https://www.codeschool.com/learn/ios

Program
Course Program Outcomes
Specific
Outcomes (POs)
Outcomes
(PSOs)
PO1 PO PO PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PS PSO PSO3 PSO
2 3 O1 2 4
CO1 3 2 2 3 3 3 3
CO2 3 2 3 2 1
CO3 3 2 3 2
CO4 3 2 3 3 3 3
CO5 3 2 3 2 1
CO6 3 2 3 3 3 3

PREPARED BY APPROVED BY

(Mr.Natarajan.C, ASP/CSE) (HOD/CSE)


UNIT-I

ANDROID OVERVIEW
Overview of Android platform- Android SDK features - setting up the mobile app
development environment along with an emulator- Android Application Development
Architecture - creating an applications and activities -Application manifest

Android

Android is a software package and linux based operating system for mobile devices such as
tablet computers and smartphones.

It is developed by Google and later the OHA (Open Handset Alliance). Java language is
mainly used to write the android code even though other languages can be used.

The goal of android project is to create a successful real-world product that improves the
mobile experience for end users.

There are many code names of android such as Lollipop, Kitkat, Jelly Bean, Ice cream
Sandwich, Froyo, Ecliar, Donut etc which is covered in next page.

Features of Android SDK

Android is a powerful open-source operating system that open-source provides immense


features and some of these are listed below.

 Android Open Source Project so we can customize the OS based on our requirements.
 Android supports different types of connectivity for GSM, CDMA, Wi-Fi, Bluetooth,
etc. for telephonic conversation or data transfer.
 Using wifi technology we can pair with other devices while playing games or using
other applications.
 It contains multiple APIs to support location-tracking services such as GPS.
 We can manage all data storage-related activities by using the file manager.
 It contains a wide range of media supports like AVI, MKV, FLV, MPEG4, etc. to play
or record a variety of audio/video.
 It also supports different image formats like JPEG, PNG, GIF, BMP, MP3, etc.
 It supports multimedia hardware control to perform playback or recording using a
camera and microphone.
 Android has an integrated open-source WebKit layout-based web browser to support
User Interfaces like HTML5, and CSS3.
 Android supports multi-tasking means we can run multiple applications at a time and
can switch between them.
 It provides support for virtual reality or 2D/3D Graphics.

Categories of Android applications


There are many android applications in the market. The top categories are:
o Entertainment
o Tools
o Communication
o Productivity
o Personalization
o Music and Audio
o Social
o Media and Video
o Travel and Local etc.
Programming Languages used in Developing Android Applications
1. Java
2. Kotlin
Developing the Android Application using Kotlin is preferred by Google, as Kotlin is made
an official language for Android Development, which is developed and maintained by
JetBrains. Previously before Java is considered the official language for Android
Development. Kotlin is made official for Android Development in Google I/O 2017.
Advantages of Android Development
 The Android is an open-source Operating system and hence possesses a vast community
for support.
 The design of the Android Application has guidelines from Google, which becomes
easier for developers to produce more intuitive user applications.
 Fragmentation gives more power to Android Applications. This means the application
can run two activities on a single screen.
 Releasing the Android application in the Google play store is easier when it is
compared to other platforms.
Disadvantages of Android Development
 Fragmentation provides a very intuitive approach to user experience but it has some
drawbacks, where the development team needs time to adjust to the various screen sizes
of mobile smartphones that are now available in the market and invoke the particular
features in the application.
 The Android devices might vary broadly. So the testing of the application becomes
more difficult.
 As the development and testing consume more time, the cost of the application may
increase, depending on the application’s complexity and features.
Android Architecture
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
android architecture
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 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.
Activity Manger:
gives information about, and interacts with, activities, services, and the containing process.
Windows Manager:
The interface that apps use to talk to the window manager. Each window manager instance
is bound to a Display.
Notification Manager
Android allows to put notification into the titlebar of your application. The user can expand
the notification bar and by selecting the notification the user can trigger another activity.
Package Manager
Package Manager is a highly powerful application to manage apps, both system and user,
installed on an android device.
Content Provider
Content Provider is a part of an android application and it will act like more like a
relational database to store the app data. We can perform multiple operations like insert,
update, delete and edit on the data stored in content provider
using insert(), update(), delete() and query() methods.
View sytems:
View system’s is a basic building block of UI (User Interface) in android. A view is a small
rectangular box that responds to user inputs. Eg: EditText, Button, CheckBox, etc.
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:
 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.
Topic 3:
 Start-> My computer -> local disk(c:) -> Program Files ->Android -> AndroidStudio -
> bin -> studio64
Dalvik Virtual Machine | DVM

As we know the modern JVM is high performance and provides excellent memory
management. But it needs to be optimized for low-powered handheld devices as well.

The Dalvik Virtual Machine (DVM) is an android virtual machine optimized for mobile
devices. It optimizes the virtual machine for memory, battery life and performance.

Dalvik is a name of a town in Iceland. The Dalvik VM was written by Dan Bornstein.

The Dex compiler converts the class files into the .dex file that run on the Dalvik VM.
Multiple class files are converted into one dex file.

Let's see the compiling and packaging process from the source file:
The javac tool compiles the java source file into the class file.

The dx tool takes all the class files of your application and generates a single .dex file. It is a
platform-specific tool.

The Android Assets Packaging Tool (aapt) handles the packaging process.

JVM (Java Virtual


S.NO DVM (Dalvik Virtual Machine)
Machine)

It is Register based which is designed to


1 It is Stack based.
run on low memory.

DVM uses its own byte code and runs the JVM uses java byte code and
2 “.Dex” file. From Android 2.2 SDK runs “.class” file having JIT
Dalvik has got a Just in Time compiler (Just In Time).

DVM has been designed so that a device


A single instance of JVM is
can run multiple instances of the VM
3 shared with multiple
efficiently. Applications are given their
applications.
own instance.

DVM supports the Android operating JVM supports multiple


4
system only. operating systems.

For JVM many Re-tools are


5 For DVM very few Re-tools are available
available.

6 There is a constant pool for every It has a constant pool for


JVM (Java Virtual
S.NO DVM (Dalvik Virtual Machine)
Machine)

application. every class.

7 Here the executable is APK. Here the executable is JAR.

CREATING ON APPLICATION AND ACTIVITIES

Android application:

It consists of loosely coupled components

Bound by an application manifest-that describes each component and how they all interact, as
well as application metadata including its hardware and platform requirements

The following six components provides the building block for your applications

 Activities
 Services
 Content Providers
 Intents
 Broadcast receivers
 Widgets

Activity

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.

File: activity_main.xml

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


2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/ap
k/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.
9. <TextView
10. android:layout_width="wrap_content"
11. android:layout_height="wrap_content"
12. android:text="Hello World!"
13. app:layout_constraintBottom_toBottomOf="parent"
14. app:layout_constraintLeft_toLeftOf="parent"
15. app:layout_constraintRight_toRightOf="parent"
16. app:layout_constraintTop_toTopOf="parent" />
17. </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

package example.javatpoint.com.activitylifecycle;
1. import android.app.Activity;
2. import android.os.Bundle;
3. import android.util.Log;
4.
5. public class MainActivity extends Activity {
6.
7. @Override
8. protected void onCreate(Bundle savedInstanceState) {
9. super.onCreate(savedInstanceState);
10. setContentView(R.layout.activity_main);
11. Log.d("lifecycle","onCreate invoked");
12. }
13. @Override
14. protected void onStart() {
15. super.onStart();
16. Log.d("lifecycle","onStart invoked");
17. }
18. @Override
19. protected void onResume() {
20. super.onResume();
21. Log.d("lifecycle","onResume invoked");
22. }
23. @Override
24. protected void onPause() {
25. super.onPause();
26. Log.d("lifecycle","onPause invoked");
27. }
28. @Override
29. protected void onStop() {
30. super.onStop();
31. Log.d("lifecycle","onStop invoked");
32. }
33. @Override
34. protected void onRestart() {
35. super.onRestart();
36. Log.d("lifecycle","onRestart invoked");
37. }
38. @Override
39. protected void onDestroy() {
40. super.onDestroy();
41. Log.d("lifecycle","onDestroy invoked");
42. }
43. }
Output:

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

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.

Android service is a component that is used to perform operations on the background such as
playing music, handle network transactions, interacting content providers etc. It doesn't has
any UI (user interface).

The service runs in the background indefinitely even if application is destroyed.

Moreover, service can be bounded by a component to perform interactivity and inter process
communication (IPC).

The android.app.Service is subclass of ContextWrapper class.

Life Cycle of Android Service

There can be two forms of a service.The lifecycle of service can follow two different paths:
started or bound.

1. Started
2. Bound
1) Started Service

A service is started when component (like activity) calls startService() method, now it runs in
the background indefinitely. It is stopped by stopService() method. The service can stop itself
by calling the stopSelf() method.

2) Bound Service

A service is bound when another component (e.g. client) calls bindService() method. The
client can unbind the service by calling the unbindService() method.

The service cannot be stopped until all clients unbind the service.

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


activities) to bind to the service, send requests, receive responses, and perform interprocess
communication (IPC)
Understanding Started and Bound Service by background music example

Suppose, I want to play music in the background, so call startService() method. But I want to
get information of the current song being played, I will bind the service that provides
information about the current song.

Android Service Example

Let's see the example of service in android that plays an audio in the background. Audio will
not be stopped even if you switch to another activity. To stop the audio, you need to stop the
service.
activity_main.xml

Drag the 3 buttons from the pallete, now the activity_main.xml will look like this:

File: activity_main.xml
1. <?xml version="1.0" encoding="utf-8"?>
2. <RelativeLayout 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="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.androidservice.MainActivity">
8.
9.
10. <Button
11. android:id="@+id/buttonStart"
12. android:layout_width="wrap_content"
13. android:layout_height="wrap_content"
14. android:layout_alignParentTop="true"
15. android:layout_centerHorizontal="true"
16. android:layout_marginTop="74dp"
17. android:text="Start Service" />
18.
19. <Button
20. android:id="@+id/buttonStop"
21. android:layout_width="wrap_content"
22. android:layout_height="wrap_content"
23. android:layout_centerHorizontal="true"
24. android:layout_centerVertical="true"
25. android:text="Stop Service" />
26.
27. <Button
28. android:id="@+id/buttonNext"
29. android:layout_width="wrap_content"
30. android:layout_height="wrap_content"
31. android:layout_alignParentBottom="true"
32. android:layout_centerHorizontal="true"
33. android:layout_marginBottom="63dp"
34. android:text="Next Page" />
35. </RelativeLayout>
activity_next.xml

It is the layout file of next activity.

File: activity_next.xml

It contains only one textview displaying the message Next Page

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


2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/ap
k/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.androidservice.NextPage">
8.
9. <TextView
10. android:id="@+id/textView"
11. android:layout_width="wrap_content"
12. android:layout_height="wrap_content"
13. android:layout_marginEnd="8dp"
14. android:layout_marginStart="8dp"
15. android:layout_marginTop="200dp"
16. android:text="Next Page"
17. app:layout_constraintEnd_toEndOf="parent"
18. app:layout_constraintStart_toStartOf="parent"
19. app:layout_constraintTop_toTopOf="parent" />
20. </android.support.constraint.ConstraintLayout>

Service class

Now create the service implemenation class by inheriting the Service class and overridding
its callback methods.

MyService.java

1. package example.javatpoint.com.androidservice;
2.
3. import android.app.Service;
4. import android.content.Intent;
5. import android.media.MediaPlayer;
6. import android.os.IBinder;
7. import android.support.annotation.Nullable;
8. import android.widget.Toast;
9.
10. public class MyService extends Service {
11. MediaPlayer myPlayer;
12. @Nullable
13. @Override
14. public IBinder onBind(Intent intent) {
15. return null;
16. }
17. @Override
18. public void onCreate() {
19. Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
20.
21. myPlayer = MediaPlayer.create(this, R.raw.sun);
22. myPlayer.setLooping(false); // Set looping
23. }
24. @Override
25. public void onStart(Intent intent, int startid) {
26. Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
27. myPlayer.start();
28. }
29. @Override
30. public void onDestroy() {
31. Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
32. myPlayer.stop();
33. }
34. }

Activity class

Now create the MainActivity class to perform event handling. Here, we are writing the code
to start and stop service. Additionally, calling the second activity on buttonNext.

File: MainActivity.java

1. package example.javatpoint.com.androidservice;
2.
3. import android.content.Intent;
4. import android.support.v7.app.AppCompatActivity;
5. import android.os.Bundle;
6. import android.view.View;
7. import android.widget.Button;
8.
9. public class MainActivity extends AppCompatActivity implements View.OnClickListener{
10. Button buttonStart, buttonStop,buttonNext;
11. @Override
12. protected void onCreate(Bundle savedInstanceState) {
13. super.onCreate(savedInstanceState);
14. setContentView(R.layout.activity_main);
15.
16. buttonStart = findViewById(R.id.buttonStart);
17. buttonStop = findViewById(R.id.buttonStop);
18. buttonNext = findViewById(R.id.buttonNext);
19.
20. buttonStart.setOnClickListener(this);
21. buttonStop.setOnClickListener(this);
22. buttonNext.setOnClickListener(this);
23.
24.
25. }
26. public void onClick(View src) {
27. switch (src.getId()) {
28. case R.id.buttonStart:
29.
30. startService(new Intent(this, MyService.class));
31. break;
32. case R.id.buttonStop:
33. stopService(new Intent(this, MyService.class));
34. break;
35. case R.id.buttonNext:
36. Intent intent=new Intent(this,NextPage.class);
37. startActivity(intent);
38. break;
39. }
40. }
41. }
NextPage class

Now, create another activity.

File: NextPage.java

1. package example.javatpoint.com.androidservice;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5.
6. public class NextPage extends AppCompatActivity {
7.
8. @Override
9. protected void onCreate(Bundle savedInstanceState) {
10. super.onCreate(savedInstanceState);
11. setContentView(R.layout.activity_next);
12. }
13. }

Declare the Service in the AndroidManifest.xml file

Finally, declare the service in the manifest file.

File: AndroidManifest.xml

Let's see the complete AndroidManifest.xml file

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


2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3. package="example.javatpoint.com.androidservice">
4.
5. <application
6. android:allowBackup="true"
7. android:icon="@mipmap/ic_launcher"
8. android:label="@string/app_name"
9. android:roundIcon="@mipmap/ic_launcher_round"
10. android:supportsRtl="true"
11. android:theme="@style/AppTheme">
12. <activity android:name=".MainActivity">
13. <intent-filter>
14. <action android:name="android.intent.action.MAIN" />
15.
16. <category android:name="android.intent.category.LAUNCHER" />
17. </intent-filter>
18. </activity>
19. <activity android:name=".NextPage"></activity>
20. <service
21. android:name=".MyService"
22. android:enabled="true" />
23. </application>
24.
25. </manifest>
Output:

https://data-flair.training/blogs/content-provider-in-android/
Content Providers in Android

Content Providers are an important component of Android. They handle the access to the
central repository and supply data from one application to another on request. This task of
handling is done by methods of ContentResolver class. So, content providers can store data in
various ways such as files, database or over the internet.
Many a time we need to share our data with applications and that’s where it becomes useful.
The following diagram depicts how the content provider helps in sharing data with
applications from data stores.

As can be seen, the content provider lets us collect the data centrally and provide them to
applications as shown in the above diagram. Content providers act the same as database and
also we can query it to add, delete, insert or update the data.

It can be understood that a content provider hides the database details and also, it lets an
application share data among other applications. Content providers are not limited to texts,
but also contains images and videos as well.

CRUD Operations

Content providers provide the following four basic operations. These are also known as
CRUD operations, where

C – Create
R – Read
U – Update
D – Delete
The above are the four operations of content providers :

 Create: It is used for the creation of data in content providers.


 Read: It reads the data stored in the content provider.
 Update: It lets the editing in existing data in content providers.
 Delete: It deletes the existing data stored in its Storage.
Examples of Android Content Providers

To understand content providers with examples, consider the following examples :

 The Gallery that contains images.


 Contact lists that contain Contact details.
 A dictionary that has collections of all the words that are used.
 The music playlist has a list of songs.
 Call logs contain the call details.
This is how exactly content providers work.

Accessing Data with Content Provider

We need to use the ContentResolver object in our application, in order to communicate with
the content providers for data access. Now to enable communication between the user
interface and ContentResolver, we use another object, CursorLoader to run query
asynchronously. This CursorLoader will be called using Activity/Fragment of the application.
Then, the content provider receives the query from the client and executes and returns the
result.

To understand how it works, consider the following diagram:


Methods of Content Provider in Android

Let’s see the following methods of content provider:

 onCreate() – This method in Android initializes the provider as soon as the receiver is
created.
 query() – It receives a request in the form of a query from the user and responds with a
cursor in Android.
 insert() – This method is used to insert the data into our content provider.
 update() – This method is used to update existing data in a row and return the updated
row data.
 delete() – This method deletes existing data from the content provider.
 getType() – It returns the Multipurpose Internet Mail Extension type of data to the given
Content URI.
Intent
Android uses Intent for communicating between the components of an Application and also
from one application to another application.
Intent are the objects which is used in android for passing the information among Activities
in an Application and from one app to another also. Intent are used for communicating
between the Application components and it also provides the connectivity between two apps.
For example: Intent facilitate you to redirect your activity to another activity on occurrence of
any event. By calling, startActivity() you can perform this task.

Intentintent=newIntent(getApplicationContext(),SecondActivity.class);
startActivity(intent);

In the above example, foreground activity is getting redirected to another activity i.e.
SecondActivity.java. getApplicationContext() returns the context for your foreground
activity.
Types of Intents:
Intent are of two types: Explicit Intent and Implicit Intent

Explicit Intent:

 Explicit Intents are used to connect the application internally.


 In Explicit we use the name of component which will be affected by Intent. For
Example: If we know class name then we can navigate the app from One Activity to
another activity using Intent. In the similar way we can start a service to download a
file in background process.

Explicit Intent work internally within an application to perform navigation and data transfer.
The below given code snippet will help you understand the concept of Explicit Intents

Intentintent=newIntent(getApplicationContext(),SecondActivity.class);
startActivity(intent);

Here SecondActivity is the JAVA class name where the activity will now be navigated.
Example with code in the end of this post will make it more clear.
Implicit Intent:

 In Implicit Intents we do need to specify the name of the component. We just specify
the Action which has to be performed and further this action is handled by the
component of another application.
 The basic example of implicit Intent is to open any web page

Let’s take an example to understand Implicit Intents more clearly. We have to open a website
using intent in your application. See the code snippet given below

IntentintentObj=newIntent(Intent.ACTION_VIEW);
intentObj.setData(Uri.parse("https://www.abhiandroid.com"));
startActivity(intentObj);

Unlike Explicit Intent you do not use any class name to pass through Intent(). In this example
we have just specified an action. Now when we will run this code then Android will
automatically start your web browser and it will open AbhiAndroid home page.
Broadcast Receivers
Broadcast Receivers simply respond to broadcast messages from other applications or from
the system itself. These messages are sometime called events or intents. For example,
applications can also initiate broadcasts to let other applications know that some data has
been downloaded to the device and is available for them to use, so this is broadcast receiver
who will intercept this communication and will initiate appropriate action.
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.
publicclassMyReceiverextendsBroadcastReceiver{
@Override
publicvoidonReceive(Context context,Intent intent){
Toast.makeText(context,"Intent Detected.",Toast.LENGTH_LONG).show();
}
}
Registering Broadcast Receiver
An application listens for specific broadcast intents by registering a broadcast receiver
in AndroidManifest.xml file. Consider we are going to register MyReceiver for system
generated event ACTION_BOOT_COMPLETED which is fired by the system once the
Android system has completed the boot process.

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

<intent-filter>
<actionandroid: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.

2 android.intent.action.BATTERY_LOW
Indicates low battery condition on the device.

3 android.intent.action.BATTERY_OKAY
Indicates the battery is now okay after being low.

4 android.intent.action.BOOT_COMPLETED
This is broadcast once, after the system has finished booting.
5 android.intent.action.BUG_REPORT
Show activity for reporting a bug.

6 android.intent.action.CALL
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.

8 android.intent.action.DATE_CHANGED
The date has changed.

9 android.intent.action.REBOOT
Have the device reboot.

Android Widgets

There are given a lot of android widgets with simplified examples such as Button, EditText,
AutoCompleteTextView, ToggleButton, DatePicker, TimePicker, ProgressBar etc.

Android widgets are easy to learn. The widely used android widgets with examples are given
below:

Android Button

Let's learn how to perform event handling on button click.

Android Toast

Displays information for the short duration of time.

Custom Toast

We are able to customize the toast, such as we can display image on the toast

ToggleButton

It has two states ON/OFF.

CheckBox
Let's see the application of simple food ordering.

AlertDialog

AlertDialog displays a alert dialog containing the message with OK and Cancel buttons.

Spinner

Spinner displays the multiple options, but only one can be selected at a time.

AutoCompleteTextView

Let's see the simple example of AutoCompleteTextView.

RatingBar

RatingBar displays the rating bar.

DatePicker

Datepicker displays the datepicker dialog that can be used to pick the date.

TimePicker

TimePicker displays the timepicker dialog that can be used to pick the time.

ProgressBar

ProgressBar displays progress task.

Application Android Manifest:

As we know that every android project that we make, need to have an Android Manifest file
within. This file is present in the root of the project source set. The reason why it is a must to
have it is that it describes all the important information of the application to the Android build
tools.
The manifest file in Android is generally created automatically as soon as the app is built in
Android Studio.
Structure of a Manifest file in Android is:
<manifest>
<application>
<activity android:name="com.example.applicationname.MainActivity">
</activity>
</application>
</manifest>
The information that is stored in the Manifest file is as follows:

 The name of the application’s package, it is generally the code’s namespace. This
information is used to determine the location of the code while building the project.
 Another component is the one, that includes all the activities, services, receivers, and
content providers.
 The permissions that are required by the application to access the protected parts of the
system and other apps.
 The features required by the app, that affect which devices can install the app from
Google Play. These features include both hardware and software features.
 It also specifies the application metadata, which includes the icon, version number,
themes, etc.
The android manifest.xml file generally looks like the following:

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myfirstapplication">
<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" />
</application>
</manifest>
Element Tags of Manifest File

Following are the essential element tags of Manifest.xml files:

1. <manifest>
It is the root element of this element. It consists of a package attribute package that tells the
activity’s package name.
2. <application>
It is the subelement of the manifest file that includes the declaration of the namespace. It
contains certain attributes. These attributes declare the application components, and these
attributes include:
 icon
 allowBackup
 label
 theme
3. <activity>
Activity is a subelement of application. It has the declaration of the activity that must be there
in the manifest file. It also has certain attributes like name, label, theme, etc.
4. <intent-filter>
It is an element in the activity, it describes the type of intent in which the Android
components can respond.
5. <action>
This element provides an action for the intent filter. Each intent filter must have at least one
action element in it.
6. <category>
This element adds the category name in an intent-filter.
7. <service>
This element contains the operations that are provided by libraries or APIs.
Manifest File Application Property Elements

Following is a list of important Application Property Elements in manifest.xml (Sub- Node


Elements)

1. <uses-permission>: This element specifies the Android Manifest permissions that are
requested for the purpose of security.
2. <permission>: This element sets permission to provide access to control for some
components of the app.
3. <permission-groups>: This element sets permission to provide access to control for a set
of components of the app.
4. <permission-tree>: This element refers to a specific component that is the owner of the
set of components.
5. <instrumentation>: This element tells the interaction between the app and the system.
6. <uses-sdk>: This one specifies the compatibility of the app.
7. <uses-configuration>: This element specifies the permissions that are requested for the
purpose of security.
8. <uses-feature>: This element specifies one hardware or software feature that is required
by the Application.
9. <supports-screen, compatible-screen>: These elements tell the screen size and
configuration.
How to set Manifest File Permissions in Android?

Now in this part of the tutorial, we’ll see how to set permission in a Manifest file.

An android application must get some permissions to get access to other apps or the Internet.
While we build our app, the manifest file gets automatically generated as manifest.xml. This
manifest file contains permissions that are configured by us. A few permissions are applied
by default if there is no permission provided by us.

These are written in the manifest file as:

<manifest >

<uses-permission .../>

...

<manifest >
The permission mentioned in the manifest file can be either granted or rejected by the users.
Once the user grants permission to the app, the app can use the protected features. If the user
denies permission the app doesn’t get permission to access the protected features.

The following permissions are added by default and set to TRUE:

 INTERNET
 ACCESS_NETWORK_STATE
 READ_PHONE_STATE
There are many permissions that are set to FALSE by default but can be set to TRUE as per
requirements. A few of these permissions are as follows:

ACCESS_WIFI_S AUTHENTICATE_ACCO BATTERY_STAT


BLUETOOTH
TATE UNT S
BIND_APPWIDG BROADCAST_WAP_PUS BROADCAST_STI BIND_INPUT_ME
ET H CKY THOD
CHANGE_CONFIGURATI CLEAR_APP_DA
CALL_PHONE CAMERA
ON TA
CHANGE_WIFI_S CLEAR_APP_USER_DAT DELETE_CACHE
DEVICE_POWER
TATE A _FILES
DISABLE_KEYG EXPAND_STATU EXPAND_STATU
DELETE_PACKAGES
UARD S_BAR S_BAR
GLOBAL_SEARC
FACTORY_TEST GET_PACKAGE_SIZE FLASHLIGHT
H
HARDWARE_TES INTERNAL_SYSTEM_PR USE_CREDENTIA MANAGE_ACCO
T OCESSES LS UNTS
MANAGE_APP_T MODIFY_AUDIO_SETTI MODIFY_PHONE
NFC
OKENS NGS _STATE
PROCESS_OUTGOING_C SET_ALWAYS_F
SEND_SMS SET_ALARM
ALLS INISH
READ_CALENDA KILL_BACKGROUND_P SET_WALLPAPE
VIBRATE
R ROCESSES R
WRITE_CALEND WARITE_SETTIN
WAKE_LOCK WRITE_APN_SETTINGS
AR GS
UNIT-II

INTERFACE TOOLS
Creating user interface - Views - creating views - Layouts - Drawable resources - resolution and
density independence - Menus - Intents - Adapters - Using Internet resources - Dialogs.

Creating user interface

In android, Layout is used to define the user interface for an app or activity and it will hold the UI
elements that will appear to the user.

The user interface in an android app is made with a collection of View and ViewGroup objects.
Generally, the android apps will contain one or more activities and each activity is a one screen of
app. The activities will contain a multiple UI components and those UI components are the instances
of View and ViewGroup subclasses.

The user interface in an android app is made with a collection of View and ViewGroup objects.
Generally, the android apps will contain one or more activities and each activity is a one screen of the
app. The activities will contain multiple UI components and those UI components are the instances
of View and ViewGroup subclasses.

Android View
The View is a base class for all UI components in android. For example, the EditText class is
used to accept the input from users in android apps, which is a subclass of View.

Following are the some of common View subclasses that will be used in android applications.

 TextView
 EditText
 Button
 CheckBox
 RadioButton
 ImageButton
 Progress Bar
 Spinner

Like these we have many View subclasses available in android.


Android Button Example

Android Button represents a push-button. The android.widget.Button is subclass of TextView class


and CompoundButton is the subclass of Button class.

There are different types of buttons in android such as RadioButton, ToggleButton, CompoundButton
etc.

Android Button Example with Listener


Here, we are going to create two textfields and one button for sum of two numbers. If user clicks
button, sum of two input values is displayed on the Toast.

We can perform action on button using different types such as calling listener on button or adding
onClick property of button in activity's xml file.

1. button.setOnClickListener(new View.OnClickListener() {
2. @Override
3. public void onClick(View view) {
4. //code
5. }
6. });

1. <Button
2. android:onClick="methodName"
3. />
File: activity_main.xml

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


2. <RelativeLayout 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="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.sumoftwonumber.MainActivity">
8.
9. <EditText
10. android:id="@+id/editText1"
11. android:layout_width="wrap_content"
12. android:layout_height="wrap_content"
13. android:layout_alignParentTop="true"
14. android:layout_centerHorizontal="true"
15. android:layout_marginTop="61dp"
16. android:ems="10"
17. android:inputType="number"
18. tools:layout_editor_absoluteX="84dp"
19. tools:layout_editor_absoluteY="53dp" />
20.
21. <EditText
22. android:id="@+id/editText2"
23. android:layout_width="wrap_content"
24. android:layout_height="wrap_content"
25. android:layout_below="@+id/editText1"
26. android:layout_centerHorizontal="true"
27. android:layout_marginTop="32dp"
28. android:ems="10"
29. android:inputType="number"
30. tools:layout_editor_absoluteX="84dp"
31. tools:layout_editor_absoluteY="127dp" />
32.
33. <Button
34. android:id="@+id/button"
35. android:layout_width="wrap_content"
36. android:layout_height="wrap_content"
37. android:layout_below="@+id/editText2"
38. android:layout_centerHorizontal="true"
39. android:layout_marginTop="109dp"
40. android:text="ADD"
41. tools:layout_editor_absoluteX="148dp"
42. tools:layout_editor_absoluteY="266dp" />
43. </RelativeLayout>

Activity class
Now write the code to display the sum of two numbers.

File: MainActivity.java

1. package example.javatpoint.com.sumoftwonumber;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.widget.Button;
7. import android.widget.EditText;
8. import android.widget.Toast;
9.
10. public class MainActivity extends AppCompatActivity {
11. private EditText edittext1, edittext2;
12. private Button buttonSum;
13.
14. @Override
15. protected void onCreate(Bundle savedInstanceState) {
16. super.onCreate(savedInstanceState);
17. setContentView(R.layout.activity_main);
18.
19. addListenerOnButton();
20. }
21.
22. public void addListenerOnButton() {
23. edittext1 = (EditText) findViewById(R.id.editText1);
24. edittext2 = (EditText) findViewById(R.id.editText2);
25. buttonSum = (Button) findViewById(R.id.button);
26.
27. buttonSum.setOnClickListener(new View.OnClickListener() {
28. @Override
29. public void onClick(View view) {
30. String value1=edittext1.getText().toString();
31. String value2=edittext2.getText().toString();
32. int a=Integer.parseInt(value1);
33. int b=Integer.parseInt(value2);
34. int sum=a+b;
35. Toast.makeText(getApplicationContext(),String.valueOf(sum), Toast.LENGTH_LONG).sh
ow();
36. }
37. });
38. }
39. }

Ouput:
Android Toast Example

Andorid Toast can be used to display information for the short period of time. A toast contains
message to be displayed quickly and disappears after sometime.

The android.widget.Toast class is the subclass of java.lang.Object class.

You can also create custom toast as well for example toast displaying image. You can visit next page
to see the code for custom toast.

Toast class
Toast class is used to show notification for a particular interval of time. After sometime it disappears.
It doesn't block the user interaction.

Constants of Toast class

There are only 2 constants of Toast class which are given below.

Constant Description

public static final int LENGTH_LONG displays view for the long duration of time.

public static final int LENGTH_SHORT displays view for the short duration of time.

Android Toast Example

1. Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LENGTH_SHORT)
.show();

Another code:

1. Toast toast=Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LENGTH_SH


ORT);
2. toast.setMargin(50,50);
3. toast.show();

Here, getApplicationContext() method returns the instance of Context.


1. Example
package example.javatpoint.com.toast;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.widget.Toast;
6.
7. public class MainActivity extends AppCompatActivity {
8.
9. @Override
10. protected void onCreate(Bundle savedInstanceState) {
11. super.onCreate(savedInstanceState);
12. setContentView(R.layout.activity_main);
13.
14. //Displaying Toast with Hello Javatpoint message
15. Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LENGTH_SHORT).show();
16. }
17. }

Output:
Android ToggleButton Example

Android Toggle Button can be used to display checked/unchecked (On/Off) state on the button.

It is beneficial if user have to change the setting between two states. It can be used to On/Off Sound,
Wifi, Bluetooth etc.

Since Android 4.0, there is another type of toggle button called switch that provides slider control.

Android ToggleButton and Switch both are the subclasses of CompoundButton class.

Android ToggleButton class


ToggleButton class provides the facility of creating the toggle button.

XML Attributes of ToggleButton class


The 3 XML attributes of ToggleButton class.

XML Attribute Description

android:disabledAlpha The alpha to apply to the indicator when disabled.

android:textOff The text for the button when it is not checked.

android:textOn The text for the button when it is checked.


Methods of ToggleButton class
The widely used methods of ToggleButton class are given below.

Method Description

CharSequence getTextOff() Returns the text when button is not in the checked state.

CharSequence getTextOn() Returns the text for when button is in the checked state.

void setChecked(boolean checked) Changes the checked state of this button.

activity_main.xml

Drag two toggle button and one button for the layout. Now the activity_main.xml file will look like
this:

File: activity_main.xml

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


2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/re
s/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.togglebutton.MainActivity">
8.
9. <ToggleButton
10. android:id="@+id/toggleButton"
11. android:layout_width="wrap_content"
12. android:layout_height="wrap_content"
13. android:layout_marginLeft="8dp"
14. android:layout_marginTop="80dp"
15. android:text="ToggleButton"
16. android:textOff="Off"
17. android:textOn="On"
18. app:layout_constraintEnd_toStartOf="@+id/toggleButton2"
19. app:layout_constraintStart_toStartOf="parent"
20. app:layout_constraintTop_toTopOf="parent" />
21.
22. <ToggleButton
23. android:id="@+id/toggleButton2"
24. android:layout_width="wrap_content"
25. android:layout_height="wrap_content"
26. android:layout_marginRight="60dp"
27. android:layout_marginTop="80dp"
28. android:text="ToggleButton"
29. android:textOff="Off"
30. android:textOn="On"
31. app:layout_constraintEnd_toEndOf="parent"
32. app:layout_constraintTop_toTopOf="parent" />
33.
34. <Button
35. android:id="@+id/button"
36. android:layout_width="wrap_content"
37. android:layout_height="wrap_content"
38. android:layout_marginBottom="144dp"
39. android:layout_marginLeft="148dp"
40. android:text="Submit"
41. app:layout_constraintBottom_toBottomOf="parent"
42. app:layout_constraintStart_toStartOf="parent" />
43. </android.support.constraint.ConstraintLayout>

Activity class
File: MainActivity.java
1. package example.javatpoint.com.togglebutton;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.widget.Button;
7. import android.widget.Toast;
8. import android.widget.ToggleButton;
9.
10. public class MainActivity extends AppCompatActivity {
11. private ToggleButton toggleButton1, toggleButton2;
12. private Button buttonSubmit;
13. @Override
14. protected void onCreate(Bundle savedInstanceState) {
15. super.onCreate(savedInstanceState);
16. setContentView(R.layout.activity_main);
17.
18. addListenerOnButtonClick();
19. }
20.
21. public void addListenerOnButtonClick(){
22. //Getting the ToggleButton and Button instance from the layout xml file
23. toggleButton1=(ToggleButton)findViewById(R.id.toggleButton);
24. toggleButton2=(ToggleButton)findViewById(R.id.toggleButton2);
25. buttonSubmit=(Button)findViewById(R.id.button);
26.
27. //Performing action on button click
28. buttonSubmit.setOnClickListener(new View.OnClickListener(){
29.
30. @Override
31. public void onClick(View view) {
32. StringBuilder result = new StringBuilder();
33. result.append("ToggleButton1 : ").append(toggleButton1.getText());
34. result.append("\nToggleButton2 : ").append(toggleButton2.getText());
35. //Displaying the message in toast
36. Toast.makeText(getApplicationContext(), result.toString(),Toast.LENGTH_LONG).show()
;
37. }
38.
39. });
40.
41. }
42. }
Output:

Android CheckBox Example

Android CheckBox is a type of two state button either checked or unchecked.


There can be a lot of usage of checkboxes. For example, it can be used to know the hobby of the user,
activate/deactivate the specific action etc.

Android CheckBox class is the subclass of CompoundButton class.

Android CheckBox class


The android.widget.CheckBox class provides the facility of creating the CheckBoxes.

Methods of CheckBox class

There are many inherited methods of View, TextView, and Button classes in the CheckBox class.
Some of them are as follows:

Method Description

public boolean isChecked() Returns true if it is checked otherwise false.

public void setChecked(boolean status) Changes the state of the CheckBox.

Android CheckBox Example


activity_main.xml

Drag the three checkboxes and one button for the layout. Now the activity_main.xml file will look
like this:

File: activity_main.xml

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


2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/re
s/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.checkbox.MainActivity">
8.
9.
10. <CheckBox
11. android:id="@+id/checkBox"
12. android:layout_width="wrap_content"
13. android:layout_height="wrap_content"
14. android:layout_marginLeft="144dp"
15. android:layout_marginTop="68dp"
16. android:text="Pizza"
17. app:layout_constraintStart_toStartOf="parent"
18. app:layout_constraintTop_toTopOf="parent" />
19.
20. <CheckBox
21. android:id="@+id/checkBox2"
22. android:layout_width="wrap_content"
23. android:layout_height="wrap_content"
24. android:layout_marginLeft="144dp"
25. android:layout_marginTop="28dp"
26. android:text="Coffee"
27. app:layout_constraintStart_toStartOf="parent"
28. app:layout_constraintTop_toBottomOf="@+id/checkBox" />
29.
30. <CheckBox
31. android:id="@+id/checkBox3"
32. android:layout_width="wrap_content"
33. android:layout_height="wrap_content"
34. android:layout_marginLeft="144dp"
35. android:layout_marginTop="28dp"
36. android:text="Burger"
37. app:layout_constraintStart_toStartOf="parent"
38. app:layout_constraintTop_toBottomOf="@+id/checkBox2" />
39.
40. <Button
41. android:id="@+id/button"
42. android:layout_width="wrap_content"
43. android:layout_height="wrap_content"
44. android:layout_marginLeft="144dp"
45. android:layout_marginTop="184dp"
46. android:text="Order"
47. app:layout_constraintStart_toStartOf="parent"
48. app:layout_constraintTop_toBottomOf="@+id/checkBox3" />
49.
50. </android.support.constraint.ConstraintLayout>
Activity class
File: MainActivity.java
1. package example.javatpoint.com.checkbox;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.widget.Button;
7. import android.widget.CheckBox;
8. import android.widget.Toast;
9.
10. public class MainActivity extends AppCompatActivity {
11. CheckBox pizza,coffe,burger;
12. Button buttonOrder;
13. @Override
14. protected void onCreate(Bundle savedInstanceState) {
15. super.onCreate(savedInstanceState);
16. setContentView(R.layout.activity_main);
17. addListenerOnButtonClick();
18. }
19. public void addListenerOnButtonClick(){
20. //Getting instance of CheckBoxes and Button from the activty_main.xml file
21. pizza=(CheckBox)findViewById(R.id.checkBox);
22. coffe=(CheckBox)findViewById(R.id.checkBox2);
23. burger=(CheckBox)findViewById(R.id.checkBox3);
24. buttonOrder=(Button)findViewById(R.id.button);
25.
26. //Applying the Listener on the Button click
27. buttonOrder.setOnClickListener(new View.OnClickListener(){
28.
29. @Override
30. public void onClick(View view) {
31. int totalamount=0;
32. StringBuilder result=new StringBuilder();
33. result.append("Selected Items:");
34. if(pizza.isChecked()){
35. result.append("\nPizza 100Rs");
36. totalamount+=100;
37. }
38. if(coffe.isChecked()){
39. result.append("\nCoffe 50Rs");
40. totalamount+=50;
41. }
42. if(burger.isChecked()){
43. result.append("\nBurger 120Rs");
44. totalamount+=120;
45. }
46. result.append("\nTotal: "+totalamount+"Rs");
47. //Displaying the message on the toast
48. Toast.makeText(getApplicationContext(), result.toString(), Toast.LENGTH_LONG).show(
);
49. }
50.
51. });
52. }
53. }
Output:

Android ViewGroup
The ViewGroup is a subclass of View and it will act as a base class for layouts and layouts parameters.
The ViewGroup will provide an invisible containers to hold other Views or ViewGroups and to define the layout
properties.

For example, Linear Layout is the ViewGroup that contains a UI controls like button, textview, etc. and other layouts
also.

Following are the commonly used ViewGroup subclasses in android applications.

 Linear Layout
 Relative Layout
 Table Layout
 Frame Layout
 Web View
 List View
 Grid View

Both View and ViewGroup subclasses together will play a key role to create a layouts in android applications.
Android LinearLayout with Examples
In android, LinearLayout is a ViewGroup subclass which is used to render all child View instances one by one
either in Horizontal direction or Vertical direction based on the orientation property.

In android, we can specify the linear layout orientation using android:orientation attribute.

Following is the pictorial representation of linear layout in android applications.

In LinearLayout, the child View instances arranged one by one, so the horizontal list will have only one row of
multiple columns and vertical list will have one column of multiple rows.

Android LinearLayout Declaration


Following is the way we need to define the LinearLayout in android applications.

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<!-- Add Child Views Here -->
</LinearLayout>
If you observe above code snippet, here we defined orientation as vertical, so this aligns all its child layout / views
vertically.

Android LinearLayout Example


Following is the example of creating a LinearLayout with different controls in android application.

Create a new android application using android studio and give names as LinearLayout. In case if you are not aware
of creating an app in android studio check this article Android Hello World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown below

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:orientation="vertical" >
<EditText
android:id="@+id/txtTo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="To"/>
<EditText
android:id="@+id/txtSub"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Subject"/>
<EditText
android:id="@+id/txtMsg"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="top"
android:hint="Message"/>
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Send"/>
</LinearLayout>
Once we are done with creation of layout, we need to load the XML layout resource from
our activity onCreate() callback method, for that open main activity
file MainActivity.java from \java\com.tutlane.linearlayout path and write the code like as shown below.

MainActivity.java
package com.tutlane.linearlayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
If you observe above code we are calling our layout using setContentView method in the form
of R.layout.layout_file_name. Here our xml file name is activity_main.xml so we used file name activity_main.

Generally, during the launch of our activity, the onCreate() callback method will be called by the android framework
to get the required layout for an activity.

Output of Android LinearLayout Example


When we run above example using the android virtual device (AVD) we will get a result like as shown below.
Android RelativeLayout with Examples
In android, RelativeLayout is a ViewGroup which is used to specify the position of child View instances
relative to each other (Child A to the left of Child B) or relative to the parent (Aligned to the top of parent).

Following is the pictorial representation of relative layout in android applications.


n android, RelativeLayout is very useful to design user interface because by using relative layout we can
eliminate the nested view groups and keep our layout hierarchy flat, which improves the performance of
application.

Android Positioning Views in Relative Layout


As we discussed, in RelativeLayout we need to specify the position of child views relative to each other
or relative to the parent. In case if we didn’t specify the position of child views, by default all child views
are positioned to top-left of the layout.

Following are the some of most useful layout properties available to views in RelativeLayout.

Attribute Description

layout_alignParentTop If it specified “true”, the top edge of view will match the top edge of the parent.

layout_alignParentBottom If it specified “true”, the bottom edge of view will match the bottom edge of parent.

layout_alignParentLeft If it specified “true”, the left edge of view will match the left edge of parent.

layout_alignParentRight If it specified “true”, the right edge of view will match the right edge of the parent.

layout_centerInParent If it specified “true”, the view will be aligned to the centre of parent.

layout_centerHorizontal If it specified “true”, the view will be horizontally centre aligned within its parent.

layout_centerVertical If it specified “true”, the view will be vertically centre aligned within its parent.

layout_above It accepts another sibling view id and places the view above the specified view id.

layout_below It accepts another sibling view id and places the view below the specified view id.

layout_toLeftOf It accepts another sibling view id and places the view left of the specified view id.

layout_toRightOf It accepts another sibling view id and places the view right of the specified view id.

layout_toStartOf It accepts another sibling view id and places the view to start of the specified view id.
Attribute Description

layout_toEndOf It accepts another sibling view id and places the view to the end of the specified view id.

Android RelativeLayout Example


Following is the example of creating a RelativeLayout with different controls in android application.

Create a new android application using android studio and give names as RelativeLayout. In case if you
are not aware of creating an app in android studio check this article Android Hello World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown below

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text="Button1" />
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="Button2" />
<Button
android:id="@+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Button3" />

<Button
android:id="@+id/btn4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Button4" />
<Button
android:id="@+id/btn5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/btn2"
android:layout_centerHorizontal="true"
android:text="Button5" />
<Button
android:id="@+id/btn6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/btn4"
android:layout_centerHorizontal="true"
android:text="Button6" />
<Button
android:id="@+id/btn7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="@+id/btn1"
android:layout_toRightOf="@+id/btn1"
android:layout_alignParentRight="true"
android:text="Button7" />
</RelativeLayout>
Once we are done with creation of layout, we need to load the XML layout resource from
our activity onCreate() callback method, for that open main activity
file MainActivity.java from \java\com.tutlane.relativelayout path and write the code like as shown
below.

MainActivity.java
package com.tutlane.linearlayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
If you observe above code we are calling our layout using setContentView method in the form
of R.layout.layout_file_name. Here our xml file name is activity_main.xml so we used file
name activity_main.

Generally, during the launch of our activity, onCreate() callback method will be called by the android
framework to get the required layout for an activity.

Output of Android RelativeLayout Example


When we run above example using the android virtual device (AVD) we will get a result like as shown
below.

This is how we can use RelativeLayout in android applications based on our requirements.

Android TableLayout with Examples


In android, TableLayout is a ViewGroup subclass that is used to display the child View elements in rows and
columns.

Following is the pictorial representation of table layout in android applications.


In android, TableLayout will position its children elements into rows and columns and it won’t display any
border lines for rows, columns or cells.

The TableLayout in android will work same as the HTML table and the table will have as many columns
as the row with the most cells. The TableLayout can be explained as <table> and TableRow is
like <tr> element.

Android TableLayout Example


Following is the example of creating a TableLayout with different controls in android application.

Create a new android application using android studio and give names as TableLayout. In case if you are
not aware of creating an app in android studio check this article Android Hello World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown below

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="100dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" >
<TableRow android:background="#0079D6" android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="UserId" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="User Name" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Location" />
</TableRow>
<TableRow android:background="#DAE8FC" android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Suresh Dasari" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Hyderabad" />
</TableRow>
<TableRow android:background="#DAE8FC" android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Rohini Alavala" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Guntur" />
</TableRow>
<TableRow android:background="#DAE8FC" android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="3" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Trishika Dasari" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Guntur" />
</TableRow>
</TableLayout>
Once we are done with creation of layout, we need to load the XML layout resource from
our activity onCreate() callback method, for that open main activity
file MainActivity.java from \java\com.tutlane.tablelayout path and write the code like as shown below.

MainActivity.java
package com.tutlane.linearlayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
If you observe above code, we are calling our layout using setContentView method in the form
of R.layout.layout_file_name. Here our xml file name is activity_main.xml so we used file
name activity_main.

Generally, during the launch of our activity, onCreate() callback method will be called by android
framework to get the required layout for an activity.

Output of Android TableLayout Example


When we run above example using the android virtual device (AVD) we will get a result like as shown
below.
This is how we can use the table layout in android applications based on our requirements.

Android FrameLayout with Examples


In android, Framelayout is a ViewGroup subclass that is used to specify the position of View instances it contains on
the top of each other to display only single View inside the FrameLayout.

In simple manner, we can say FrameLayout is designed to block out an area on the screen to display a single item.

Following is the pictorial representation of frame layout in android applications.


In android, FrameLayout will act as a placeholder on the screen and it is used to hold a single child view.

In FrameLayout, the child views are added in a stack and the most recently added child will show on the top. We can
add multiple children views to FrameLayout and control their position by using gravity attributes in FrameLayout.

Android FrameLayout Example


Following is the example of creating a FrameLayout with different controls in android application.

Create a new android application using android studio and give names as FrameLayout. In case if you are not aware
of creating an app in android studio check this article Android Hello World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown below

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/imgvw1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:src="@drawable/flimg" />
<TextView
android:id="@+id/txtvw1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:background="#4C374A"
android:padding="10dp"
android:text="Grand Palace, Bangkok"
android:textColor="#FFFFFF"
android:textSize="20sp" />
<TextView
android:id="@+id/txtvw2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|bottom"
android:background="#AA000000"
android:padding="10dp"
android:text="21/Aug/2017"
android:textColor="#FFFFFF"
android:textSize="18sp" />
</FrameLayout>
If you observe above code we used ImageView to show the image (flimg) from drawable folder in framelayout. So
add your image to drawable folder and replace @drawable/flimg path with your image path.

Once we are done with the creation of layout, we need to load the XML layout resource from
our activity onCreate() callback method, for that open main activity
file MainActivity.java from \java\com.tutlane.framelayout path and write the code like as shown below.

MainActivity.java
package com.tutlane.linearlayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
If you observe above code, we are calling our layout using setContentView method in the form
of R.layout.layout_file_name. Here our xml file name is activity_main.xml so we used file name activity_main.

Generally, during the launch of our activity, the onCreate() callback method will be called by the android framework
to get the required layout for an activity.

Output of Android FrameLayout Example


When we run the above example using the android virtual device (AVD) we will get a result like as shown below.
This is how we can use frame layout in android applications based on our requirements.

Android AlertDialog Example

Android AlertDialog can be used to display the dialog message with OK and Cancel buttons. It can
be used to interrupt and ask the user about his/her choice to continue or discontinue.

Android AlertDialog is composed of three regions: title, content area and action buttons.

Android AlertDialog is the subclass of Dialog class.


Android AlertDialog Example

Android AlertDialog can be used to display the dialog message with OK and Cancel buttons. It can
be used to interrupt and ask the user about his/her choice to continue or discontinue.

Android AlertDialog is composed of three regions: title, content area and action buttons.

Android AlertDialog is the subclass of Dialog class.

Methods of AlertDialog class

Method Description

public AlertDialog.Builder setTitle(CharSequence) This method is used to set the title of


AlertDialog.

public AlertDialog.Builder This method is used to set the message for


setMessage(CharSequence) AlertDialog.

public AlertDialog.Builder setIcon(int) This method is used to set the icon over
AlertDialog.

Android AlertDialog Example


Let's see a simple example of android alert dialog.

activity_main.xml

You can have multiple components, here we are having only a textview.

File: activity_main.xml

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


2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.co
m/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.alertdialog.MainActivity">
8.
9. <Button
10. android:layout_width="wrap_content"
11. android:layout_height="wrap_content"
12. android:id="@+id/button"
13. android:text="Close app"
14. app:layout_constraintBottom_toBottomOf="parent"
15. app:layout_constraintLeft_toLeftOf="parent"
16. app:layout_constraintRight_toRightOf="parent"
17. app:layout_constraintTop_toTopOf="parent" />
18.
19. </android.support.constraint.ConstraintLayout>

strings.xml

Optionally, you can store the dialog message and title in the strings.xml file.

File: strings.xml

1. <resources>
2. <string name="app_name">AlertDialog</string>
3. <string name="dialog_message">Welcome to Alert Dialog</string>
4. <string name="dialog_title">Javatpoint Alert Dialog</string>
5. </resources>

Activity class

Let's write the code to create and show the AlertDialog.

File: MainActivity.java

1. package example.javatpoint.com.alertdialog;
2.
3. import android.content.DialogInterface;
4. import android.support.v7.app.AppCompatActivity;
5. import android.os.Bundle;
6. import android.view.View;
7. import android.widget.Button;
8. import android.app.AlertDialog;
9. import android.widget.Toast;
10.
11. public class MainActivity extends AppCompatActivity {
12. Button closeButton;
13. AlertDialog.Builder builder;
14. @Override
15. protected void onCreate(Bundle savedInstanceState) {
16. super.onCreate(savedInstanceState);
17. setContentView(R.layout.activity_main);
18.
19. closeButton = (Button) findViewById(R.id.button);
20. builder = new AlertDialog.Builder(this);
21. closeButton.setOnClickListener(new View.OnClickListener() {
22. @Override
23. public void onClick(View v) {
24.
25. //Uncomment the below code to Set the message and title from the strings.xml file

26. builder.setMessage(R.string.dialog_message) .setTitle(R.string.dialog_title);


27.
28. //Setting message manually and performing action on button click
29. builder.setMessage("Do you want to close this application ?")
30. .setCancelable(false)
31. .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
32. public void onClick(DialogInterface dialog, int id) {
33. finish();
34. Toast.makeText(getApplicationContext(),"you choose yes action for alertbox",

35. Toast.LENGTH_SHORT).show();
36. }
37. })
38. .setNegativeButton("No", new DialogInterface.OnClickListener() {
39. public void onClick(DialogInterface dialog, int id) {
40. // Action for 'NO' Button
41. dialog.cancel();
42. Toast.makeText(getApplicationContext(),"you choose no action for alertbox",

43. Toast.LENGTH_SHORT).show();
44. }
45. });
46. //Creating dialog box
47. AlertDialog alert = builder.create();
48. //Setting the title manually
49. alert.setTitle("AlertDialogExample");
50. alert.show();
51. }
52. });
53. }
54. }

Output:
Adapter
Adapter is a bridge between UI component and data source that helps us to fill data in UI
component. It holds the data and send the data to an Adapter view then view can takes the data
from the adapter view and shows the data on different views like
as ListView, GridView, Spinner etc. For more customization in Views we uses the base adapter or
custom adapters.
To fill data in a list or a grid we need to implement Adapter. Adapters acts like a bridge between
UI component and data source. Here data source is the source from where we get the data and
UI components are list or grid items in which we want to display that data.

Adapters In Android:
There are the some commonly used Adapter in Android used to fill the data in the UI
components.

1. BaseAdapter – It is parent adapter for all other adapters


2. ArrayAdapter – It is used whenever we have a list of single items which is backed by an
array
3. Custom ArrayAdapter – It is used whenever we need to display a custom list
4. SimpleAdapter – It is an easy adapter to map static data to views defined in
your XML file
5. Custom SimpleAdapter – It is used whenever we need to display a customized list and
needed to access the child items of the list or grid
UNIT-3

FILES AND DATABASES


Saving Simple Application Data - creating and saving preferences - preferences activity -saving
activity state - loading files - file management tools-sending emails through application -
Introducing Android databases -SQLite - Web Database- Firebase, MySQL-PHP

Saving Simple Application Data


There are two lightweight techniques for saving simple application data for Android applications —
Shared Preferences and a pair of event handlers used for saving Activity instance details. Both
mechanisms use a name/value pair (NVP) mechanism to store simple primitive values.
Using SharedPreferences, you can create named maps of key/value pairs within your application that can
be shared between application components running in the same Context.
Shared Preferences support the primitive types Boolean, string, fl oat, long, and integer, making them an
ideal way to quickly store default values, class instance variables, the current UI state, and user
preferences. They are most commonly used to persist data across user sessions and to share settings
between application components.
Alternatively, Activities offer the onSaveInstanceState handler. It’s designed specifi cally to persist the UI
state when the Activity becomes eligible for termination by a resource-hungry run time.
The handler works like the Shared Preference mechanism. It offers a Bundle parameter that represents a
key/value map of primitive types that can be used to save the Activity’s instance values. This Bundle is
then made available as a parameter passed in to the onCreate and onRestoreInstanceState method
handlers.
This UI state Bundle is used to record the values needed for an Activity to provide an identical UI
following unexpected restarts.

Creating and Saving Preferences


To create or modify a Shared Preference, call getSharedPreferences on the application Context, passing in
the name of the Shared Preferences to change. Shared Preferences are shared across an application’s
components but aren’t available to other applications.
To modify a Shared Preference, use the SharedPreferences.Editor class. Get the Editor object by calling
edit on the Shared Preferences object you want to change. To save edits, call commit on the Editor, as
shown in the code snippet below.

public static final String MYPREFS = “mySharedPreferences”;


protected void savePreferences(){
// Create or retrieve the shared preference object.
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences = getSharedPreferences(MYPREFS, mode);
// Retrieve an editor to modify the shared preferences.
SharedPreferences.Editor editor = mySharedPreferences.edit();
// Store new primitive types in the shared preferences object.
editor.putBoolean(“isTrue”, true);
editor.putFloat(“lastFloat”, 1f);
editor.putInt(“wholeNumber”, 2);
editor.putLong(“aNumber”, 3l);
editor.putString(“textEntryValue”, “Not Empty”);
// Commit the changes.
editor.commit();
}

Retrieving Shared Preferences


Accessing saved Shared Preferences is also done with the getSharedPreferences method. Pass in the name
of the Shared Preference you want to access, and use the type-safe get<type> methods to extract
saved values.
Each getter takes a key and a default value (used when no value is available for that key), as shown in the
skeleton code below:
public void loadPreferences() {
// Get the stored preferences
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences = getSharedPreferences(MYPREFS,
mode);
// Retrieve the saved values.
boolean isTrue = mySharedPreferences.getBoolean(“isTrue”, false);
float lastFloat = mySharedPreferences.getFloat(“lastFloat”, 0f);
int wholeNumber = mySharedPreferences.getInt(“wholeNumber”, 1);
long aNumber = mySharedPreferences.getLong(“aNumber”, 0);
String stringPreference;
stringPreference = mySharedPreferences.getString(“textEntryValue”,
“”);
}

Saving the Activity State


If you want to save Activity information that doesn’t need to be shared with other components (e.g., class
instance variables), you can call Activity.getPreferences() without specifying a preferences name. Access
to the Shared Preferences map returned is restricted to the calling Activity; each Activity supports a single
unnamed SharedPreferences object.
The following skeleton code shows how to use the Activity’s private Shared Preferences:
protected void saveActivityPreferences(){
// Create or retrieve the activity preferences object.
SharedPreferences activityPreferences =
getPreferences(Activity.MODE_PRIVATE);
// Retrieve an editor to modify the shared preferences.
SharedPreferences.Editor editor = activityPreferences.edit();
// Retrieve the View
TextView myTextView = (TextView)findViewById(R.id.myTextView);
// Store new primitive types in the shared preferences object.
editor.putString(“currentTextValue”,
myTextView.getText().toString());
// Commit changes.
editor.commit();
}

Saving and Restoring Instance State


To save Activity instance variables, Android offers a specialized alternative to Shared Preferences. By
overriding an Activity’s onSaveInstanceState event handler, you can use its Bundle parameter to save
instance values. Store values using the same get and put methods as shown for Shared Preferences, before
passing the modifi ed Bundle into the superclass’s handler, as shown in the following code snippet:
private static final String TEXTVIEW_STATE_KEY = “TEXTVIEW_STATE_KEY”;
@Override
public void onSaveInstanceState(Bundle outState) {
// Retrieve the View
TextView myTextView = (TextView)findViewById(R.id.myTextView);
// Save its state
outState.putString(TEXTVIEW_STATE_KEY,
myTextView.getText().toString());
super.onSaveInstanceState(outState);
}

This handler will be triggered whenever an Activity completes its Active life cycle, but only when it’s not
being explicitly fi nished. As a result, it’s used to ensure a consistent Activity state between active life
cycles of a single user session.
The saved Bundle is passed in to the onRestoreInstanceState and onCreate methods if the application is
forced to restart during a session. The following snippet shows how to extract values from the Bundle and
use them to update the Activity instance state:
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
TextView myTextView = (TextView)findViewById(R.id.myTextView);
String text = “”;
if (icicle != null && icicle.containsKey(TEXTVIEW_STATE_KEY))
text = icicle.getString(TEXTVIEW_STATE_KEY);
myTextView.setText(text);
}

It’s important to remember that onSaveInstanceState is called only when an Activity becomes inactive,
but not when it is being closed by a call to fi nish or by the user pressing the Back button.

Loading File
Android provides many kinds of storage for applications to store their data. These storage places
are
 shared preferences
 internal and external storage
 SQLite storage
 storage via network connection(on Cloud)

Android Internal Storage

Android Internal storage is the storage of the private data on the device memory. By default,
saving and loading files to the internal storage are private to the application and other
applications will not have access to these files. When the user uninstalls the applications the
internal stored files associated with the application are also removed. However, note that some
users root their Android phones, gaining superuser access. These users will be able to read and
write whatever files they wish.

Reading and Writing Text File in Android Internal Storage

Android offers openFileInput and openFileOutput from the Java I/O classes to modify reading
and writing streams from and to local files.
 openFileOutput(): This method is used to create and save a file. Its syntax is given below:

 FileOutputStream fOut = openFileOutput("file name",Context.MODE_PRIVATE);

The method openFileOutput() returns an instance of FileOutputStream. After that we can call
write method to write data on the file. Its syntax is given below:

String str = "test data";

fOut.write(str.getBytes());

fOut.close();
 openFileInput(): This method is used to open a file and read it. It returns an instance of
FileInputStream. Its syntax is given below:

 FileInputStream fin = openFileInput(file);

After that, we call read method to read one character at a time from the file and then print it. Its
syntax is given below:

int c;

String temp="";
while( (c = fin.read()) != -1){
temp = temp + Character.toString((char)c);
}

fin.close();
In the above code, string temp contains all the data of the file.
 Note that these methods do not accept file paths (e.g. path/to/file.txt), they just take simple file
names.
Android Internal Storage Project Structure

Android Internal Storage Example Code

The xml layout contains an EditText to write data to the file and a Write Button and Read
Button. Note that the onClick methods are defined in the xml file only as shown
below: activity_main.xml
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:padding="5dp"
android:text="Android Read and Write Text from/to a File"
android:textStyle="bold"
android:textSize="28sp" />

<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/textView1"
android:layout_marginTop="22dp"
android:minLines="5"
android:layout_margin="5dp">

<requestFocus />
</EditText>

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Write Text into File"
android:onClick="WriteBtn"
android:layout_alignTop="@+id/button2"
android:layout_alignRight="@+id/editText1"
android:layout_alignEnd="@+id/editText1" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Read Text From file"
android:onClick="ReadBtn"
android:layout_centerVertical="true"
android:layout_alignLeft="@+id/editText1"
android:layout_alignStart="@+id/editText1" />

</RelativeLayout>
The MainActivity contains the implementation of the reading and writing to files as it was
explained above.
package com.journaldev.internalstorage;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class MainActivity extends Activity {

EditText textmsg;
static final int READ_BLOCK_SIZE = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

textmsg=(EditText)findViewById(R.id.editText1);
}

// write text to file


public void WriteBtn(View v) {
// add-write text into file
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE);
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(textmsg.getText().toString());
outputWriter.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();

} catch (Exception e) {
e.printStackTrace();
}
}

// Read text from file


public void ReadBtn(View v) {
//reading text from file
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);

char[] inputBuffer= new char[READ_BLOCK_SIZE];


String s="";
int charRead;

while ((charRead=InputRead.read(inputBuffer))>0) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
s +=readstring;
}
InputRead.close();
textmsg.setText(s);

} catch (Exception e) {
e.printStackTrace();
}
}
}
Here, a toast is displayed when data is successfully written into the internal storage and the data
is displayed in the EditText itself on reading the data from the file. The image shown below is
the output of the project. The image depicts text being written to the internal storage and on
clicking Read it displays back the text in the same EditText.

Where is the file located?

To actually view the file open the Android Device Monitor from Tools->Android->Android
Device Monitor. The file is present in the folder data->data->{package name}->files as shown in
the
images below: The file “mytextfile.txt” is found in the package name of the project
i.e. com.journaldev.internalstorage as shown below:
Android External Storage Example
Like internal storage, we are able to save or read data from the device external memory such as sdcard.
The FileInputStream and FileOutputStream classes are used to read and write data into the file.

Example of reading and writing data in the android external storage

activity_main.xml

Drag the 2 edittexts, 2 textviews and 2 buttons from the pallete, now the activity_main.xml file will like
this:

File: activity_main.xml
1. <?xml version="1.0" encoding="utf-8"?>
2. <RelativeLayout 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="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.externalstorage.MainActivity">
8.
9. <EditText
10. android:id="@+id/editText1"
11. android:layout_width="wrap_content"
12. android:layout_height="wrap_content"
13. android:layout_alignParentRight="true"
14. android:layout_alignParentTop="true"
15. android:layout_marginRight="20dp"
16. android:layout_marginTop="24dp"
17. android:ems="10" >
18.
19. <requestFocus />
20. </EditText>
21.
22. <EditText
23. android:id="@+id/editText2"
24. android:layout_width="wrap_content"
25. android:layout_height="wrap_content"
26. android:layout_alignRight="@+id/editText1"
27. android:layout_below="@+id/editText1"
28. android:layout_marginTop="24dp"
29. android:ems="10" />
30.
31. <TextView
32. android:id="@+id/textView1"
33. android:layout_width="wrap_content"
34. android:layout_height="wrap_content"
35. android:layout_alignBaseline="@+id/editText1"
36. android:layout_alignBottom="@+id/editText1"
37. android:layout_alignParentLeft="true"
38. android:text="File Name:" />
39.
40. <TextView
41. android:id="@+id/textView2"
42. android:layout_width="wrap_content"
43. android:layout_height="wrap_content"
44. android:layout_alignBaseline="@+id/editText2"
45. android:layout_alignBottom="@+id/editText2"
46. android:layout_alignParentLeft="true"
47. android:text="Data:" />
48.
49. <Button
50. android:id="@+id/button1"
51. android:layout_width="wrap_content"
52. android:layout_height="wrap_content"
53. android:layout_alignLeft="@+id/editText2"
54. android:layout_below="@+id/editText2"
55. android:layout_marginLeft="70dp"
56. android:layout_marginTop="16dp"
57. android:text="save" />
58.
59. <Button
60. android:id="@+id/button2"
61. android:layout_width="wrap_content"
62. android:layout_height="wrap_content"
63. android:layout_alignBaseline="@+id/button1"
64. android:layout_alignBottom="@+id/button1"
65. android:layout_toRightOf="@+id/button1"
66. android:text="read" />
67. </RelativeLayout>

Provide permission for the external storage

You need to provide the WRITE_EXTERNAL_STORAGE permission.

1. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
File: Activity_Manifest.xml

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


2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3. package="example.javatpoint.com.externalstorage">
4. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
5. <application
6. android:allowBackup="true"
7. android:icon="@mipmap/ic_launcher"
8. android:label="@string/app_name"
9. android:roundIcon="@mipmap/ic_launcher_round"
10. android:supportsRtl="true"
11. android:theme="@style/AppTheme">
12. <activity android:name=".MainActivity">
13. <intent-filter>
14. <action android:name="android.intent.action.MAIN" />
15.
16. <category android:name="android.intent.category.LAUNCHER" />
17. </intent-filter>
18. </activity>
19. </application>
20.
21. </manifest>

Activity class

Let's write the code to write and read data from the android external storage.

File: MainActivity.java

1. package example.javatpoint.com.externalstorage;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.widget.Button;
7. import android.widget.EditText;
8. import android.widget.Toast;
9.
10. import java.io.BufferedReader;
11. import java.io.File;
12. import java.io.FileInputStream;
13. import java.io.FileNotFoundException;
14. import java.io.FileOutputStream;
15. import java.io.IOException;
16. import java.io.InputStreamReader;
17. import java.io.OutputStreamWriter;
18.
19. public class MainActivity extends AppCompatActivity {
20. EditText editTextFileName,editTextData;
21. Button saveButton,readButton;
22. @Override
23. protected void onCreate(Bundle savedInstanceState) {
24. super.onCreate(savedInstanceState);
25. setContentView(R.layout.activity_main);
26.
27. editTextFileName=findViewById(R.id.editText1);
28. editTextData=findViewById(R.id.editText2);
29. saveButton=findViewById(R.id.button1);
30. readButton=findViewById(R.id.button2);
31.
32. //Performing action on save button
33. saveButton.setOnClickListener(new View.OnClickListener(){
34.
35. @Override
36. public void onClick(View arg0) {
37. String filename=editTextFileName.getText().toString();
38. String data=editTextData.getText().toString();
39.
40. FileOutputStream fos;
41. try {
42. File myFile = new File("/sdcard/"+filename);
43. myFile.createNewFile();
44. FileOutputStream fOut = new FileOutputStream(myFile);
45. OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
46. myOutWriter.append(data);
47. myOutWriter.close();
48. fOut.close();
49. Toast.makeText(getApplicationContext(),filename + "saved",Toast.LENGTH_LONG).show(
);
50. } catch (FileNotFoundException e) {e.printStackTrace();}
51. catch (IOException e) {e.printStackTrace();}
52. }
53. });
54.
55. //Performing action on Read Button
56. readButton.setOnClickListener(new View.OnClickListener(){
57. @Override
58. public void onClick(View arg0) {
59. String filename=editTextFileName.getText().toString();
60. StringBuffer stringBuffer = new StringBuffer();
61. String aDataRow = "";
62. String aBuffer = "";
63. try {
64. File myFile = new File("/sdcard/"+filename);
65. FileInputStream fIn = new FileInputStream(myFile);
66. BufferedReader myReader = new BufferedReader(
67. new InputStreamReader(fIn));
68. while ((aDataRow = myReader.readLine()) != null) {
69. aBuffer += aDataRow + "\n";
70. }
71. myReader.close();
72. } catch (IOException e) {
73. e.printStackTrace();
74. }
75. Toast.makeText(getApplicationContext(),aBuffer,Toast.LENGTH_LONG).show();
76. }
77. });
78. }
79. }

Android File Manager

Android allows every user to access their device's file system using a file manager. They can
access Android files and transfer them between a computer and a smartphone or tablet. This is
performed by simply plug in a USB cable in an Android device and fire up your desktop file
manager. Android's file manager app reacts as an important part of the software on a device. It
provides facility to browse files, manage storage space, downloads, move files around, and a lot
of other activities. However, several Android device manufacturers provide a pre-install Android
file manager app on their devices. The pre-install file manager contains fewer features as
compared to other third-party file managers.

Some of the best Android File Managers:

1. Files Go (free)
2. Mixplorer Silver ($4.79)
3. Astro Cloud & File Manager (free)
4. Solid Explorer ($1.99 after free trial)
5. DiskUsage (free)
6. File Commander (free, in-app purchase)

Files Go

Files Go file manager is a product of Google, which behaves less like a file manager app and
more as a device assistant. This file manager helps you to manage your device's storage space by
deleting rarely used applications, files, documents, large size media, and folders. It also
facilitates a cache clearing functionality and allows you to view files based on their categories.
The Files Go supports local encrypted file sharing and backup features that provide a facility to
send files to the cloud.

MiXplorer Silver

MiXplorer Silver has a strong file manager in this era now, but it is now recently placed in the
Google Play store in a premium version. This version bunches together MiXplorer with several
premium add-ons like Mix archive, tagger, and metadata. It supports multiple archive formats,
including RAR and ZIP. The MiXplorer Silver contains a built-in media player and image
viewer. It supports for both networked and cloud-based storage device.
Astro Cloud & File Manager

ASTRO file manager is another important and popular choice for Android file management. This
file manager contains both cloud and local storage management components in a single package.
It offers you to manage your internal and SD card storage space. Using Astro Cloud file
manager, you can move your files and media to and from cloud services like One Drive,
Dropbox, and Google Drive. Its left side drawer contains convenient shortcuts such as cloud
service and network storage, bookmarked locations, and shortcuts to media files. Other than file
management functionality, this app also contains an app manager, quick viewer to SD card usage
space, and a task killer.
Solid Explorer

This is an attractive file manager app which provides two-pane user interface over the Android
phones and tablets. It also supports for archive files like TAR, RAR, and ZIP, and indexed search
function. Other than an impressive feature, Solid Explorer supports a wide range of plugins that
add new features such as FTP server plugin, USB OTG support, and lots more. It has two
separate explorer panes, which are combined with drag-and-drop support, which offers copying
and moving files from one location to another.
DiskUsage

DiskUsage is not a really complete file manager app; however, it is still an attractive tool that
helps you to manage your file system. This helps you to instantly find the files and folders that
occupy more storage space in the device. It performs as a separate tool to view and delete
folders.
File Commander

File Commander is an excellent file manager that provides extra features and utilities in-app
purchases. Instead of opening a file and directory view, the app's home screen gives users a
series of classified "libraries" such as document, audio, and video. This file manager also
supports remote access, file sharing, and cloud storage. It contains additions tools in-app
purchases.
sending emails through application
Email is messages distributed by electronic means from one system user to one or more
recipients via a network.
Before starting Email Activity, You must know Email functionality with intent, Intent is carrying
data from one component to another component with-in the application or outside the
application.
To send an email from your application, you don’t have to implement an email client from the
beginning, but you can use an existing one like the default Email app provided from Android,
Gmail, Outlook, K-9 Mail etc. For this purpose, we need to write an Activity that launches an
email client, using an implicit Intent with the right action and data. In this example, we are going
to send an email from our app by using an Intent object that launches existing email clients.
Following section explains different parts of our Intent object required to send an email.

Intent Object - Action to send Email

You will use ACTION_SEND action to launch an email client installed on your Android device.
Following is simple syntax to create an intent with ACTION_SEND action.
Intent emailIntent = new Intent(Intent.ACTION_SEND);

Intent Object - Data/Type to send Email

To send an email you need to specify mailto: as URI using setData() method and data type will
be to text/plain using setType() method as follows −
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");

Intent Object - Extra to send Email


Android has built-in support to add TO, SUBJECT, CC, TEXT etc. fields which can be attached
to the intent before sending the intent to a target email client. You can use following extra fields
in your email −

Sr.No. Extra Data & Description

1
EXTRA_BCC
A String[] holding e-mail addresses that should be blind carbon copied.

2
EXTRA_CC
A String[] holding e-mail addresses that should be carbon copied.

3
EXTRA_EMAIL
A String[] holding e-mail addresses that should be delivered to.

4
EXTRA_HTML_TEXT
A constant String that is associated with the Intent, used with ACTION_SEND
to supply an alternative to EXTRA_TEXT as HTML formatted text.

5
EXTRA_SUBJECT
A constant string holding the desired subject line of a message.

6
EXTRA_TEXT
A constant CharSequence that is associated with the Intent, used with
ACTION_SEND to supply the literal data to be sent.

7
EXTRA_TITLE
A CharSequence dialog title to provide to the user when used with a
ACTION_CHOOSER.

Here is an example showing you how to assign extra data to your intent −
emailIntent.putExtra(Intent.EXTRA_EMAIL , new String[]{"Recipient"});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "subject");
emailIntent.putExtra(Intent.EXTRA_TEXT , "Message Body");
The out-put of above code is as below shown an image
Email Example

Example

Following example shows you in practical how to use Intent object to launch Email client to send
an Email to the given recipients.
To Email experiment with this example, you will need actual Mobile device equipped with latest
Android OS, otherwise you might get struggle with emulator which may not work properly.
Second you will need to have an Email client like GMail(By default every android version
having Gmail client App) or K9mail installed on your device.

Step Description

1 You will use Android studio to create an Android application and name it
as Tutorialspoint under a package com.example.tutorialspoint.

2 Modify src/MainActivity.java file and add required code to take care of sending
email.

3 Modify layout XML file res/layout/activity_main.xml add any GUI component if


required. I'm adding a simple button to launch Email Client.

4 Modify res/values/strings.xml to define required constant values

5 Modify AndroidManifest.xml as shown below

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

Following is the content of the modified main activity


file src/com.example.Tutorialspoint/MainActivity.java.
package com.example.tutorialspoint;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {


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

Button startBtn = (Button) findViewById(R.id.sendEmail);


startBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendEmail();
}
});
}

protected void sendEmail() {


Log.i("Send email", "");
String[] TO = {""};
String[] CC = {""};
Intent emailIntent = new Intent(Intent.ACTION_SEND);

emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");
emailIntent.putExtra(Intent.EXTRA_EMAIL, TO);
emailIntent.putExtra(Intent.EXTRA_CC, CC);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Your subject");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Email message goes here");

try {
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
finish();
Log.i("Finished sending email...", "");
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this, "There is no email client installed.",
Toast.LENGTH_SHORT).show();
}
}
}
Following will be the content of res/layout/activity_main.xml file −
Here abc indicates about tutorialspoint logo
<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:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sending Mail Example"
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_alignRight="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton" />

<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:id="@+id/sendEmail"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/compose_email"/>

</LinearLayout>
Following will be the content of res/values/strings.xml to define two new constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Tutorialspoint</string>
<string name="compose_email">Compose Email</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.Tutorialspoint" >

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name="com.example.tutorialspoint.MainActivity"
android:label="@string/app_name" >

<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

</activity>

</application>
</manifest>
Let's try to run your tutorialspoint 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 toolbar. Before starting your
application, Android studio installer 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 −
Now use Compose Email button to list down all the installed email clients. From the list, you
can choose one of email clients to send your email. I'm going to use Gmail client to send my
email which will have all the provided defaults fields available as shown below. Here From: will
be default email ID you have registered for your Android device.

You can modify either of the given default fields and finally use send email button to send your
email to the mentioned recipients.
Android databases –SQLite

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

Sr.No Method & Description

1
openDatabase(String path, SQLiteDatabase.CursorFactory factory, int
flags, DatabaseErrorHandler errorHandler)
This method only opens the existing database with the appropriate flag mode.
The common flags mode could be OPEN_READWRITE OPEN_READONLY

2
openDatabase(String path, SQLiteDatabase.CursorFactory factory, int
flags)
It is similar to the above method as it also opens the existing database but it
does not define any handler to handle the errors of databases

3
openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory
factory)
It not only opens but create the database if it not exists. This method is
equivalent to openDatabase method.

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

Database - Insertion
we can create table or insert data into table using execSQL method defined in SQLiteDatabase
class. Its syntax is given below
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS TutorialsPoint(Username
VARCHAR,Password VARCHAR);");
mydatabase.execSQL("INSERT INTO TutorialsPoint VALUES('admin','admin');");
This will insert some values into our table in our database. Another method that also does the
same job but take some additional parameter is given below

Sr.No Method & Description

1
execSQL(String sql, Object[] bindArgs)
This method not only insert data , but also used to update or modify already
existing data in database using bind arguments

Database - Fetching

We can retrieve anything from database using an object of the Cursor class. We will call a
method of this class called rawQuery and it will return a resultset with the cursor pointing to the
table. We can move the cursor forward and retrieve the data.
Cursor resultSet = mydatbase.rawQuery("Select * from TutorialsPoint",null);
resultSet.moveToFirst();
String username = resultSet.getString(0);
String password = resultSet.getString(1);
There are other functions available in the Cursor class that allows us to effectively retrieve the
data. That includes

Sr.No Method & Description

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

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

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

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

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

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

Database - Helper class

For managing all the operations related to the database , an helper class has been given and is
called SQLiteOpenHelper. It automatically manages the creation and update of the database. Its
syntax is given below
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(){
super(context,DATABASE_NAME,null,1);
}
public void onCreate(SQLiteDatabase db) {}
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {}
}

onCreate(SQLiteDatabase sqLiteDatabase) method is called only once throughout the


application lifecycle. It will be called whenever there is a first call to getReadableDatabase() or
getWritableDatabase() function available in super SQLiteOpenHelper class. So
SQLiteOpenHelper class call the onCreate() method after creating database and instantiate
SQLiteDatabase object. Database name is passed in constructor call.

onUpgrade(SQLiteDatabase db,int oldVersion, int newVersion) is only called whenever


there is a updation in existing version. So to update a version we have to increment the value of
version variable passed in the superclass constructor.
In onUpgrade method we can write queries to perform whatever action is required. In most
example you will see that existing table(s) are being dropped and again onCreate() method is
being called to create tables again. But it’s not mandatory to do so and it all depends upon your
requirements.
We have to change database version if we have added a new row in the database table. If we
have requirement that we don’t want to lose existing data in the table then we can write alter
table query in the onUpgrade(SQLiteDatabase db,int oldVersion, int newVersion) method.
For more details read: Insert, Read, Delete & Update Operation In SQLite

<?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:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.sqliteoperations.MainActivity"
android:background="@android:color/holo_blue_dark">

<TextView
android:text="@string/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="12dp"
android:id="@+id/textView"
android:textSize="18sp"
android:textStyle="bold|italic"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:gravity="center" />

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="@+id/editName"
android:textStyle="bold|italic"
android:layout_below="@+id/textView"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="Enter Name"
android:gravity="center_vertical|center" />

<TextView
android:text="@string/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="13dp"
android:id="@+id/textView2"
android:textStyle="bold|italic"
android:textSize="18sp"
android:layout_below="@+id/editName"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:gravity="center"
android:hint="Enter Password" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:layout_marginTop="11dp"
android:id="@+id/editPass"
android:hint="Enter Password"
android:gravity="center_vertical|center"
android:textSize="18sp"
android:layout_below="@+id/textView2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textAllCaps="false"
android:textStyle="normal|bold" />

<Button
android:text="@string/add_user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:textStyle="bold|italic"
android:textSize="18sp"
android:onClick="addUser"
android:layout_marginLeft="28dp"
android:layout_marginStart="28dp"
android:layout_below="@+id/editPass"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="23dp" />

</RelativeLayout>

Now open app -> java -> package -> MainActivity.java and add the below code.

package com.example.sqliteoperations;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {


EditText Name, Pass , updateold, updatenew, delete;
myDbAdapter helper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Name= (EditText) findViewById(R.id.editName);
Pass= (EditText) findViewById(R.id.editPass);

helper = new myDbAdapter(this);


}
public void addUser(View view)
{
String t1 = Name.getText().toString();
String t2 = Pass.getText().toString();
if(t1.isEmpty() || t2.isEmpty())
{
Message.message(getApplicationContext(),"Enter Both Name and Password");
}
else
{
long id = helper.insertData(t1,t2);
if(id<=0)
{
Message.message(getApplicationContext(),"Insertion Unsuccessful");
Name.setText("");
Pass.setText("");
} else
{
Message.message(getApplicationContext(),"Insertion Successful");
Name.setText("");
Pass.setText("");
}
}
}
}

Step 4: In this step create a java class myDbAdapter. java.

package com.example.sqliteoperations;

import android.content.Context;
import android.widget.Toast;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class myDbAdapter {
myDbHelper myhelper;
public myDbAdapter(Context context)
{
myhelper = new myDbHelper(context);
}

public long insertData(String name, String pass)


{
SQLiteDatabase dbb = myhelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(myDbHelper.NAME, name);
contentValues.put(myDbHelper.MyPASSWORD, pass);
long id = dbb.insert(myDbHelper.TABLE_NAME, null , contentValues);
return id;
}
static class myDbHelper extends SQLiteOpenHelper
{
private static final String DATABASE_NAME = "myDatabase"; // Database Name
private static final String TABLE_NAME = "myTable"; // Table Name
private static final int DATABASE_Version = 1;. // Database Version
private static final String UID="_id"; // Column I (Primary Key)
private static final String NAME = "Name"; //Column II
private static final String MyPASSWORD= "Password"; // Column III
private static final String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME+
" ("+UID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+"
VARCHAR(255) ,"+ MyPASSWORD+" VARCHAR(225));";
private static final String DROP_TABLE ="DROP TABLE IF EXISTS "+TABLE_NAME;
private Context context;

public myDbHelper(Context context) {


super(context, DATABASE_NAME, null, DATABASE_Version);
this.context=context;
}

public void onCreate(SQLiteDatabase db) {

try {
db.execSQL(CREATE_TABLE);
} catch (Exception e) {
Message.message(context,""+e);
}
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
Message.message(context,"OnUpgrade");
db.execSQL(DROP_TABLE);
onCreate(db);
}catch (Exception e) {
Message.message(context,""+e);
}
}
}
}

Step 5: In this step create another java class Message.class


In this just simply add toast for displaying message. This is optional, it is just added to again and
again defining toast in the example.

package com.example.sqliteoperations;

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

public class Message {


public static void message(Context context, String message) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
}
Firebase: Realtime Database

The Firebase Realtime Database is a cloud-hosted database in which data is stored as JSON. The
data is synchronized in real-time to every connected client. All of our clients share one Realtime
Database instances and automatically receive updates with the newest data, when we build cross-
platform applications with our iOS, and JavaScript SDKs.

The Firebase Realtime Database is a NoSQL database from which we can store and sync the data
between our users in real-time. It is a big JSON object which the developers can manage in real-
time. By using a single API, the Firebase database provides the application with the current value
of the data and updates to that data. Real-time syncing makes it easy for our users to access their
data from any device, be it web or mobile.
The Realtime database helps our users collaborate with one another. It ships with mobile and
web SDKs, which allow us to build our app without the need for servers. When our users go
offline, the Real-time Database SDKs use local cache on the device for serving and storing
changes. The local data is automatically synchronized, when the device comes online.

Features of Firebase
Firebase has several features that make this platform essential. These features include unlimited
reporting, cloud messaging, authentication and hosting, etc. Let's take a look at these features to
understand how these features make Firebase essential:

Incredibly Built-In Analytics

The analytics dashboard is one of the best features of Firebase, which is equipped with. It is free
and can report 500 event types, each with 25 attributes. The dashboard is top-notch for observing
user behavior and measuring various user characteristics. Ultimately it helps us to understand
how people use our app so that we can better optimize it in the future.

Key features
Unlimited Reporting
It allows for reporting of 500 distinct events.

Audience Segmentation
We can identify custom audiences in the Firebase console based on device data, custom events,
or user properties. After that, we can use these audiences that we specified with other Firebase
attributes when targeting new features or notifications.
Integration with Other Services
We can integrate Firebase with other services that can utilize our business apps such as Big
Query, Firebase Notifications, Firebase Remote Configuration, Firebase CrashReporting, and
Google Tag Manager.

App Development Made Easy


With Firebase, we can focus our time and attention on developing the best possible applications
for our business. The operation and internal functions are very solid. They have taken care of the
Firebase Interface. We can spend more time in developing high-quality apps that users want to
use.
Cloud Messaging
Firebase allows us to deliver and receive messages in a more reliable way across platforms.

Authentication
Firebase has little friction with acclaimed authentication.

Test Lab
Test in the lab instead on your users.

Hosting
Firebase delivers web content faster.

Remote Configuration
It allows us to customize our app on the go.

Dynamic Links
Dynamic Links are smart URLs which dynamically change behavior for providing the best
experience across different platforms. These links allow app users to take directly to the content
of their interest after installing the app - no matter whether they are completely new or lifetime
customers.

Crash Reporting
It keeps our app stable.

Real-time Database
It can store and sync app data in real-time.

Storage
We can easily store the file in the database.

Growth and User Engagement


One of the most important aspects of application development is being able to develop and
engage with users over time. Firebase has a lot of built-in features, which ensures that it is
exactly what we do. With the platform leading to commercial apps, it is really at the center of
what makes Firebase so great.
Here are some user interaction aspects which make development a piece of cake:
AdWords
Linking AdWords is very easy, and with it, we can segment and define our user base using
Firebase Analytics. Also, it is easy to improve our targeting in marketing advertising campaigns.
Some other benefits include conversion tracking, cross-network, attribution networks, and LTV
(Calculating Customer Lifetime Value).

App Indexing
With app indexing, we can work on aspects like re-engaging with our app, especially by surfing
the in-app content within Google search results. It will also help in ranking our application in
Google search results.

Invites
It is a perfect tool for referrals and sharing. Get the help of our users to develop our app easily
via email or SMS, allowing their existing users to share our app or in-app content. If we use this
feature in combination with promotions, then we can also work towards acquiring new customers
and retaining our existing customers.

Notifications
We can manage information campaigns very easily, including the ability to set and schedule
messages to engage users at the right time of day. These notifications are completely free. These
are unlimited for both iOS and Android. There is only one dashboard to worry about, and if we
integrate with Firebase Analytics, we can use various user segmentation features.

Increase Your Earnings


Of course, the thing about having an app or any other business strategy is that we can increase
our earnings. With the feature of AdMob, we can monetize our app, considering the best possible
experience for our users. Showing real-time ads to millions of Google advertisers, choosing a
format which suits our app, and working with over 40 top ads networks using AdMob Mediation,
we can make app development well worth it, while speaking silently.

Step 1:

In the first step, we will create a new Android Studio project with an empty activity and Kotlin
language and give it name FirebaseRealtimeDatabaseExample.
Step 2:

In the next step, we will connect our Android Application with the Firebase either from Firebase
Assistant or manually using console. After that, we will add all the required libraries and plugin
to our app.gradle file. And we will also add mavenLocal() as our repository and all projects.
Step 3:

In the next step, we will go to the Firebase console and look at the Real-time database. In
Developers-> Database, there will be two options, i.e., cloud Firestore and Real-time database.
Step 4:

In the next step, we will create a database by clicking on the Create database. After clicking on
Create database, a popup box is open where we actually create a database with specific rules. We
will talk about these rules later in this section. But for now, we will select start in test mode
where anybody can access our data, and later we change these rules. And last we select on
Enable.
Step 5:

After clicking on Enable, the real-time database will be enabled with a database by default. Here,
we have Data, Rules, Backups, and, Usage for data storing, security rules, backups, and usage,
respectively.
Before understanding the next steps, we will talk about the Firebase Database Rules.

The Real-time database provides a declarative rules language. It defines how our data should be
structured, how it should be indexed, and when our data can be read from and written to. By
default, read and write access to our database is restricted, so only authenticated users can read or
write data.

To get started without setting up Authentication, we can configure our rules for public access.
These rules make our database open to anyone, even people not using our app, read and write
access to our database.

1. {
2. "rules": {
3. ".read": true,
4. ".write": true
5. }
6. }
If we want to allow authenticated users for accessing read and write to our database, then we will
use the following rules:

1. {
2. "rules": {
3. ".read": "auth!=null",
4. ".write": "auth!=null"
5. }
6. }
This will make sure that user only who have been authenticated using firebase can read and write
to our database.

Step 6:

In the next step, we will go to the console and go to database rules and modify these rules to
authenticated users.

After performing the required changes in the rules, we will publish them.
Now, our database is set with specific rules, and we can use it now. In the next section, we will
learn how we perform read and write operations in a Real-time database.

Example:

package com.example.firebase_database;

import android.os.Bundle;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

public class MainActivity extends AppCompatActivity {


DatabaseReference ref;
TextView txt;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt=(TextView)findViewById(R.id.tv1);
ref= FirebaseDatabase.getInstance().getReference().child("student").child("name");
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String str;
str=dataSnapshot.getValue(String.class);
//Toast.makeText(getApplicationContext(),str,Toast.LENGTH_LONG).show();
txt.setText(str);
}

@Override
public void onCancelled(@NonNull DatabaseError databaseError) {

}
});
}
}

MySQL-PHP
mysql
MySQL is an open-source relational database management system (RDBMS). It is the most
popular database system used with PHP. MySQL is developed, distributed, and supported by
Oracle Corporation.
 The data in a MySQL database are stored in tables which consists of columns and rows.
 MySQL is a database system that runs on a server.
 MySQL is ideal for both small and large applications.
 MySQL is very fast, reliable, and easy to use database system.It uses standard SQL
 MySQL compiles on a number of platforms.

The data in a MySQL database are stored in tables. A table is a collection of related data, and it
consists of columns and rows.

Databases are useful for storing information categorically. A company may have a database with
the following tables:

 Employees
 Products
 Customers
 Orders

Open a Connection to MySQL


<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

Close the Connection

The connection will be closed automatically when the script ends. To close the connection
before, use the following:

MySQLi Object-Oriented:
$conn->close();

Create a MySQL Database Using MySQLi and PDO

The CREATE DATABASE statement is used to create a database in MySQL.

The following examples create a database named "myDB":


Example (MySQLi Object-oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>

Create a MySQL Table Using MySQLi


Example (MySQLi Object-oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to create table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP
)";

if ($conn->query($sql) === TRUE) {


echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . $conn->error;
}

$conn->close();
?>

Insert Data Into MySQL Using MySQLi and PDO

After a database and a table have been created, we can start adding data in them.

Here are some syntax rules to follow:

 The SQL query must be quoted in PHP


 String values inside the SQL query must be quoted
 Numeric values must not be quoted
 The word NULL must not be quoted

The INSERT INTO statement is used to add new records to a MySQL table:

INSERT INTO table_name (column1, column2, column3,...)


VALUES (value1, value2, value3,...)
Example (MySQLi Object-oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)


VALUES ('John', 'Doe', '[email protected]')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>
UNIT-IV

SMALL COMPUTING TECNOLOGY AND SENSORS 9


Audio, Video Using the Camera - Telephony And SMS - Bluetooth Networks -
Managing network connectivity - WI-FI - Sensors-Sensors and the Sensor
Manager - Interpreting sensor values-Using the compass, Accelerometer and
Orientation sensor.

Android MediaPlayer Class


In android, by using MediaPlayer class we can access audio or video files from application (raw)
resources, standalone files in file system or from a data stream arriving over a network
connection and play audio or video files with the multiple playback options such as play, pause,
forward, backward, etc.
Audio algorithm:-
Step 1: Open an empty activity and give a name(Musicplayer)then click finish.
Step 2: In project, right click the res folder(directory),select new directory &give a name raw.
Step 3: Download any mp3 (music) file and copy the file.
Step 4: In raw directory , right click and paste the mp3 file, then click refactor.
Step 5: In activity-main.xml, drag and drop 2 buttons in design view ,and change the text of 2
buttons ,play and pause respectively.
Step 6: Add the code in mainactivity.java ,for play and pause button.
Step7: Run the app ,check the output in emulator, the audio will play ,when click the play button.
Step 8: Stop or pause the audio when click the pause button.
Step 9: Save and exit the application

Activity_Main.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"
tools:context=".MainActivity">

<Button
android:id="@+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="131dp"
android:layout_marginTop="158dp"
android:layout_marginEnd="192dp"
android:layout_marginBottom="69dp"

android:text="@string/play"
app:layout_constraintBottom_toTopOf="@+id/stop"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="133dp"
android:layout_marginTop="69dp"
android:layout_marginEnd="190dp"
android:layout_marginBottom="408dp"

android:text="@string/pause"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/start" />
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java
package com.example.exno_2_amutha;

import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


private MediaPlayer mediaPlayer;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaPlayer=MediaPlayer.create(this,R.raw.sound);
Button playbutton=(Button) findViewById(R.id.start);
playbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new
MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
Toast.makeText(MainActivity.this,"The Song is
Over",Toast.LENGTH_SHORT).show();
}
});
}
});
Button pausebutton=(Button) findViewById(R.id.stop);
pausebutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mediaPlayer.pause();
}
});

Video
Step 1: Create a new project ,open an empty activity named by videoplayer , then click
finish.
Step 2: Remove text view in the code view of activity-main.xml
Step 3: Drag and drop the relative layout.
Step 4: In designview ,drag and drop the button and give a text as play , and give android:onclick
=”videoplay”, and change the id.
Step 5:Click widgets in palette , drag and drop the videoview and change the id.
Step 6:In project right click yes ,select new. Select resource->click new resource folder and click
change the folder location. src/ main/res/raw
Step 7: Download any mp4, or webm file, copy that file.
Step 8: Right click raw folder and paste it then click refactor.
Step 9: Write the code in mainactivity.java
Step 10: Run the app
Acivity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context=".MainActivity">

<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:onClick="videoplay"
android:layout_height="wrap_content"
android:text="play" />

<VideoView
android:id="@+id/videoView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

</LinearLayout>

Main_acivity.java
package com.example.exno_3_video;
import androidx.appcompat.app.AppCompatActivity;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.VideoView;
public class MainActivity extends AppCompatActivity {
Button clk;
VideoView videov;
MediaController mediaC;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
clk=(Button)findViewById(R.id.button);
videov=(VideoView)findViewById(R.id.videoView);
mediaC=new MediaController(this);
}
public void videoplay(View view)
{

String videopath="android.resource://com.example.exno_3_video/"+R.raw.cloud;
Uri uri=Uri.parse(videopath);
videov.setVideoURI(uri);
videov.setMediaController(mediaC);
mediaC.setAnchorView(videov);
videov.start();

}
}

Output:
Camera
Camera is a hardware device that allows capturing pictures and videos in your applications.
Follow this tutorial to easily understand how to use a camera in your own Android App.
The Android framework provides the facility of working with Camera in two ways:
1.By using existing camera application(camera intent)
2.By using Camera Api
#1 Using Camera By Using Camera Application
We can capture pictures without using the instance of Camera class. Here you will use
an intent action type of MediaStore.ACTION_IMAGE_CAPTURE to launch an existing Camera
application on your phone. In Android MediaStore is a type of DataBase which stores pictures
and videos in android.
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

#2 Using Camera By using Camera Api


This class is used for controlling device cameras. It can be used to take pictures when you are
building a camera application.
Camera API works in following ways:
1.Camera Manager: This is used to get all the cameras available in the device like front camera
back camera each having the camera id.
2.CameraDevice: You can get it from Camera Manager class by its id.
3.CaptureRequest: You can create a capture request from camera device to capture images.
4.CameraCaptureSession: To get capture request’s from Camera Device create a
CameraCaptureSession.
5.CameraCaptureSession.CaptureCallback: This is going to provide the Capture session
results.
Camera Permission Declarations In Manifest
First, you should declare the Camera requirement in your Manifest file if Camera is compulsory
for your application and you don’t want your application to be installed on a device that does not
support Camera.
Before you start development on your application you have to make sure that your Manifest has
appropriate declarations in it that will allow you to use Camera feature in your Application.

<uses-permission android:name="android.permission.CAMERA"/>

Camera Example in Android Studio By Using Camera Intent and storing the camera
Image in Local DataBase
In this Camera in Android example, I will show you how to capture the image from device
camera using Intent and store that camera image in the local database and display a toast when
an image is stored successfully or when some error occurred while storing an image.

activity_main.xml

Drag one imageview and one button from the pallete, now the xml file will look like this:

File: activity_main.xml
1. <RelativeLayout xmlns:androclass="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. tools:context=".MainActivity" >
6.
7. <Button
8. android:id="@+id/button1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentBottom="true"
12. android:layout_centerHorizontal="true"
13. android:text="Take a Photo" >
14. </Button>
15.
16. <ImageView
17. android:id="@+id/imageView1"
18. android:layout_width="fill_parent"
19. android:layout_height="fill_parent"
20. android:layout_above="@+id/button1"
21. android:layout_alignParentTop="true"
22. android:src="@drawable/ic_launcher" >
23. </ImageView>
24. </RelativeLayout>

Activity class

Let's write the code to capture image using camera and displaying it on the image view.
File: MainActivity.java
1. package com.example.simplecamera;
2.
3. import android.app.Activity;
4. import android.content.Intent;
5. import android.graphics.Bitmap;
6. import android.os.Bundle;
7. import android.view.Menu;
8. import android.view.View;
9. import android.widget.Button;
10. import android.widget.ImageView;
11.
12. public class MainActivity extends Activity {
13. private static final int CAMERA_REQUEST = 1888;
14. ImageView imageView;
15. public void onCreate(Bundle savedInstanceState) {
16.
17. super.onCreate(savedInstanceState);
18. setContentView(R.layout.activity_main);
19.
20. imageView = (ImageView) this.findViewById(R.id.imageView1);
21. Button photoButton = (Button) this.findViewById(R.id.button1);
22.
23. photoButton.setOnClickListener(new View.OnClickListener() {
24.
25. @Override
26. public void onClick(View v) {
27. Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAP
TURE);
28. startActivityForResult(cameraIntent, CAMERA_REQUEST);
29. }
30. });
31. }
32.
33. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
34. if (requestCode == CAMERA_REQUEST) {
35. Bitmap photo = (Bitmap) data.getExtras().get("data");
36. imageView.setImageBitmap(photo);
37. }
38. }
39.
40. @Override
41. public boolean onCreateOptionsMenu(Menu menu) {
42. // Inflate the menu; this adds items to the action bar if it is present.
43. getMenuInflater().inflate(R.menu.activity_main, menu);
44. return true;
45. }
46.
47. }
Telephony and SMS
SMSManager class manages operations like sending a text message, data message, and
multimedia messages (MMS). For sending a text message method sendTextMessage() is used
likewise for multimedia message sendMultimediaMessage() and for data
message sendDataMessage() method is used. The details of each function are:

sendTextMessage(String destinationAddress,
String scAddress, String text, PendingIntent sentIntent,
sendTextMessage() PendingIntent deliveryIntent, long messageId)

sendDataMessage(String destinationAddress,
String scAddress, short destinationPort, byte[] data,
sendDataMessage() PendingIntent sentIntent, PendingIntent deliveryIntent)

sendMultimediaMessage(Context context,
Uri contentUri, String locationUrl,
sendMultimediaMessage() Bundle configOverrides, PendingIntent sentIntent

Below is an example of a basic application that sends a text message.

Step 1: Create a new Android Application.


Step 2: Go to AndroidManifest.xml.
app->Manifest->AndroidManifest.xml
Step 3: In AndroidManifest.xml add the permission to send SMS. It will permit an android
application to send SMS.
<uses-permission android:name=” android.permission.SEND_SMS ” />
Step 4: Open activity_main.xml from the following address and add the below code. Here, in a
Linear Layout, two edittext for taking phone number and a text message and a button for
sending the message is added.
app->res->layout->activitymain.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:layout_marginTop="140dp"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Enter number"
android:inputType="textPersonName" />
<EditText
android:id="@+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Enter message"
android:inputType="textPersonName" />
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginLeft="60dp"
android:layout_marginRight="60dp"
android:text="SEND" />
</LinearLayout>
Since the Send button is for sending the message so onClickListener is added with the button.
Now create two string variables and store the value of editText phone number and message
into them using method getText() (before assigning convert them to a string
using toString() method). Now in try block create an instance of SMSManager class and get
the SMSManager associated with the default subscription id. Now call
method sendTextMessage() to send message.
SmsManager smsManager=SmsManager.getDefault();
smsManager.sendTextMessage(number,null,msg,null,null);
package com.example.gfg;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


EditText phonenumber,message;
Button send;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
send=findViewById(R.id.button);
phonenumber=findViewById(R.id.editText);
message=findViewById(R.id.editText2);
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String number=phonenumber.getText().toString();
String msg=message.getText().toString();
try {
SmsManager smsManager=SmsManager.getDefault();
smsManager.sendTextMessage(number,null,msg,null,null);
Toast.makeText(getApplicationContext(),"Message
Sent",Toast.LENGTH_LONG).show();
}catch (Exception e)
{
Toast.makeText(getApplicationContext(),"Some fiedls is
Empty",Toast.LENGTH_LONG).show();
}
}
});
}
}
Note: For running application in Android device enable the SMS permission for the app.
Goto permissions->SMS->YourApp and enable permission.
Output:
Sending the message
sing Built-in Intent to send SMS

You can use Android Intent to send SMS by calling built-in SMS functionality of the Android.
Following section explains different parts of our Intent object required to send an SMS.

Intent Object - Action to send SMS

You will use ACTION_VIEW action to launch an SMS client installed on your Android device.
Following is simple syntax to create an intent with ACTION_VIEW action.

Intent smsIntent = new Intent(Intent.ACTION_VIEW);


Intent Object - Data/Type to send SMS

To send an SMS you need to specify smsto: as URI using setData() method and data type will be
to vnd.android-dir/mms-sms using setType() method as follows −

smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.android-dir/mms-sms");

Intent Object - Extra to send SMS

Android has built-in support to add phone number and text message to send an SMS as follows −

smsIntent.putExtra("address" , new String("0123456789;3393993300"));


smsIntent.putExtra("sms_body" , "Test SMS to Angilla");
Here address and sms_body are case sensitive and should be specified in small characters only. You can
specify more than one number in single string but separated by semi-colon (;).

Example

Following example shows you in practical how to use Intent object to launch SMS client to send
an SMS to the given recipients.

To experiment with this example, you will need actual Mobile device equipped with latest Android OS,
otherwise you will have to struggle with emulator which may not work.
Step Description
You will use Android studio IDE to create an Android application and name it as tutorialspoint
1
under a package com.example.tutorialspoint.
2 Modify src/MainActivity.java file and add required code to take care of sending SMS.
Modify layout XML file res/layout/activity_main.xml add any GUI component if required. I'm
3
adding a simple button to launch SMS Client.
4 No need to define default constants.Android studio takes care of default constants.
5 Modify AndroidManifest.xml as shown below
Run the application to launch Android emulator and verify the result of the changes done in the
6
application.

Following is the content of the modified main activity file


src/com.example.tutorialspoint/MainActivity.java.

package com.example.tutorialspoint;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {


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

Button startBtn = (Button) findViewById(R.id.button);


startBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendSMS();
}
});
}

protected void sendSMS() {


Log.i("Send SMS", "");
Intent smsIntent = new Intent(Intent.ACTION_VIEW);

smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("address" , new String ("01234"));
smsIntent.putExtra("sms_body" , "Test ");

try {
startActivity(smsIntent);
finish();
Log.i("Finished sending SMS...", "");
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this,
"SMS faild, please try again later.", Toast.LENGTH_SHORT).show();
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

Following will be the content of res/layout/activity_main.xml file −

Here abc indicates about tutorialspoint logo


<?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:text="Drag and Drop Example"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />

<TextView
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="30dp"
android:textColor="#ff14be3c" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_marginTop="48dp"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Compose SMS"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2"
android:layout_marginTop="54dp"
android:layout_alignLeft="@+id/imageView"
android:layout_alignStart="@+id/imageView" />

</RelativeLayout>

Following will be the content of res/values/strings.xml to define two new constants −

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


<resources>
<string name="app_name">tutorialspoint</string>
</resources>

Following is the default content of AndroidManifest.xml −

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


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

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name="com.example.tutorialspoint.MainActivity"
android:label="@string/app_name" >

<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

</activity>

</application>
</manifest>

Let's try to run your tutorialspoint 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 toolbar. 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 −
Now use Compose SMS button to launch Android built-in SMS clients which is shown below −
You can modify either of the given default fields and finally use send SMS button to send your
SMS to the mentioned recipient.
Bluetooth Networks
Bluetooth is a communication network protocol, which allows devices to connect wirelessly to
exchange the data with other Bluetooth devices.

Generally, in android applications by using Bluetooth API’s we can implement Bluetooth


functionalities, such as searching for the available Bluetooth devices, connecting with the
devices and managing the data transfer between devices within the range.

By using android Bluetooth API’s in android applications, we can perform the following
functionalities.

 Scan for the available Bluetooth devices within the range


 Use local Bluetooth adapter for paired Bluetooth devices
 Connect to other devices through service discovery
 Transfer data to and from other devices
 Manage multiple connections

To transfer the data between two Bluetooth devices first, they must establish a communication
channel using the pairing process. The devices which we are going to pair must be discoverable
and should accept the incoming connection requests. Generally, the devices will find
discoverable devices using a service discovery process. Once the device accepts the pairing
request, the two devices will exchange security keys to complete the bonding process and the
devices will cache these security keys for later use.

Once the pairing and bonding process completes, the devices are ready to exchange the required
information. When the session is complete, the device that initiated the pairing request will
release the channel that linked to the discoverable device. The two devices remain bonded, so
they can reconnect automatically during a future session as long as they're in the range of each
other.

Android Set Bluetooth Permissions


To use Bluetooth features in our android applications, we must need to add multiple permissions,
such
as BLUETOOTH and ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION i
n our manifest file.

Permission Description

BLUETOOTH We need this permission to perform any Bluetooth communication, such as


requesting a connection, accepting a connection, and transferring data.
Permission Description

LOCATION We need this permission because the Bluetooth scans can be used to gather the
information about the location of user.
In case, if we want to discover the available Bluetooth devices or manipulate Bluetooth settings
from our app, we need to define BLUETOOTH_ADMIN permission.

Following is the example of defining the Bluetooth permissions in android manifest file.

<manifest ... >


<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
...
</manifest>

Android BluetoothAdapter Class


In android, we can perform Bluetooth related activities by using BluetoothAdapter class in our
applications.

By using BluetoothAdapter object, we can interact with device’s Bluetooth adapter to perform
Bluetooth related operations. In case, if device does not contain any Bluetooth adapter, then it
will return null.

Following is the code snippet to initialize BluetoothAdapter class and to know whether the
Bluetooth is supported on the device or not.

BluetoothAdapter bAdapter = BluetoothAdapter.getDefaultAdapter();


if(bAdapter==null)
{
// Device won't support Bluetooth
}
If you observe above code snippet, we used the getDefaultAdapter() method
of BluetoothAdapter class, which will return whether the device contains Bluetooth adapter or
not.

In case if getDefaultAdapter() method returns NULL, then the device does not support
Bluetooth and we can disable all Bluetooth features.
Android Enable or Disable Bluetooth
If Bluetooth is supported but disabled, then the isEnabled() method will return false and we can
request the user to enable Bluetooth without leaving our application by
using startActivityForResult() method with ACTION_REQUEST_ENABLE intent action
parameter.

Following is the code snippet to enable a Bluetooth by


using BluetoothAdapter parameter ACTION_REQUEST_ENABLE.

if(!bAdapter.isEnabled())
{
Intent eintent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(eintent, intVal);
}
If you observe above code snippet, we used startActivityForResult() method
with ACTION_REQUEST_ENABLE intent action parameter to enable a Bluetooth.

The second parameter intVal in startActivityForResult() method is a locally defined integer


that must be greater than 0 and the system will return this parameter back to us
during onActivityResult() implementation as a requestCode parameter.

To know more about to TURN ON / OFF Bluetooth in android applications, check this Android
Bluetooth Turn ON / OFF with Examples.

Android Bluetooth Turn ON / OFF Example

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<Button
android:id="@+id/btnOn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Turn
On" android:layout_marginLeft="100dp" android:layout_marginTop="200dp" />
<Button
android:id="@+id/btnOFF"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/btnOn"
android:layout_toRightOf="@+id/btnOn"
android:text="Turn OFF" />
</RelativeLayout>
Now open your main activity
file MainActivity.java from \java\com.tutlane.bluetoothexample path and write the code like
as shown below

MainActivity.java
package com.tutlane.bluetoothexample;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btntOn = (Button)findViewById(R.id.btnOn);
Button btntOff = (Button)findViewById(R.id.btnOFF);
final BluetoothAdapter bAdapter = BluetoothAdapter.getDefaultAdapter();
btntOn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(bAdapter == null)
{
Toast.makeText(getApplicationContext(),"Bluetooth Not
Supported",Toast.LENGTH_SHORT).show();
}
else{
if(!bAdapter.isEnabled()){

startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE),1);
Toast.makeText(getApplicationContext(),"Bluetooth Turned
ON",Toast.LENGTH_SHORT).show();
}
}
}
});
btntOff.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bAdapter.disable();
Toast.makeText(getApplicationContext(),"Bluetooth Turned OFF",
Toast.LENGTH_SHORT).show();
}
});
}
}
If you observe above code, we used startActivityForResult() method with BluetoothAdapter
action parameter ACTION_REQUEST_ENABLE intent to enable or disable a Bluetooth in our
application.

As discussed, we need to set Bluetooth permissions in android manifest file


(AndroidManifest.xml) to access Bluetooth features in android applications. Now open android
manifest file (AndroidManifest.xml) and write the code like as shown below

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutlane.bluetoothexample">
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<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>
</application>
</manifest>

Output of Android Bluetooth Turn ON / OFF Example


When we run the above program in the android studio we will get the result as shown below.
Sensors:
Most of the android devices have built-in sensors that measure motion, orientation, and
various environmental condition. The android platform supports three broad categories
of sensors.

 Motion Sensors
 Environmental sensors
 Position sensors

 Motion Sensors
These sensors track movement; they include accelerometers, gyroscopes and gravity
sensors. They provide data on forces like acceleration and rotation that act on the sensor’s
three-dimensional axes.

 Environmental Sensors
Barometers and thermometers are types of sensors that access environmental metrics.
These sensors monitor environmental variables like air pressure and temperature.
 Position Sensors
Magnetometer and orientation sensors help determine the physical position of a device.

 Each of these categories represents many specific sensors that are available on a device.
You will go through them next.
Android Sensor API
We can collect raw sensor data by using Android Sensor API. Android sensor
API provides many classes and interfaces. Some of the important classes and
interfaces are:
1. SensorManager Class: Sensor manager is used to accessing various
sensors present in the device.
2. Sensor Class: The sensor class is used to get information about the
sensor such as sensor name, sensor type, sensor resolution, sensor type,
etc.
3. SensorEvent class: This class is used to find information about the
sensor.
4. SensorEventListener interface: This is used to perform some action
when sensor accuracy changes.

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

public void onSensorChanged(SensorEvent event) {


}
Example: Light Sensor App
This app will show us light intensity in our room with the help of a light sensor
present in our phone.
Step by Step Implementation
Step 1: Create a New Project in your android studio
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: Working with the XML file
Navigate to the app > res > layout > activity_main.xml and add the below
code to that file.
XML

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

<RelativeLayout

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

<!-- Textview to show light sensor reading -->

<TextView

android:id="@+id/tv_text"

android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:text="Light Sensor"

android:textSize="20sp"

android:textColor="@color/black"

android:layout_centerInParent="true" />

</RelativeLayout>

Step 3: Working With the MainActivity.kt

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.
package com.mrtechy.gfg_sensor

import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatDelegate

class MainActivity : AppCompatActivity(), SensorEventListener {

// Initialised sensorManager & two variables


// for storing brightness value
private lateinit var sensorManager: SensorManager
private var brightness: Sensor? = null
private lateinit var text: TextView

override fun onCreate(savedInstanceState: Bundle?) {


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

// Set default nightmode


AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_N
O)
// searched our textview id and stored it
text = findViewById(R.id.tv_text)

// setupSensor Called
setUpSensor()
}

// Declared setupSensor function


private fun setUpSensor() {
sensorManager = getSystemService(SENSOR_SERVICE) as SensorManager
brightness = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT)
}

// These are two methods from sensorEventListner Interface


override fun onSensorChanged(event: SensorEvent?) {
if (event?.sensor?.type == Sensor.TYPE_LIGHT) {
val light1 = event.values[0]

text.text = "Sensor: $light1\n${brightness(light1)}"


}
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
return
}

// Created a function to show messages according to the brightness


private fun brightness(brightness: Float): String {

return when (brightness.toInt()) {


0 -> "Pitch black"
in 1..10 -> "Dark"
in 11..50 -> "Grey"
in 51..5000 -> "Normal"
in 5001..25000 -> "Incredibly bright"
else -> "This light will blind you"
}
}

// This is onResume function of our app


override fun onResume() {
super.onResume()
sensorManager.registerListener(this, brightness,
SensorManager.SENSOR_DELAY_NORMAL)
}

// This is onPause function of our app


override fun onPause() {
super.onPause()
sensorManager.unregisterListener(this)
}
}
Output:
Note: App those usage sensors will only work on physical Android devices, not
on any emulators.
9
UNIT-V

ADVANCED TECHNOLOGY
Paranoid Android - Using Wake Locks - AIDL to Support IPC for
Services -General API’s- Payment-gateway, Android jetpack-
Technology II-IOS-Introduction to Objective C-IOS features.
Paranoid Android

Paranoid Android is a custom ROM that targets to extend or enhance the


system and working of existing Android.

Features of Paranoid Android


The two most popular and notable features of this operating system
are Halo and Pie. The Halo feature allows users to see notifications without
leaving their current screen. On the other hand, Pie replaces the onscreen
navigation button that stays away from the screen and allows users to swipe
sideways to view the button. It also provides the features of accidental touch
rejection and pocket lock that avoids pressing any buttons in a user's pocket. It
also allows users to take a screenshot by simply swiping three fingers.
Other Features
o Built-in screen recorder.
o Fingerprint on display.
o Off-screen gestures.
o Pocket mode detects that your device is in your pocket and prevents it
from working.
o Fast charging indicator.
o Navigation bar customization.
o Improve lock-screen security.
o VPN, WiFi restrictions, and per-app cellular data.
o Swipe down three fingers for a screenshot.
o Long-press the volume to skip tracks.
WakeLockActivity.java
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;

public class WakeLockActivity extends Activity {


/** Called when the activity is first created. */
protected static WakeLock wakeLock = null;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "DoNotSleep");
wakeLock.acquire();
}

@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
wakeLock.release();
}
}
https://www.protechtraining.com/blog/post/implementing-remote-interface-using-aidl-66
Step2: implement the Step3: Expose the
stub for remote service remote service to
(IAdditionservice.stub) the local client

Step1: implement
AIDL interface
(Iadditionservice)
Defining the AIDL

The AIDL syntax is very similar to regular Java interface.

You simply define the method signature.

The datatypes supported by AIDL are somewhat different than regular

Java interfaces.

For one, all Java primitive datatypes are supported.

So are String, List, Map, and CharSequence classes.

Also, all other AIDL datatypes that you defined are supported.

In addition to that, all Parcelable classes are supported


/src/com.marakana/IAdditionService.aidl

Code:

package com.marakana;

// Declare the interface.

interface IAdditionService {

// You can pass values in, out, or inout.


// Primitive datatypes (such as int, boolean, etc.) can only be passed in.

int add(in int value1, in int value2);


}
Implementing the Remote Service

Once you create your AIDL file and put it in the right place, the Eclipse+AIDL tool
will generate a file with the same name, but .java extension.

So I now have /gen/com.protechtraining.com/IAdditionService.java file. This is an


auto-generated file so you don't want to edit it.

What is important is that it contains a Stub class that we'll want to implement for
our remote service.

To implement our remote service, we'll return the IBinder from onBind() method in
our service class, AdditionService. The IBinder represents the implementation of the
remote service. To implement IBinder, we subclass IAddtionService.Stub class from
the auto-generated Java code, and provide implementation for our AIDL-defined
methods, in this case add().
/src/com.marakana/AdditionService.java

/** @Override
* This class exposes the remote public IBinder onBind(Intent intent) {
service to the client
*/ return new IAdditionService.Stub() {
public class AdditionService /**
extends Service { * Implementation of the add() method
private static final String TAG = */
"AdditionService"; public int add(int value1, int value2) throws
RemoteException {
@Override Log.d(TAG,
public void onCreate() { String.format("AdditionService.add(%d,
super.onCreate(); %d)",value1, value2));
Log.d(TAG, "onCreate()"); return value1 + value2;
} }};}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy()");
}
}

Exposing the Service Locally

Once we have the service implement the onBind() properly, we are ready to connect to
that service from our client. In this case, we have AIDLDemo activity connecting to
that service. To establish the connection, we need to implement ServiceConnection
class. Our activity in this example provides this implementation in
AdditionServiceConnection inner class by implementing onServiceConnected() and
onServiceDiconnected() methods. Those callbacks will get the stub implementation of
the remote service upon connection. We need to cast them from stubs to our AIDL
service implementation. To do that, we use the
IAdditionService.Stub.asInterface((IBinder) boundService) helper method.

From that point on, we have a local service object that we can use to make calls against
the remote service.
/src/com.marakana/AIDLDemo.java

public class AIDLDemo extends Activity {


private static final String TAG = "AIDLDemo";
IAdditionService service;
AdditionServiceConnection connection;

/**
* This class represents the actual service connection. It casts the bound
* stub implementation of the service to the AIDL interface.
*/
class AdditionServiceConnection implements ServiceConnection {

public void onServiceConnected(ComponentName name, IBinder


boundService) {
service = IAdditionService.Stub.asInterface((IBinder) boundService);
Log.d(AIDLDemo.TAG, "onServiceConnected() connected");
Toast.makeText(AIDLDemo.this, "Service connected",
Toast.LENGTH_LONG)
.show();
}
public void onServiceDisconnected(ComponentName name) {
service = null;
Log.d(AIDLDemo.TAG, "onServiceDisconnected() disconnected");
Toast.makeText(AIDLDemo.this, "Service connected", Toast.LENGTH_LONG)
.show();
}
}
/** Binds this activity to the service. */
private void initService() {
connection = new AdditionServiceConnection();
Intent i = new Intent();
i.setClassName("com.marakana", com.marakana.AdditionService.class.getName());
boolean ret = bindService(i, connection, Context.BIND_AUTO_CREATE);
Log.d(TAG, "initService() bound with " + ret);
}
/** Unbinds this activity from the service. */
private void releaseService() {
unbindService(connection);
connection = null;
Log.d(TAG, "releaseService() unbound.");
}

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


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

initService();

// Setup the UI
Button buttonCalc = (Button) findViewById(R.id.buttonCalc);

buttonCalc.setOnClickListener(new OnClickListener() {
TextView result = (TextView) findViewById(R.id.result);
EditText value1 = (EditText) findViewById(R.id.value1);
EditText value2 = (EditText) findViewById(R.id.value2);
public void onClick(View v) {
int v1, v2, res = -1;
v1 = Integer.parseInt(value1.getText().toString());
v2 = Integer.parseInt(value2.getText().toString());

try {
res = service.add(v1, v2);
} catch (RemoteException e) {
Log.d(AIDLDemo.TAG, "onClick failed with: " + e);
e.printStackTrace();
}
result.setText(new Integer(res).toString());
}
});
}

/** Called when the activity is about to be destroyed. */


@Override
protected void onDestroy() {
releaseService();
}
}
The UI in this case is very simple. There are couple of TextViews and
EditText fields and a button The button handles its events in an anonymous
inner class OnClickListener. The button simply invokes the add() method on
the service as if it was a local call.

/res/layout/main.xml

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


<LinearLayout
<TextView android:text="AIDL Demo“ />

<EditText
android:id="@+id/value1"
android:hint="Value 1"></EditText>

<TextView android:id="@+id/TextView01“
android:text="+“></TextView>
<EditText
android:id="@+id/value2"
android:hint="Value 2"></EditText>

<Button
android:id="@+id/buttonCalc"
android:text="="></Button>

<TextView android:text="result“
android:id="@+id/result"></TextView>
</LinearLayout>
Topic 4 : Payment Gateway
RAZORPAY INTEGRATION
ANDROID STUDIO
MM.DD.20XX ADD A FOOTER 38
MM.DD.20XX ADD A FOOTER 39
MM.DD.20XX ADD A FOOTER 40
MM.DD.20XX ADD A FOOTER 41
MM.DD.20XX ADD A FOOTER 42
MM.DD.20XX ADD A FOOTER 43
MM.DD.20XX ADD A FOOTER 44
MM.DD.20XX ADD A FOOTER 45
MM.DD.20XX ADD A FOOTER 46
MM.DD.20XX ADD A FOOTER 47
MM.DD.20XX ADD A FOOTER 48
MM.DD.20XX ADD A FOOTER 49
MM.DD.20XX ADD A FOOTER 50
MM.DD.20XX ADD A FOOTER 51
MM.DD.20XX ADD A FOOTER 52
https://www.geeksforgeeks.org/how-to-
integrate-razorpay-payment-gateway-in-
android/

https://dashboard.razorpay.com/app/keys
Topic 5: Android Jetpack Technology - II
https://www.metizsoft.com/blog/android-
jetpack-navigation-component
Topic 6: Introduction to IOS features and
Objective C Features
iOS (formerly iPhone OS) is a mobile operating system created and developed
by Apple Inc. exclusively for its hardware.
It is the operating system that powers many of the company's mobile devices,
including the iPhone and iPod Touch; t
he term also included the versions running on iPads until the name iPadOS was
introduced with version 13 in 2019.
It is the world's second-most widely installed mobile operating system, after
Android.
It is the basis for three other operating systems made by Apple: iPadOS, tvOS,
and watchOS.
It is proprietary software, although some parts of it are open source under the
Apple Public Source License and other licenses.
https://developer.apple.com/library/archive/navigation/
Explore the World with Apple Maps
Apple is committed to building the world’s
best map, and iOS takes Maps even further
with brand new ways to navigate and explore.
Users will experience significantly enhanced
details in cities for neighborhoods,
commercial districts, elevation, and buildings,
new road colors and labels, custom-designed
landmarks, and a new night-time mode with a
moonlit glow. This is a whole new way of
looking at the world through Maps.
New Privacy Features
iOS introduces even more privacy controls to
help protect user information. With on-device
speech recognition, audio of Siri requests is
now processed entirely on iPhone by default,
and performance improves significantly. Mail
Privacy Protection stops senders from learning
whether an email has been opened, and hides
IP addresses so senders can’t learn a user’s
location or use it to build a profile on them.
App Privacy Report offers an overview of how
apps use the access that has been granted to
location, photos, camera, microphone, and
contacts in the last seven days, and which
other domains are contacted.
Redesigned Weather and Notes Apps
Weather includes more graphical displays of
weather data, full-screen maps, and dynamic
layouts that change based on conditions.
Beautifully redesigned animated backgrounds
more accurately reflect the sun’s position and
precipitation, and notifications highlight when
rain or snow starts and stops.
iCloud+ combines everything users love about iCloud with new premium
features, including Hide My Email, expanded HomeKit Secure Video
support, and an innovative new internet privacy service, iCloud Private
Relay, at no additional cost.9 Current iCloud subscribers will be upgraded to
iCloud+ automatically this fall. All iCloud+ plans can be shared with people
in the same Family Sharing group, so everyone can enjoy the new features,
storage, and elevated experience that comes with the service.
The Health app gets a new sharing tab that lets users share
their health data with family, caregivers, or a care team,
Trends gives users a way to focus attention on meaningful
changes in personal health metrics, and Walking Steadiness
is a new metric that empowers people to proactively
manage their fall risk.
Objective-C is a general-purpose, object-oriented programming
language that adds Smalltalk-style messaging to the C
programming language.
This is the main programming language used by Apple for the
OS X and iOS operating systems and their respective APIs,
Cocoa and Cocoa Touch.
This reference will take you through simple and practical
approach while learning Objective-C Programming language.

https://www.tutorialspoint.com/objective_c/index.htm
It is primarily used in developing iOS and Mac OS X operating
systems as well as its applications.

Initially, Objective-C was developed by NeXT for its NeXTSTEP OS


from whom it was taken over by Apple for its iOS and Mac OS X.

Object-Oriented Programming
Objective-C fully supports object-oriented programming, including the
four pillars of object-oriented development −

Encapsulation
Data hiding
Inheritance
Polymorphism
https://www.tutorialspoint.com/objective_c/index.htm

You might also like