Anushka Yadav (INDTRIAL)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 81

An

Industrial Training Report


On
“Android Studio”
Submitted
In partial fulfillment
For the award of the Degree of
Bachelor of Technology
in Department of Computer Science and Engineering

Submitted to: Submitted By:

Dr. Subhash Chandra Anushka Yadav

HOD, CSE 19ERWCS010

Department of Computer Science and Engineering


Rajasthan College of Engineering for Women
Rajasthan Technical University
Session: 2023

1
Candidate’s Declaration

I hereby declare that the work, which is being presented in the Industrial Training, entitled “Android Studio” in
partial fulfillment for the award of Degree of “Bachelor’s of Technology” in Department of Computer Science
and Engineering and submitted to the Department of Computer Science & Engineering, Rajasthan College Of
Engineering For Women, Rajasthan Technical University is a record of my own investigations carried under the
Guidance of Dr. Subhash Chandra, Department of Computer Science & Engineering, RCEW.

I have not submitted the matter presented in this Dissertation anywhere for the award of any other Degree.

Anushka Yadav
19ERWCS010

Rajasthan College of Engineering for Women, Jaipur

Counter Signed by

Dr. Subhash Chandra

Associate Professor

Department of Computer Science and Engineering

2
Certificate

This is to certify that the Industrial training report entitled “Android Studio” done by Ms. Anushka Yadav,
Enrollment no. 19ERWCS010 is an authentic work carried out by her at Rajasthan College of Engineering for
Women under my guidance. The matter embodied in this dissertation work has not been submitted earlier for the
award of any degree or diploma to the best of my knowledge and belief.

Dr. Subhash Chandra

Associate Professor

Rajasthan College of Engineering for Women, Jaipur

Rajasthan Technical University

3
Acknowledgement

I would like to thank the HOD, Computer Science and Engineering Dr. Subhash Chandra for his valuable
guidance. I appreciate his presence for giving all discussions, suggestions and the time for me whenever I needed
him. He consciously or unconsciously leveraged his key and creative insights wherever applicable in the project.
Amidst of him busy schedule, he made himself available for any query related to project almost every time. I
sincerely appreciate his contributions in terms of time and ideas.

I would also like to give my special thanks to Director Dr. Shraddha Arya for providing the opportunity and
support to me for this work.

I would also offer my deepest gratitude towards the Management of Rajasthan College of Engineering for
Women, Dr. Jitendra Singh Fauzdar and Mrs. Beena Singh, for providing me a spirit to put my every effort
and hard work for the completion of the work.

I also want to thank my all department faculties and staff members, friends and family for their encouragement
and support. In particular, I am grateful to my parents for their love and for instilling in me a deep sense of
academic pride.

Lastly, I offer my regards and blessings to all of those who supported me in any respect during the completion of
the work.

Anushka Yadav
19ERWCS010

4
Abstract

Java was developed by James Gosling at Sun Microsystems Inc in the year 1995, later acquired
by Oracle Corporation. It is a simple programming language. Java makes writing, compiling,
and debugging programming easy. It helps to create reusable code and modular programs.
Java is a class-based, object-oriented programming language and is designed to have as few
implementation dependencies as possible. A general-purpose programming language made for
developers to write once run anywhere that is compiled Java code can run on all platforms that
support Java. Java applications are compiled to byte code that can run on any Java Virtual
Machine. The syntax of Java is similar to c/c++. The principles for creating java were simple,
robust, secured, high performance, portable, multi-threaded, interpreted, dynamic, etc. In 1995
Java was developed by James Gosling, who is known as the Father of Java. Currently, Java is
used in mobile devices, internet programming, games, e-business, etc. It is a programming
language created in 1991. James Gosling, Mike Sheridan, and Patrick Naughton, a team of
Sun engineers known as the Green team initiated the Java language in 1991. Sun Microsystems
released its first public implementation in 1996 as Java 1.0. It provides no-cost -run-times on
popular platforms. Java1.0 compiler was re-written in Java by Arthur Van Hoff to strictly
comply with its specifications. With the arrival of Java 2, new versions had multiple
configurations built for different types of platforms. In 1997, Sun Microsystems approached
the ISO standards body and later formalized Java, but it soon withdrew from the process. At
one time, Sun made most of its Java implementations availablewithout charge, despite their
proprietary software status. Sun generated revenue from Java through the selling of licenses
for specialized products such as the Java Enterprise System.
Android dominates the mobile OS industry because of the long list of features it provides. It’s
user-friendly, has huge community support, provides a greater extent of customization, and a
large number of companies build Android-compatible smartphones. As a result, the market
observes a sharp increase in the demand for developing Android mobile applications, and with
that companies need smart developers with the right skill set. At first, the purpose of Android
was thought of as a mobile operating system. However, with the advancement of code libraries
and its popularity among developers of the divergent domain, Android becomesan absolute
set of software for all devices like tablets, wearables, set-top boxes, smart TVs, notebooks,
etc.
Healthcare organizations are considering mobile apps to offer supreme services across
boundaries. In recent times, mHealth apps have gained significant momentum as they redefine
the healthcare ecosystem. Today, they are the vital forerunner to extend the reach for the
medical and healthcare industry by enhancing efficiency, communication & quality of care
amenities. Smartphone medical applications are becoming increasingly popular around the
world, with more people using them for everything from medical treatments to general health
and well-being.

5
Chapter 1
Basic Java
Java is a high-level, general-purpose, object-oriented, and secure programming language
developed by James Gosling at Sun Microsystems, Inc. in 1991. It is formally known as OAK.
In 1995, Sun Microsystem changed the name to Java. In 2009, Sun Microsystem takeover by
Oracle Corporation.

1.1. Editions of Java


Each edition of Java has different capabilities. There are three editions of Java: Java
Standard Editions (JSE): It is used to create programs for a desktop computer.Java
Enterprise Edition (JEE): It is used to create large programs that run on the server and
manages heavy traffic and complex transactions.

Java Micro Edition (JME): It is used to develop applications for small devices such as
set-topboxes, phone, and appliances.

1.2. Types of Java Applications


There are four types of Java applications that can be created using Java programming:
Standalone Applications: Java standalone applications uses GUI components such as AWT, Swing,
and JavaFX. These components contain buttons, list, menu, scroll panel, etc. It is alsoknown as
desktop alienations.
Enterprise Applications: An application which is distributed in nature is called enterprise
applications.
Web Applications: An applications that run on the server is called web applications. We useJSP,
Servlet, Spring, and Hibernate technologies for creating web applications.
Mobile Applications: Java ME is a cross-platform to develop mobile applications which runacross
smartphones. Java is a platform for App Development in Android.

1.3. Features of Java


• Simple: Java is a simple language because its syntax is simple, clean, and easy to
understand. Complex and ambiguous concepts of C++ are either eliminated or re-
implemented in Java. For example, pointer and operator overloading are not used inJava.

6
• Object-Oriented: In Java, everything is in the form of the object. It means it has somedata
and behavior. A program must have at least one class and object.

• Robust: Java makes an effort to check error at run time and compile time. It uses a strong
memory management system called garbage collector. Exception handling and garbage
collection features make it strong.

• Secure: Java is a secure programming language because it has no explicit pointer and
programs runs in the virtual machine. Java contains a security manager that defines theaccess
of Java classes.

• Platform-Independent: Java provides a guarantee that code writes once and run
anywhere. This byte code is platform-independent and can be run on any machine.

• Portable: Java Byte code can be carried to any platform. No implementation- dependent
features. Everything related to storage is predefined, for example, the sizeof primitive data
types.

• High Performance: Java is an interpreted language. Java enables high performancewith


the use of the Just-In-Time compiler.

• Distributed: Java also has networking facilities. It is designed for the distributed
environment of the internet because it supports TCP/IP protocol. It can run over the
internet. EJB and RMI are used to create a distributed system.

• Multi-threaded: Java also supports multi-threading. It means to handle more than onejob a
time.

Fig. 1.1 Java


When we consider a Java program, it can be defined as a collection of objects that
communicate via invoking each other's methods. Let us now briefly look into what do class,
object, methods, and instance variables mean.

7
• Object − Objects have states and behaviors. Example: A dog has states - color, name,breed
as well as behavior such as wagging their tail, barking, eating. An object is an instance of a
class.

• Class − A class can be defined as a template/blueprint that describes the behavior/statethat


the object of its type supports.

• Methods − A method is basically a behavior. A class can contain many methods. It isin
methods where the logics are written, data is manipulated and all the actions are executed.

• Instance Variables − Each object has its unique set of instance variables. An object'sstate
is created by the values assigned to these instance variables.

1.4. Basic Syntax


About Java programs, it is very important to keep in mind the following points.
• Case Sensitivity − Java is case sensitive, which means identifier Hello and hello wouldhave
different meaning in Java.

• Class Names − For all class names the first letter should be in Upper Case. If severalwords
are used to form a name of the class, each inner word's first letter should be inUpper Case.

Example: class MyFirstJavaClass

• Method Names − All method names should start with a Lower Case letter. If severalwords
are used to form the name of the method, then each inner word's first letter should be in
Upper Case.
Example: public void myMethodName()

• Program File Name − Name of the program file should exactly match the class name.

When saving the file, you should save it using the class name (Remember Java is case sensitive) and
append '.java' to the end of the name (if the file name and the class name do notmatch, your program
will not compile).

8
1.5. Java Keywords
Keywords are the special words that are basically reserved keywords in any programming
language. We cannot use them in the rest of the programs. We can only use them as the name
of variables in Java, class, or method. Java has around 50 keywords which are basics to java:

Fig. 1.2 Keywords

9
1.6. Data Types
There is a basic java data type for each variable in Java. The data type of a variable determines the
type of data the variable can contain, and what operations we can execute on it.Every bit of
processed data every day is divided into types. The type of data is called a datatype. There are
various kinds of data types in Java.
Broadly, the data types are mainly of two categories:
When saving the file, you should save it using the class name (Remember Java is case sensitive)
and append '.java' to the end of the name (if the file name and the class name do notmatch, your
program will not compile).
But please make a note that in case you do not have a public class present in the file then filename
can be different than class name. It is also not mandatory to have a public class in the file.
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as
'MyFirstJavaProgram.java'
public static void main(String args[]) − Java program processing starts from the main()
method which is a mandatory part of every Java program.

10
Chapter 2
Advance java

The dictionary meaning of advance is a forward movement or a development or improvementand


the meaning of improve means thing that makes something better. All in all, we have to improve
our basic knowledge to master in that particular field.
Java is divided into two parts i.e. Core Java (J2SE) and Advanced Java (JEE). The core Java part
covers the fundamentals (data types, functions, operators, loops, thread, exception handling, etc.)
of the Java programming language. It is used to develop general purpose applications. Whereas
Advanced Java covers the standard concepts such as database connectivity, networking, Servlet,
web-services, etc. In this section, we will discuss what is advance Java, its benefit, uses, topics of
advance Java, and the difference between core Javaand advance Java.

It is a part of Java programming language. It is an advanced technology or advance version ofJava


specially designed to develop web-based, network-centric or enterprise applications. It includes the
concepts like

• Servelet, JSP
• JDBC
• Socket Programming.

Most of the applications developed using advance Java uses tow-tier architecture i.e. Clientand
Server. All the applications that runs on Server can be considered as advance Java application.

Most of the applications developed using advance Java uses tow-tier architecture i.e. Clientand
Server. All the applications that runs on Server can be considered as advance Java applications.

2.1. Why advance Java?

• It simplifies the complexity of a building n-tier application.


• Standardizes and API between components and application sever container.
• JEE application Server and Containers provides the framework services.

2.2. Benefits of Advance Java


The four major benefits of advance Java that are, network centric, process simplification, and
futuristic imaging standard.

11
• JEE (advance Java) provides libraries to understand the concept of Client-Server
architecture for web- based applications.
• We can also work with web and application servers such as Apache
Tomcat and Glassfish Using these servers, we can understand the working of HTTPprotocol. It cannot be done in
core Java.
• It is also important understand the advance Java if you are dealing with tradingtechnologies like Hadoop,
cloud-native and data science.
• It provides a set of services, API and protocols, that provides the functionality whichis
necessary for developing multi-tiered application, web-based application.

2.3. Java JDBC


JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute thequery
with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBCdrivers to
connect with the database. There are four types of JDBC drivers:
• JDBC-ODBC Bridge Driver,
• Native Driver,
• Network Protocol Driver, and
• Thin Driver

A list of popular interfaces of JDBC API are given below:

• Driver interface
• Connection interface
• Statement interface
• PreparedStatement interface
• CallableStatement interface
• ResultSet interface
• ResultSetMetaData interface
• DatabaseMetaData interface
• RowSet interface

12
2.4. Why Should We Use JDBC
Before JDBC, ODBC API was the database API to connect and execute the query with the
database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform
dependent and unsecured). That is why Java has defined its own API (JDBC API) that usesJDBC
drivers (written in Java language).
We can use JDBC API to handle database using Java program and can perform the following
activities:
• Connect to the database
• Execute queries and update statements to the database
• Retrieve the result received from the database.

2.5. JDBC Drivers


JDBC Driver is a software component that enables java application to interact with the
database. There are 4 types of JDBC drivers:
• JDBC-ODBC bridge driver
• Native-API driver (partially java driver)
• Network Protocol driver (fully java driver)
• Thin driver (fully java driver)

2.6. Java Database Connectivity with 5 Steps


There are 5 steps to connect any java application with the database using JDBC. These stepsare
as follows:
• Register the Driver class
• Create connection
• Create statement
• Execute queries
• Close connection

Register the driver class

The forName() method of Class class is used to register the driver class.This
method is used to dynamically load the driver class.

Syntax of forName() method

13
public static void forName(String className)throws ClassNotFoundException
1) Create the connection object

The getConnection() method of DriverManager class is used to establish connection


with the database.

Syntax of getConnection() method

public static Connection getConnection(String url)throws SQLException


public static Connection getConnection(String url,String name,String password)
throws SQLException
2) Create the Statement object

The createStatement() method of Connection interface is used to create statement.


The object of statement is responsible to execute queries with the database.

Syntax of createStatement() method


public Statement createStatement()throws SQLException
3) Execute the query

The executeQuery() method of Statement interface is used to execute queries to the database.
This method returns the object of ResultSet that can be used to get all the records of a table.

Syntax of executeQuery() method


public ResultSet executeQuery(String sql)throws SQLException
4) Close the connection object

By closing connection object statement and ResultSet will be closed automatically.


The close() method of Connection interface is used to close the connection.

Syntax of close() method


public void close()throws SQLException
EXAMPLE:-

1.Class.forName("oracle.jdbc.driver.OracleDriver");
2.Connection con=DriverManager.getConnection(

"jdbc:oracle:thin:@localhost:1521:xe","system","password");
3. Statement stmt=con.createStatement();
4. ResultSet rs=stmt.executeQuery("select * from emp");
14
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2)); }
5.con.close();

2.6.1. Java Database Connectivity with MySQL

To connect Java application with the MySQL database, we need to follow 5 following steps.
In this example we are using MySql as the database. So we need to know following
informations for the mysql database:
o Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
o Connection URL: The connection URL for the mysql database
is jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database,
localhost is the server name on which mysql is running, we may also use IP address,
3306 is the port number and sonoo is the database name. We may use any database, in
such case, we need to replace the sonoo with our database name.
o Username: The default username for the mysql database is root.
o Password: It is the password given by the user at the time of installing the mysql
database. In this example, we are going to use root as the password.

To connect java application with the mysql database, mysqlconnector.jar file is required to
be loaded.

Two ways to load the jar file:

o Paste the mysqlconnector.jar file in jre/lib/ext folder


o Set classpath

1) Paste the mysqlconnector.jar file in JRE/lib/ext folder:

Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar file here.

2) Set classpath:

Go to environment variable then click on new tab. In variable name write classpath and in
variable value paste the path to the mysqlconnector.jar file by appending
mysqlconnector.jar;.;
as C:\folder\mysql-connector-java-5.0.8-bin.jar;.;

15
2.7. DriverManager class
DriverManager class is the component of JDBC API and also a member of
the java.sql package.
The DriverManager class acts as an interface between users and drivers. It keeps track of the
drivers that are available and handles establishing a connection between a database and the
appropriate driver.
It contains all the appropriate methods to register and deregister the database driver class and
to create a connection between a Java application and the database. The DriverManager class
maintains a list of Driver classes that have registered themselves by calling the method
DriverManager.registerDriver().

2.8. Connection Interface

Connection is a session between a Java application and a database. It helps to establish a


connection with the database. The Connection interface is a factory of Statement,
PreparedStatement, and DatabaseMetaData, i.e., an object of Connection can be used to get
the object of Statement and DatabaseMetaData. The Connection interface provide many
methods for transaction management like commit(), rollback(), setAutoCommit(),
setTransactionIsolation(), etc.

2.9 Statement interface

The Statement interface provides methods to execute queries with the database. The
statement interface is a factory of ResultSet i.e. it provides factory method to get the object of
ResultSet.

Commonly used methods of Statement interface:


The important methods of Statement interface are as follow

1)public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the
Object of ResultSet.

2) public int executeUpdate(String sql): is used to execute specified query, it may be create,
drop, insert, update, delete etc.

3) public boolean execute(String sql): is used to execute queries that may return multiple results.

4) public int[] executeBatch(): is used to execute batch of commands.

16
2.10. ResultSet
The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points to before
the first row. By default, ResultSet object can be moved forward only and it is not updatable.
But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int)
method as well as we can make this object as updatable by:
Example:
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);

2.11. PreparedStatement interface


The PreparedStatement interface is a subinterface of Statement. It is used to execute
parameterized query.
Let's see the example of parameterized query:
String sql="insert into emp values(?,?,?)";

As you can see, we are passing parameter (?) for the values. Its value will be set by calling the
setter methods of PreparedStatement.
USE: Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.
2.12. Java ResultSetMetaData Interface
The metadata means data about data i.e. we can get further information from the data.
If you have to get metadata of a table like total number of column, column name, column type
etc. , ResultSetMetaData interface is useful because it provides methods to get metadata from
the ResultSet object.
CODE:
import java.sql.*;

class Rsmd{

17
public static void main(String args[]){

try{

Class.forName("oracle.jdbc.driver.OracleDriver");

Connection con=DriverManager.getConnection(

"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

PreparedStatement ps=con.prepareStatement("select * from

emp");ResultSet rs=ps.executeQuery();

ResultSetMetaData rsmd=rs.getMetaData();
System.out.println("Total columns: "+rsmd.getColumnCount());
System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));

System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1));

con.close();

}catch(Exception e){ System.out.println(e);}


}
}:
Total columns: 2
Column Name of 1st Column Type Name of 1st column: NUMBE

2.13. JDBC Data Types


The JDBC driver converts the Java data type to the appropriate JDBC type, before sending it to the
database. It uses a default mapping for most data types. For example, a Java int is converted to
an SQL INTEGER. Default mappings were created to provide consistency between drivers.

18
fig 3.10.1 data types

Handling NULL Values


SQL's use of NULL values and Java's use of null are different concepts. So, to handle SQL NULL
values in Java, there are three tactics you can use −
Avoid using getXXX( ) methods that return primitive data types.
Use wrapper classes for primitive data types, and use the ResultSet object's wasNull( ) method to test
whether the wrapper class variable that received the value returned by the getXXX( ) method should be
set to null.
Use primitive data types and the ResultSet object's wasNull( ) method to test whether the primitive
variable that received the value returned by the getXXX( ) method should be set to an acceptable

19
2. Java Swing
Java Swing is part of Java Foundation Classes. It is used to create window-based applications
which makes it suitable for developing lightweight desktop applications. Java Swing is built on
top of an abstract windowing toolkit API purely written in Java programming language.
Java Swing provides lightweight and platform-independent components,
making it suitable and efficient in designing and developing desktop-based
applications (systems).
4.1. Prerequisites
To follow through this article, you will need to have:
NetBeans installed
JDK installed
Basic knowledge of Java programming language
As discussed earlier, Swing is used in creating window-based applications. Swing components
are contained in the javax.swing package.
Java Swing Components are essential building blocks for designing, developing, and implementing
an application. These components form the Swing Graphical User Interface widget toolkit for
Java programming language.
In NetBeans IDE, components are found under the palette. Java Swing components provide an
interactive experience with the application
These include:
JFrame
JLabel
JTextField
JButton
Others Include: JPanel, JComboBox, JRadioButton, JCheckBox, JTable, JList, JFileChose, JTextArea

3.1 Frame

JFrame is the very first component in the Java Swing Component hierarchy. It can be created in two ways:

20
1) By creating an object of the Frame class. That is, creation through association.

import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
JFrame sectionFrame = new JFrame();
sectionFrame.setSize(600, 600); // 600 width & 600 height
sectionFrame.setLayout(null); // no layout managers
sectionFrame.setVisible(true); // frame visible
}
}

2) By extending the Frame class. That is, OOP creation through class inheritance.

import javax.swing.JFrame;
public class sectionHomeWindow extends JFrame {
/**
* Creates new form sectionHomeWindow
*/
public sectionHomeWindow() {

}
}

3.2. JLabel
JLabel is a component which displays a readable text or an image in the Swing Container User interface.
The application user cannot edit the text rendered in the JLabel.
However, the application itself, through action events, can change the text. JLabel component can display
both plain and HTML text.

21
JLabel labelName = new JLabel("Name");

fig 3.3.1: JTextField example

22
3.3 JTextField
JTextField is a swing component that allows users to input one line of text. JTextField inherits
from the JTextComponent class of javax.swing Library.

Example:

JTextField sectionTextField = new JTextField(20);

For JTextField to be accessible and editable, enable property must be set to


true. JTextField can be initialized by calling the JTextField constructor and passing a
parameter of integer type.
The integer parameter passed in the constructor does not limit the number of characters a user
can key in the text field. However, it sets the width of the text field box; i.e. the number of
columns to be assigned to it.

3.4. JButton
JButton is one of the swing components which gives swing the property of platform
independence. This component creates a click effect on the application’s user interface. It is
implemented in an application by calling any of its class constructors.
Clicking or double clicking on it results in retrieving data from databases and displaying them
on the UI, or collecting user’s data on UI and storing/saving them into a database.
JButton in most applications contains text or an image which communicates to the user what
the button does.

Example:

JButton submitButton = new JButton("Submit");

Fig 3.4.1 JButton example

Differences between Java Swing and Java AWT

23
Both Java Swing and Java Abstract Window Toolkit (AWT) are used to design graphical user
interfaces using Java.
However, they have differences that would make one suitable over the other; depending on
what one wants to achieve.
Some of the differences are:
Java AWT has a set of functions and procedures that create applications that can access
features or information of the Operating system, other applications, or even services. Java
AWT is an Application Programming Interface (API) that develops Java graphical user
interfaces. On the other hand, Java Swing is formed from Java Foundation Classes, making it
suitable for creating independent applications.
Java AWT components are heavy since they interact with the Operating System. On the other
hand, Java Swing’s components are lightweight and powerful, hence has more functionality
compared to Java AWT.
Applications done in Java Swing are faster and more efficient compared to those done in Java
AWT. Swing has less execution time compared to AWT.
Java AWT is an API framework which makes it platform-dependent since its components
depend on the platform. On the other hand, Swing components do not depend on the platform.
Hence Swing is platform-independent.

3.5.Conclusion of Java Swing


Java Swing is very easy to use. Being platform-independent and lightweight, its applications
are significantly faster and reliable.
NetBeans IDE provides a simple and friendly GUI to drag and drop Swing components
effortlessly, thereby making the design of an application very easy.
• Differences between Java swing and Java AWT.
• Java Swing components commonly used in desktop application development.
• Sample design of a simple desktop application using NetBeans IDE.

24
3. Android

Android is a complete set of software for mobile devices such as tablet computers, notebooks,
smartphones, electronic book readers, set-top boxes etc. Android is a mobile operating system
that is based on a modified version of Linux. Android’s Linux operating system kernel provides
low level interface with hardware, memory management and process control which is
optimized for mobile devices. It contains a Linux-based Operating System, middleware and
key mobile applications.
It can be thought of as a mobile operating system. But it is not limited to mobile only. It is
currently used in various devices such as mobiles, tablets, televisions etc.It 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.

4.1. Architecture of Android


Android’s architecture can be divided into four layers.
i. Linux Kernel
ii. Libraries + Android Runtime
iii. Application Framework
iv. Applications

i. Linux Kernel: Android is based on Linux Kernel layer. It contains all low level device
drivers for various hardware components of an Android device like display driver,
camera driver, memory driver, keypad driver etc. It also provides some core services
like security service, network service, power management and process management for
android devices.

ii. Libraries: These are basic libraries developed in C/C++ and provide functionality to
interact with Android. Some basic libraries are Surface Manager (for display
management), SQLite (for database support), SSL and WebKit (for web browsing
and internet security) etc.

25
Android Runtime: Android runtime provides a set of core libraries that enable
developers to write android applications using Java programming language. The
android runtime also includes Dalvik Virtual Machine, which is responsible to run
android applications.
Dalvik is a specialized virtual machine designed specifically for Android and
optimized for battery powered mobile devices with limited memory and CPU.
Dalvik uses the device’s underlying Linux kernel to handle low level functionality
including security, threading, process and memory management.

iii. Application Framework: Application framework provides classes for hardware access,
managing user interface and application resources.

iv. Applications: At this layer all Android factory and third party applications resides.

Fig. 4.1 Architecture of Android

26
4.2. Types of Android Applications
Android application can be divided into following categories.
• Foreground: These applications provide their functionality when they are visible
on device’s screen. For example games and maps applications.

• Background: These applications spend most of their lifetime hidden and have very
little interaction from user. For example call responding service, messaging
service.

• Intermittent: These applications expect some interaction but do most of their work in
background. These
applications often run silently and notify users when appropriate. Example : media
player.

• Widget: These are home screen components.

4.3. Components of Android Application


Following six components provide basic building blocks for an android application:
• Activities: An activity represents a single screen with a user interface. An
activity is implemented as a subclass of android.app.AppCompactActivity
class.

• Services: A service is a component that runs in the background. They are


used to perform regular processing that needs to continue even when our
application is not active or visible.

• Content Providers: A content provider manages a shared set of application data.


We can store the data in the file system, SQLite database, on the web, or any
other persistent storage location our application can access.Content providers are
also useful for reading and writing data that is private to our application and not
shared.

• Broadcast Receivers: A broadcast receiver is a component that responds to system-


wide broadcast announcements. Many broadcasts originate from the system—for
example, a broadcast announcing that the screen has turned off, the battery is low,
or a picture was captured. Applications can also initiate broadcasts—for example,

27
to let other applications know that some data has been downloaded to the device
and is available for them to use.

• Intents: Using Intents we can broadcast message system wide or to a specific


activity or service.

• Notifications: Notifications let us signal users without interrupting their


current Activities. These are preferred to get user’s attentions for background
attention.

4.4. Activity Class (android.app package)

An Activity represents user interface of our application. An application can have zero or
more activities. We must extend android.app.Activity class to create user interface of our
applications. Activity class defines some methods, which represents various stages of an
activity we have to override them in order to provide functionality in our application. These
methods are:

1. onCreate(): it is called when activity is first created.

2. onStart(): it is called when activity becomes visible to user.

3. onResume(): it is called when starts interaction with user.

4. onPause(): it is called when current activity is being paused and other activity is being
resumed.

5. onStop(): it is called when activity in no longer visible to user.

6. onDestroy(): it is called when activity is destroyed by the system.

7. onRestart(): it is called when activity has been stopped and restarting again.

Activity Life Cycle is an activity’s life span is represented by seven methods defined in
Activity class. Following figure represents life cycle of an Activity.

28
Fig. 4.4.1. Activity life cycle

5. Application Management Software (AMS)


Mobile devices, whether emulators or real, interact with an application using their own
software, which is called Application Management Software (AMS). The AMS is responsible
for initializing, starting, pausing, resuming, and destroying an application. Besides these
services, AMS is responsible for installing and removing an application, as well. AMS
gracefully handles all the errors that occur during the installation end execution of
applications without crashing the system.
An application’s execution includes three valid states: Running, Paused and Destroyed. The
transitions between the different states are controlled by the AMS through the onStart(),
onPause() and onDestroy() methods implemented by the application. AMS first createsinstance
of an Activity by using its no-argument constructor and call its onCreate() method.Then AMS
invokes onStart() and onResume() methods respectively to put an activity in running state. In
running state an activity acquires resources it needs and perform its services. When the AMS
has determined that it no longer needs the Activity onPause() method and Activity is stopped
to enter paused state. In paused state Activity release its resources and become inactive. An
Activity can reenter the Running state when AMS calls itsonResume() method.
Finally when AMS has decided that it no longer needs an Activity it destroy the Activity by
calling the onStop() and onDestroy() methods respectively. In destroyed state an Activity
should release all resources and then terminate.

29
4.5. XML (Extensible Markup Language)
Extensible Markup Language (XML) is a language that defines a set of rules for encoding
documents in a format which is both human-readable and machine-readable.

• XML declaration
XML documents may begin by declaring some information about themselves, as in the
following example:
<?xml version="1.0" encoding="UTF-8"?>

XML Tags: XML tags are used to mark-up elements. XML tags are surrounded by angular
brackets.
There are two types of xml tags:
1. Container Tags:- These tags are used in pairs like <tag> and </tag>. The first tag in a
pair is the start tag, the second tag is the end tag. The text between the start and end
tags is the element content.
2. Empty Tags:- These tags are used alone like <tag />.These tags do not have an end
tag. We must add ending character (/) at the end of empty tags.
Note: XML is a case sensitive language.
• Tag Attributes:
Tags can have attributes. Attributes provide additional information about the XML elements.
Attributes always come in name-value pairs like: name="value".
Attributes are always added to the start tag of an XML element.
Ex: <tag attribute_name1=”value” attribute_name2=”value” ….> element content </tag>
<tag attribute_name1=”value” attribute_name2=”value” ................... />

• xmlns:android attribute:
xmlns stands for xml namespace. Since we can define custom tags (user defined tags) in xml,
xml parsers needs a way to recognize the attributes and their values. So xmlns attribute
specify namespace for our tags. Namespace is simply a document containing definition for
our tags and their attributes.
<tag xmlns:android=”http://schemas.android.com/apk/res/android” …>
</tag>

30
6.1 Elements of the AndroidManifest.xml file
The elements used in the above xml file are described below.
▫ <manifest>
manifest is the root element of the AndroidManifest.xml file. It has package
attribute that describes the package name of the activity class.
▫ <application>
application is the subelement of the manifest. It includes the namespace
declaration. This element contains several subelements that declares the
application component such as activity etc.
The commonly used attributes are of this element are icon, label, theme etc.
android:icon represents the icon for all the android application components.
android:label works as the default label for all the application components.
android:theme represents a common theme for all the android activities.
▫ <activity>
activity is the subelement of application and represents an activity that must be
defined in the AndroidManifest.xml file. It has many attributes such as label,
name, theme, launchMode etc.
android:label represents a label i.e. displayed on the screen.
android:name represents a name for the activity class. It is required attribute.
▫ <intent-filter>
intent-filter is the sub-element of activity that describes the type of intent to
which activity, service or broadcast receiver can respond to.
▫ <action>
It adds an action for the intent-filter. The intent-filter must have at least one
action element.
▫ <category>
It adds a category name to an intent-filter.

31
Fig 4.5.1 Files in android studio

4.7. Android Intent


Android Intent is the message that is passed between components such as activities, content
providers, broadcast receivers, services etc.
It is generally used with startActivity() method to invoke activity, broadcast receivers etc.
The dictionary meaning of intent is intention or purpose. So, it can be described as the
intention to do action.
The LabeledIntent is the subclass of android.content.Intent class.
Android intents are mainly used to:

• Start the service


• Launch an activity
• Display a web page
• Display a list of contacts
• Broadcast a message

32
• Dial a phone call etc.

7.1 Types of Android Intents


There are two types of intents in android: implicit and explicit.

1) Implicit Intent

Implicit Intent doesn't specifiy the component. In such case, intent


provides information of available components provided by the system
that is to be invoked.
For example, you may write the following code to view the webpage.

Intent intent=new Intent(Intent.ACTION_VIEW);

intent.setData(Uri.parse("http://www.javatpoint.com"));

startActivity(intent);

2) Explicit Intent

Explicit Intent specifies the component. In such case, intent provides


the external class to be invoked.

Intent i = new Intent(getApplicationContext(),


ActivityTwo.class; startActivity(i);

4.8. Install android studio


If you download the Android Studio from android site, you don't need to have eclipse IDE,
android SDK and eclipse Plugin because it is already included in Android Studio. If you have
downloaded the Android Studio, unjar it, go to eclipse IDE and start the eclipse by clicking on
the eclipse icon. You don't need to do any extra steps here.

4.9. Android studio emulator setup

a. Install the emulator


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

33
We can run an Android app form the Android Studio project, or we can run an app
which is installed on the Android Emulator as we run any app on a device. To start the
Android Emulator and run an application in our project:
i. In Android Studio, we need to create an Android Virtual Device (AVD) that
the emulator can use to install and run your app. To create a new AVD:-
ii. Open the AVD Manager by clicking Tools > AVD Manager.

Fig. 4.9.1 Virtual device config

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

34
Fig. 4.9.2 Hardware page

iv. Select a hardware profile and then click Next. If we don?t see the hardware
profile we want, then we can create or import a hardware profile. The System
Image page appears.
v. Select the system image for the particular API level and click Next. This leads
to open a Verify Configuration page.

35
Fig. 4.9.3 Verify configuration

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


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

36
Fig.4.9.4 Selecting AVD

viii. Click Run.

37
Fig. 4.10 Android Emulator

38
5. Chatbot

5.1 Introduction
An Android chatbot is an advanced computer software program with the ability to
understand a user’s query and respond in a natural manner without the intervention of
a human. Such a bot is AI-powered and developed using an algorithm to automate
customer communication on any scale.

By using a chatbot for Android, a business can improve customer support experience
on any channel and boost customer engagement. On top of that, the bot can automate
sales, customer service, and marketing activities apart from helping us engage with
the audience round the clock.

Chatbots are becoming increasingly popular because they can save businesses time
and money by automating simple tasks.

While chatbots are commonly found on websites as support chats, there are also many
other places where chatbots exist, which you may have never noticed. One of the
most common ones is within your smartphone.

A chatbot is likely a program you can talk to get information or perform tasks on your
phone. For example, on some phones, you can ask the chatbot for the weather
forecast or schedule an appointment. These chatbots use AI to understand the human
conversation.

You can disable the chatbot on your phone if you do not want to use it. The steps will
vary depending on your phone type and the make and model of your phone. Chatbots
help make your life easier, but if you do not want to use one, you can disable it.

5.2. Implementation in Android Studio

We will be building a simple application in which we will be building a simple


chatbot where we can ask a question to our bot and the bot will answer our questions.
we are going to implement this project using the Java language. We will be using
Brainshop for creating brain for creating brain API of our Chatbot.

Step by Step Implementation

Step 1: Create a New Project

Step 2: Add the below dependency in your build.gradle file

39
Step 3: Adding permissions to the internet in the AndroidManifest.xml file

Step 4: Working with the activity_main.xml file

Step 5: Creating a Modal class for storing our messages

40
Step 6: Creating a layout file for user messages

Step 7: Create a layout file for bot messages

41
Step 8: Working with the Adapter class

For setting data to our items of Chat RecyclerView we have to create an Adapter
class. Navigate to the app > java > your app’s package name > Right-click on it >
New > Java class and name your class as MessageRVAdapter and add the below code
to it. Comments are added inside the code to understand the code in more detail.

42
43
Step 9: Generating API key for using the chatbot service

Let’s visit Brainshop.ai and generate our simple account with username and
password. Simply create account on this website. After creating a new account we
will get to see the below screen. After creating account we have to request a new
password from the request password option and enter email address. After adding
email address we have to add the password to our account. Now we are good to go to
generate our API key.

44
Fig. 5.1 Setup

Follow the above steps to Generate a new brain for chatbot. After generating bot now
we will get the API URL for this brain. Navigate to the settings tab inside the created
brain we will get to see the bot details as shown below.

Fig 5.2 settings

Step 10: Working with the MainActivity.java file


Go to the MainActivity.java file and refer to the following code. Below is the code for the
MainActivity.java file. Comments are added inside the code to understand the code in more
detail.
import android.os.Bundle;

import android.view.View;

import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
45
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;

import org.json.JSONObject;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

// creating variables for our


// widgets in xml file.
private RecyclerView chatsRV;
private ImageButton sendMsgIB;
private EditText userMsgEdt;

private final String USER_KEY = "user";

private final String BOT_KEY = "bot";

// creating a variable for


// our volley request queue.
private RequestQueue mRequestQueue;

// creating a variable for array list and adapter class.


private ArrayList<MessageModal> messageModalArrayList;
private MessageRVAdapter messageRVAdapter;

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

// on below line we are initializing all our views.


46
chatsRV = findViewById(R.id.idRVChats);
sendMsgIB = findViewById(R.id.idIBSend);
userMsgEdt = findViewById(R.id.idEdtMessage);

// below line is to initialize our request queue.


mRequestQueue = Volley.newRequestQueue(MainActivity.this);

47
mRequestQueue.getCache().clear();

// creating a new array list


messageModalArrayList = new ArrayList<>();

// adding on click listener for send message button.


sendMsgIB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

// checking if the message entered


// by user is empty or not.
if (userMsgEdt.getText().toString().isEmpty()) {
// if the edit text is empty display a toast message.
Toast.makeText(MainActivity.this, "Please enter your message..",
Toast.LENGTH_SHORT).show();
return;

// calling a method to send message


// to our bot to get response.
sendMessage(userMsgEdt.getText().toString());

// below line we are setting text in our edit text as empty


userMsgEdt.setText("");
}
});

// on below line we are initialing our adapter class and passing our array list to it.
messageRVAdapter = new MessageRVAdapter(messageModalArrayList, this);

// below line we are creating a variable for our linear layout manager.
LinearLayoutManager linearLayoutManager = new
LinearLayoutManager(MainActivity.this, RecyclerView.VERTICAL, false);

// below line is to set layout


// manager to our recycler view.
chatsRV.setLayoutManager(linearLayoutManager);

// below line we are setting


// adapter to our recycler view.
chatsRV.setAdapter(messageRVAdapter);
}

private void sendMessage(String userMsg) {


48
// below line is to pass message to our

49
// array list which is entered by the user.
messageModalArrayList.add(new MessageModal(userMsg, USER_KEY));
messageRVAdapter.notifyDataSetChanged();

// url for our brain


// make sure to add mshape for uid.
// make sure to add your url.
String url = "Enter you API URL here" + userMsg;

// creating a variable for our request queue.


RequestQueue queue = Volley.newRequestQueue(MainActivity.this);

// on below line we are making a json object request for a get request and passing our
url .
JsonObjectRequest jsonObjectRequest = new
JsonObjectRequest(Request.Method.GET, url, null, new
Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {

try {

// in on response method we are extracting data


// from json response and adding this response to our array list.
String botResponse = response.getString("cnt");
messageModalArrayList.add(new MessageModal(botResponse, BOT_KEY));

// notifying our adapter as data changed.


messageRVAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();

// handling error response from bot.


messageModalArrayList.add(new MessageModal("No response",
BOT_KEY));
messageRVAdapter.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {

// error handling.
messageModalArrayList.add(new MessageModal("Sorry no response found",
BOT_KEY));
Toast.makeText(MainActivity.this, "No response from the bot..",
50
Toast.LENGTH_SHORT).show();
}

51
});

// at last adding json object


// request to our queue.

queue.add(jsonObjectRequest);
}
}

5.3. Technology of Our chatbot

Fig 5.3.1 Chatbot

52
Fig. 5.3.2 Chatbot app

53
6. LOCATION API
A data class representing a geographic location. A location consists of latitude, longitude,
timestamp, accuracy, and other information such as bearing, altitude and velocity. All
locations generated through LocationManager are guaranteed to have a valid latitude,
longitude, timestamp (both UNIX epoch time and elapsed realtime since boot), and accuracy.
All other parameters are optional.

6.1. Introduction

6.1.1. Build location-aware apps

One of the unique features of mobile applications is location awareness. Mobile users
take their devices with them everywhere, and adding location awareness to your app
offers users a more contextual experience. The location APIs available in Google Play
services facilitate adding location awareness to your app with automated location
tracking, wrong-side-of-the-street detection, geofencing, and activity recognition
Android location APIs make it easy for you to build location-aware applications,
without needing to focus on the details of the underlying location technology.
Location data are information about the geographic positions of devices (such as
smartphones or tablets) or structures (such as buildings, attractions).
The geographic positions of location data are called coordinates, and they are
commonly expressed in Latitude and Longitude format.
Additional attributes such as elevation or altitude may be included and helps data users
get more accurate picture of the geographic positions of their data.

Latitude Longitude

People commonly mean GPS data when they talk about location data. In reality, there are
various types of location data.
It is important to know how the data is collected as it determines the accuracy and depth of
the collected data, this have direct implications on the suitability and usability of the data for a
business.

54
6.2. LOCATION DATA KNOWLEDGE BASE

6.2.1. Global Positioning System (GPS)

A GPS provides latitude-longitude coordinates gathered by the hardware on a device


which communicates with a satellite such as a car navigating system, a mobile phone
or a fitness tracker.
The latitude/longitude coordinates generated by the GPS are considered the standard
for location data. Your device receives signals from the satellites and it can calculate
where it is by measuring the time it takes for the signal to arrive. This produces very
accurate and precise data under the right conditions. The quality of a GPS signal
degrades significantly indoors or in locations that obstruct the view of multiple GPS
satellites.

6.2.2. Cell Tower Location:

Google has been caught collecting location data on every Android device owner since
the beginning of this year (that's for the past 11 months)—even when location services
are entirely disabled, according to an investigation conducted by Quartz.
This location-sharing practice doesn't want your Android smartphone to use any app,
or turn on location services, or even have a SIM card inserted. All it wants is to have
your Android device to be connected to the Internet.
The investigation revealed that Android smartphones have been collecting the
addresses of nearby cellular towers, and this data could be used for "Cell Tower
Triangulation"—a technique widely used to identify the location of a phone/device
using data from three or more nearby cell towers.
Each time your Android device comes within the range of a new cell tower, it gathers
the cell tower address and sends this data back to Google when the device is connected
to a WiFi network or has a cellular data enabled. Since the component responsible for
collecting location data resides in Android's core Firebase Cloud Messaging service
that manages push notifications and messages on the operating system, it cannot be
disabled and doesn't rely on what apps you have installed—even if you factory reset
your smartphone or remove the SIM card.
Although the company said that it never used or stored this location data it collected
on its users and that it is now taking steps to end this practice, this data could be used
to target location-based advertisement when the user enters any store or restaurant.

55
6.2.3. Wi-Fi Location:

Wi-Fi location tracking, also known as Wi-Fi Positioning System (WPS), takes the
concept of Global Positioning System further. Instead of relying on satellites, it uses
Wi-Fi routers and smart devices (Wi-Fi access points) to pinpoint a phone, tablet, or
laptop more accurately than a GPS does. If that sounds both fascinating and scary,
that’s because it is.
Wi-Fi location tracking is a geolocation system that uses the entire Wi-Fi
infrastructure (phones, tablets, laptops, and routers) as Wi-Fi access points to
determine a device’s location.
Even when you’re not connected to a router, your device is still sending and receiving
data in order to discover nearby routers, so the devices are still in constant
communication as long as you have Wi-Fi enabled.
Wi-Fi location tracking is a good system for geolocation whenever the Global
Positioning System can’t get the job done. For example, GPS can’t always locate your
device when you’re indoors, as the signal coming from GPS satellites is weak or easily
blocked. In these instances, Wi-Fi location tracking can take the reins and pinpoint
your accurate location.

6.3. FUSED LOCATION API

Apps can take advantage of the signals provided by multiple sensors in the device to
determine device location. However, choosing the right combination of signals for a specific
task in different conditions is not simple. Finding a solution that is also battery-efficient is
even more complicated.
The fused location provider is a location API in Google Play services that intelligently
combines different signals to provide the location information that your app needs.
The fused location provider manages the underlying location technologies, such as GPS and
Wi-Fi, and provides a simple API that you can use to specify the required quality of service.
For example, you can request the most accurate data available, or the best accuracy possible
with no additional power consumption.

6.3.1. Support for common location scenarios


Using the fused location provider API, your app can request the last known
location of the user's device. Getting the last known location is usually a good
starting point for apps that require location information.
In your activity's onCreate() method, create an instance of the Fused Location Pro

CODE:

56
private FusedLocationProviderClient fusedLocationClient;

// ..

@Override
protected void onCreate (Bundle savedInstanceState) {
// ...

fusedLocationClient =
LocationServices.getFusedLocationProviderClient(this);
}

6.3.1.1. Choose the best location estimate


The FusedLocationProviderClient provides several methods to retrieve device location
information. Choose from one of the following, depending on your app's use case:

• getLastLocation() gets a location estimate more quickly and minimizes battery usage that
can be attributed to your app. However, the location information might be out of date, if no
other clients have actively used location recently.

• getCurrentLocation() gets a fresher, more accurate location more consistently. However,


this method can cause active location computation to occur on the device
This is the recommended way to get a fresh location, whenever possible, and is safer than
alternatives like starting and managing location updates yourself using requestLocationUpdates().
If your app calls requestLocationUpdates(), your app can sometimes consume large amounts of
power if location isn't available, or if the request isn't stopped correctly after obtaining a fresh
location.

CODE:
fusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
// Logic to handle location object
}
}
});

57
6.4 DEPENDENCY REQUIRED
Latest google play services to add in gradle scripts in the second build gradle

Done by:
implementation” ” and then sync.

Dependency for Fused Location Provider for Android (includes activity recognition and
geofencing):

‘com.google.android.gms:play-services-location:21.0.1’

6.5 LocationRequest

An encapsulation of various parameters for requesting location


through FusedLocationProviderClient.
There are a variety of different situations where various types of applications may want to use
different request parameters. For example, applications that are showing the user's location in
realtime may consider a PRIORITY_HIGH_ACCURACY request with a short interval. At
the other extreme, an application that want a negligible power impact while still receiving
opportunistic locations could create PRIORITY_NO_POWER request. With this request the
application will not trigger any location updates, but can still receive locations updates
triggered by other application's location requests. In between these use cases an application
can consider a PRIORITY_BALANCED_POWER_ACCURACY request with a reasonable
interval and fastest interval. See the documentation around the various parameters of
LocationRequest for more information.
Applications should strongly consider using setFastestInterval(long) to limit the fastest rate at
which their location callbacks can be invoked (and thus limit the amount of power used and
that they may be blamed for).

CODE:
protected void createLocationRequest() {
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(5000);
58
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}

6.6 Permissions Required

To protect user privacy, apps that use location services must request location
permissions.When you request location permissions, follow the same best practices as you
would for any other runtime permission. One important difference when it comes to location
permissions is that the system includes multiple permissions related to location. Which
permissions you request, and how you request them, depend on the location requirements for
your app's use case.

Types of location access


Each permission has a combination of the following characteristics:
Category: Either foreground location or background location.
Accuracy: Either precise location or approximate location.

CODE:

locationPermissionRequest.launch(new String[] {
Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE
_LOCATION
});
In the manifest file we need to add the user request permission by

CODE;
<manifest ... >
<!-- Always include this permission -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

<!-- Include only if your app benefits from precise location access. -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
</manifest>

6.7 Make a Location Request

59
Once a location request is in place you can start the regular updates
bycalling requestLocationUpdates().

Depending on the form of the request, the fused location provider either invokes
the LocationCallback.onLocationResult() callback method. The accuracy and frequency of
the updates are affected by the location permissions you've requested and the options you set
in the location request object. The fused location provider invokes
the LocationCallback.onLocationResult() callback method. The incoming argument
contains a list Location object containing the location's latitude and longitude. The following
snippet shows how to implement the LocationCallback interface and define the method, then
get the timestamp of the location update and display the latitude, longitude and timestamp on
your app's user interface:

CODE:
private LocationCallback locationCallback;

// ...

@Override
protected void onCreate(Bundle savedInstanceState) {
// ...

locationCallback = new LocationCallback() {


@Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
for (Location location : locationResult.getLocations()) {
// Update UI with location data
// ...
}
}
};
}

6.8 GEOLOCATION ACCESS

Geocoding is the process of converting addresses (like "1600 Amphitheatre Parkway,


Mountain View, CA") into geographic coordinates (like latitude 37.423021 and longitude -
122.083739), which you can use to place markers on a map, or position the map.

60
Reverse geocoding is the process of converting geographic coordinates into a human-
readable address. You can also use the Geocoding API to find the address for a given place
ID.
The Geocoding API provides a direct way to access these services via an HTTP request. The
following example uses the Geocoding service through the Maps JavaScript API to
demonstrate the basic functionality. The Geocoder class requires a backend service that is not
included in the core android framework. The Geocoder query methods will return an empty
list if there no backend service in the platform. Use the isPresent() method to determine
whether a Geocoder implementation exists.

• Public methods:
• getFromLocation: Returns an array of Addresses that attempt to describe the area
immediately surrounding the given latitude and longitude. The returned addresses
should be localized for the locale provided to this class's constructor.

CODE:
public List<Address> getFromLocation (double latitude, double longitude,
int maxResults)

CODE:
public void getFromLocation (double latitude, double longitude, int maxResults,
Geocoder.GeocodeListener listener)

Warning: Geocoding services may provide no guarantees on availability or accuracy. Results


are a best guess, and are not guaranteed to be meaningful or correct. Do NOT use this API for
any safety-critical or regulatory compliance purposes.
• isPresent:

Returns true if there is a geocoder implementation present that may return results. If true,
there is still no guarantee that any individual geocoding attempt will succeed.

CODE:
public static boolean isPresent ()

6.9 Result:

61
Fig 4.5.1 Address found with help of geocoder

62
7. DATABASE AND AUTHENTICATION

A database is information that is set up for easy access, management and updating. Computer
databases typically store aggregations of data records or files that contain information, such as
sales transactions, customer data, financials and product information. Databases are used for
storing, maintaining and accessing any sort of data. They collect information on people,
places or things. That information is gathered in one place so that it can be observed and
analyzed. Databases can be thought of as an organized collection of information.
Authentication is the verification of a user’s identity through the use of a mobile device and
one or more authentication methods to ensure secure access. If you want to keep your online
accounts safe, enabling mobile authentication across your devices is the single most important
step you can take. While no security measure is fully hack proof, there are steps to lock access
to your important accounts and information.
As more and more companies and private users see an increase in security breaches due to
hackers and other bad actors, the need for mobile authentication is greater than ever. If you
don’t properly authenticate your devices, sensitive information could potentially fall into the
hands of hackers. The threat of malware and tying a specific user to a device is paramount, so
getting user authentication right is essential. Imagine logging into your bank account to see a
zero balance or sensitive information wiped out from your computer and encrypted by a
ransomware attack.
In the context of databases, however, authentication acquires one more dimension because it
may happen at different levels. It may be performed by the database itself, or the setup may be
changed to allow either the operating system, or some other external method, to authenticate
users. For example, while creating a database in Microsoft’s SQL Server, a user is required to
define whether to use database authentication, operating system authentication, or both (the
so-called mixed-mode authentication). Other databases in which security is paramount
employ near-foolproof authentication modes like fingerprint recognition and retinal scans.

7.1. Introduction
The application project uses firebase API for its user authentication process and database.
Using Firebase, the users can be authenticated by email and password, Google, Facebook,
Twitter, phone number, etc. While the real- time database feature of the firebase framework
rules out the necessity for an app to have its own database. The cloud-based database can be
leveraged for managing the app’s data and providing swift data outcomes.

63
7.2 Firebase API

Firebase is a powerful platform for your mobile and web application. Firebase can power
your app’s backend, including data storage, user authentication, static hosting, and more. With
Firebase, you can easily build mobile and web apps that scale from one user to one million.It
is an API that lets developers easily sync and store data in realtime. Developers can use the
service to build their apps without having to manage servers or write server-side code. There
are clients for Android, iOS and JavaScript (including bindings for Ember, React, Angular
and Backbone). The API allows users to access the functionality of Firebase
programmatically. The API supports standard CRUD operations on the data within the
databases as well as querying of the data. Firebase uses WebSockets to achive realtime
communication between clients. Data can also be accessed over the Firebase REST API.
Firebase Simple Login is an additional service that allows developers to authenticate users
using only client-side code. Enable authentication via a number of third-party providers,
anonymous login, or email / password authentication without having to manually store
authentication credentials or run a server. Firebase Hosting gives developers a fast, secure and
reliable way to host their app's static assets such as HTML, CSS, JavaScript, and media files.
It is backed by a global CDN, serves content over SSL by default, and is available either a
custom domain or on a subdomain of firebaseapp.com.
• real – time database
Building a properly structured database requires quite a bit of forethought. Most
importantly, you need to plan for how data is going to be saved and later
retrieved to make that process as easy as possible.
All Firebase Realtime Database data is stored as JSON objects. You can think of the
database as a cloud-hosted JSON tree. Unlike a SQL database, there are no
tables or records. When you add data to the JSON tree, it becomes a node in the
existing JSON structure with an associated key. You can provide your own keys, such
as user IDs or semantic names, or they can be provided for you using push().
For example, consider a chat application that allows users to store a basic profile and
contact list. A typical user profile is located at a path, such as /users/$uid. The user
alovelace might have a database entry that looks something like this:
{
"users": {
"alovelace": {
"name": "Ada Lovelace",
"contacts": { "ghopper": true },
},
"ghopper": { ... },
"eclarke": { ... }
}}

64
Although the database uses a JSON tree, data stored in the database can be represented
as certain native types that correspond to available JSON types to help you write more
maintainable code. Firebase data is written to a Firebase Database reference and
retrieved by attaching an asynchronous listener to the reference. The listener is
triggered once for the initial state of the data and again anytime the data changes.
• Dependencies
dependencies {

// Import the BoM for the Firebase platform

implementation platform('com.google.firebase:firebase-bom:31.1.1')

// Add the dependency for the Realtime Database library

// When using the BoM, you don't specify versions in Firebase


librarydependencies

implementation 'com.google.firebase:firebase-database'

• Get a DatabaseReference

To read or write data from the database, you need an instance of


DatabaseReference:
private DatabaseReference mDatabase;
// ...
mDatabase = FirebaseDatabase.getInstance().getReference();

• Write data

For basic write operations, you can use setValue() to save data to a
specified reference, replacing any existing data at that path. You can
use this method to:
• Pass types that correspond to the available JSON types as follows:
o String
o Long
o Double
o Boolean
o Map<String, Object>
o List<Object>
65
• Pass a custom Java object, if the class that defines it has a default
constructor that takes no arguments and has public getters for the
properties to be assigned.
// Write a message to the database
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef =
database.getReference("message");

myRef.setValue("Hello, World!");
If you use a Java object, the contents of your object are automatically
mapped to child locations in a nested fashion. Using a Java object also
typically makes your code more readable and easier to maintain.
7.3 Cloud storage
Cloud Storage for Firebase is built for app developers who need to store and serve
user-generated content, such as photos or videos.
Cloud Storage for Firebase is a powerful, simple, and cost-effective object storage
service built for Google scale. The Firebase SDKs for Cloud Storage add Google
security to file uploads and downloads for your Firebase apps, regardless of network
quality.
You can use our SDKs to store images, audio, video, or other user-generated content.
On the server, you can use Google Cloud Storage APIs to access the same files.
Developers use the Firebase SDKs for Cloud Storage to upload and download files
directly from clients. If the network connection is poor, the client is able to retry the
operation right where it left off, saving your users time and bandwidth.
Cloud Storage for Firebase stores your files in a Google Cloud Storage bucket,
making them accessible through both Firebase and Google Cloud. This allows you the
flexibility to upload and download files from mobile clients via the Firebase SDKs for
Cloud Storage. In addition, you can do server-side processing such as image filtering
or video transcoding using the Google Cloud Storage APIs. Cloud Storage scales
automatically, meaning that there's no need to migrate to any other provider. Learn
more about all the benefits of our integration with Google Cloud.
The Firebase SDKs for Cloud Storage integrate seamlessly with Firebase
Authentication to identify users, and we provide a declarative security language that
lets you set access controls on individual files or groups of files, so you can make files
as public or private as you want.

Looking to store other types of data?


• Cloud Firestore is a flexible, scalable database for mobile, web, and
server development from Firebase and Google Cloud.

66
• The Firebase Realtime Database stores JSON application data, like
game state or chat messages, and synchronizes changes instantly
across all connected devices. To learn more about the differences
between database options, see Choose a database: Cloud Firestore
or Realtime Database.
• Firebase Remote Config stores developer-specified key-value pairs
to change the behavior and appearance of your app without
requiring users to download an update.
• Firebase Hosting hosts the HTML, CSS, and JavaScript for your
website as well as other developer-provided assets like graphics,
fonts, and icons.
▪ Dependencies

dependencies {

// Import the BoM for the Firebase platform

implementation platform('com.google.firebase:firebase-bom:31.1.1')

// Add the dependency for the Cloud Storage library

// When using the BoM, you don't specify versions in Firebase

library dependencies

implementation 'com.google.firebase:firebase-storage'

▪ Set up cloud storage


FirebaseStorage storage = FirebaseStorage.getInstance();
• If you want to use a Cloud Storage bucket other than the default
provided above, or use multiple Cloud Storage buckets in a
single app, you can create an instance of FirebaseStorage that
references your custom bucket:
// Get a non-default Storage bucket
FirebaseStorage storage =
FirebaseStorage.getInstance("gs://my-
custom-bucket");
• If you're building a more complicated app using a custom
FirebaseApp, you can create an instance of FirebaseStorage
initialized with that app:
// Get the default bucket from a custom FirebaseApp
67
FirebaseStorage storage =

FirebaseStorage.getInstance(customApp);

// Get a non-default bucket


FirebaseAppFirebaseStorage customStorage =

68
FirebaseStorage.getInstance(customApp,
"gs://my-
custom-bucket");

7.4 Authentication

Most apps need to know the identity of a user. Knowing a user's identity allows an app to
securely save user data in the cloud and provide the same personalized experience across all
of the user's devices. Firebase Authentication provides backend services, easy-to-use SDKs,
and ready-made UI libraries to authenticate users to your app. It supports authentication using
passwords, phone numbers, popular federated identity providers like Google, Facebook and
Twitter, and more. It integrates tightly with other Firebase services, and it leverages industry
standards like OAuth 2.0 and OpenID Connect, so it can be easily integrated with your
custom backend.
When you upgrade to Firebase Authentication with Identity Platform, you unlock additional
features, such as multi-factor authentication, blocking functions, user activity and audit
logging, SAML and generic OpenID Connect support, multi-tenancy, and enterprise-level
support.

I want to build my authentication system with Firebase


If you're building a new app or adding sign-in to an existing app, Firebase has libraries and
services that can help you implement secure authentication without having to build the
authentication backend yourself. Firebase Authentication is a complete backend solution for
signing in with passwords, federated identity providers, email links, and text messages.

I want a drop-in solution that's easy to use


The fastest and easiest way to add authentication to an app is to use FirebaseUI Auth, a drop-
in UI library. FirebaseUI implements complete user flows for all of Firebase Authentication's
supported sign-in methods.
Because FirebaseUI Auth is a drop-in solution, it has a specific UX that might not meet your
needs. If you want to change the UX, you can fork the library, which is open source, and use
your own version. However, for substantially different sign-in flows, you might prefer to
implement your own flows with the Firebase SDK as discussed in the next section.
▪ Dependencies and resources

69
dependencies {
// ...

implementation 'com.firebaseui:firebase-ui-auth:7.2.0'

// Required only if Facebook login support is required


// Find the latest Facebook SDK releases here: https://goo.gl/Ce5L94
implementation 'com.facebook.android:facebook-android-sdk:8.x'
}
If you support sign-in with Facebook or Twitter, add string resources
to strings.xml that specify the identifying information required by each
provider:

<resources>
<!-- Facebook application ID and custom URL scheme (app ID
prefixed by ' fb'). -->
<string name="facebook_application_id"
translatable="false">YOUR_APP_ID</string>
<string name="facebook_login_protocol_scheme"
translatable="false">fbYOUR_APP_ID</string>
</resources>
▪ Setup cloud storage
• Sign in
1. Create an ActivityResultLauncher which registers a callback for
the FirebaseUI Activity result contract:
// See: https://developer.android.com/training/basics/intents/result
private final ActivityResultLauncher<Intent> signInLauncher =
registerForActivityResult(
new FirebaseAuthUIActivityResultContract(),
new
ActivityResultCallback<FirebaseAuthUIAuthenticationResult>() {
@Override
public void
onActivityResult(FirebaseAuthUIAuthenticationResult result)
{
onSignInResult(result);
}
}
);

70
2. To kick off the FirebaseUI sign in flow, create a sign in intent with your
preferred sign-in methods:
// Choose authentication providers
List<AuthUI.IdpConfig> providers = Arrays.asList(
new AuthUI.IdpConfig.EmailBuilder().build(),
new AuthUI.IdpConfig.PhoneBuilder().build(),
new AuthUI.IdpConfig.GoogleBuilder().build(),
new AuthUI.IdpConfig.FacebookBuilder().build(),
new AuthUI.IdpConfig.TwitterBuilder().build());

// Create and launch sign-in intent


Intent signInIntent = AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(providers)
.build();
signInLauncher.launch(signInIntent);
3. When the sign-in flow is complete, you will receive the result in
onSignInResult:
private void onSignInResult(FirebaseAuthUIAuthenticationResult
result) {
IdpResponse response = result.getIdpResponse();
if (result.getResultCode() == RESULT_OK) {
// Successfully signed in
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
// ...
} else {
// Sign in failed. If response is null the user canceled the
// sign-in flow using the back button. Otherwise check
// response.getError().getErrorCode() and handle the error.
// ...
}
}

4. Set up sign-in methods

i. In the Firebase console, open the Authentication section. On


the Sign in method tab, enable the Email/Password provider.
Note that email/password sign-in must be enabled to use email
link sign-in.
ii. In the same section, enable Email link (passwordless sign-in)
sign-in method and click Save.

71
iii. You will also have to enable Firebase Dynamic Links to use
email-link sign in. In the Firebase console, click on Dynamic
Links under Engage in the navigation bar. Click on Getting
started and add a domain. The domain you choose here will be
reflected in the email links sent to your users.
iv. You can enable email link sign in in FirebaseUI by calling the
enableEmailLinkSignIn on an EmailBuilder instance. You will
also need to provide a valid ActionCodeSettings object with
setHandleCodeInApp set to true. Additionally, you need to
whitelist the URL you pass to setUrl, which can be done in the
Firebase console, under Authentication -> Sign in Methods ->
Authorized domains.
v. ActionCodeSettings actionCodeSettings =
ActionCodeSettings.newBuilder()

.setAndroidPackageName(

/* yourPackageName= */ "...",

/* installIfNotAvailable= */ true,

/* minimumVersion= */ null)

.setHandleCodeInApp(true) // This must be set to true

.setUrl("https://google.com") // This URL needs to be whitelisted

.build();

List<AuthUI.IdpConfig> providers = Arrays.asList(


new AuthUI.IdpConfig.EmailBuilder()

.enableEmailLinkSignIn()

.setActionCodeSettings(actionCodeSettings)

.build()

);

Intent signInIntent = AuthUI.getInstance()

.createSignInIntentBuilder()

.setAvailableProviders(providers)

.build();
signInLauncher.launch(signInIntent)

72
vi. Once you catch the deep link, you will need to call verify that
we can handle it for you. If we can, you need to then pass it to
us via setEmailLink.

if (AuthUI.canHandleIntent(getIntent())) {
if (getIntent().getExtras() == null) {

return;

String link =
getIntent().getExtras().getString("email_link_sign_in");

if (link != null) {

Intent signInIntent = AuthUI.getInstance()

.createSignInIntentBuilder()

.setEmailLink(link)

.setAvailableProviders(providers)

.build();
signInLauncher.launch(signInIntent);

• Sign out

FirebaseUI provides convenience methods to sign out of Firebase


Authentication as well as all social identity providers:
AuthUI.getInstance()
.signOut(this)
.addOnCompleteListener(new OnCompleteListener<Void>()
{
public void onComplete(@NonNull Task<Void> task) {
// ...
}
});

• Customization
By default FirebaseUI uses AppCompat for theming, which means it will
naturally adopt the color scheme of your app. If you require further
customization you can pass a theme and a logo to the sign-in Intent builder:
73
Intent signInIntent = AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(providers)
.setLogo(R.drawable.my_great_logo) // Set logo drawable
.setTheme(R.style.MySuperAppTheme) // Set theme
.build();
signInLauncher.launch(signInIntent);

74
Fig. 7.4.1 Login page Fig 7.4.2 Storage

75
8. Output Screens

Fig. 8.1 Splash screen

Fig.8.2 Login page Fig.8.3 Home page

76
Fig.8.4 Doctor search Fig.8.5 Medical documents storage

77
Fig.8.6 Reminders Fig.8.7 Profile

78
9. Future Scope

The future scope of this project may include several functionalities which may bring user
ease as this is the for most thing asked as the moto of our application.

Our application involves following functionalities as the future scope:

• EMERGENCY CALLING:

We will be providing an emergency calling button in our application in the very home
page for the emergency requirements in the cases like accidents. In this emergency
calling system we will be connecting a small radar through GPS in local localities and
search the nearby hospitals.
When the person will click the Emergency calling button it will directly connect them
to the nearest hospital to the site of accident avoiding the traffic for line of calling
108.This will help in making a clear route for patients and help them save their life.

• USE OF BIG DATA:

Right now, as we are working on a free firebase provided database, we are limited
with what we can do with the database entries.

But in the future, we can expand the services of database as the needs will be
expanding with the increase in services.

• DATA LINKING WITH AADHAR:

We are thinking about linking the users Aadhaar with their account so that they can
feed their data into their account for the future references.

This will also provide ease for them and their doctors as they will not be required to
carry each and every documentation and reports everywhere they go.

They will be allowed to store and save all their medical history with them in their
account with their Aadhaar number itself in our application.

79
Conclusion

The mobile app comes in various forms and formats to meet the various needs of the
user. The healthcare segment is also surrounded by a wide range of apps. These
healthcare apps areapplication programs that offer health-related services ranging
from wellness to doctor consultations, health diet management for severe disease to
mental health peace. Similarly, the aim of our healthcare application h-care is to
provide the user the facility to bookappointments online, find health facilities near
them, store medical records for emergencies, provide them guidance through a
chatbot assistant and many more. The user can access them at any setting whether it
is at his home and on-the-go.
Apart from health solutions, at a larger scale, these health apps are creating a health
consciousness among the population. Combined with mHealth and electronic
medical records (EMR), the apps are capable of providing vital health states which
are easy to share and analyze. Encouragement to live a healthy lifestyle, easier
communication, improved patient monitoring, appointment scheduling, and
counseling are some other benefits of the healthcare apps. During the fight against
the Covid-19, these apps have played a key role in meeting various healthcare
demands, similarly, the growth is likely to continue post-covid-19 as well.
Overall, the health apps hold a huge potential to transform the medical ecosystem
thus providing better health outcomes for users. In the coming years, the demand
for healthcareapps is likely to increase with the advancement in features (like
attractive interface, eye- catching graphics, and icons and analytics option),
awareness among the user, rise in the smartphone user, and also the penetration
to the new geographies. Coupled with Artificial intelligence, the healthcare apps
will transform the healthcare dynamics significantly.
However, the lack of data security, policy issues regarding healthcare data and their
management, and the regulatory issue will be the major factor affecting the usage and will actas a
key barrier.

80
Reference
[1]. Ribeiro and A. R. D. Silva, “Survey on Cross-Platforms and Languages for Mobile Apps,”
Eighth International Conference on the Quality of Information and Communications Technology,
2012.

[2]. Pohares, V. C. Kulloli, T. Bhattacharyya, and S. Bhure, “Cross Platform Mobile Application
Development,” International Journal of Computer Trends and Technology, vol. 4, no. 5, pp. 1095–
1100 , 2013.

[3]. S. S. Jagtap and D. B. Hanchate, “Development of Android Based Mobile App for PrestaShop
eCommerce Shopping Cart (ALC) ,” International Research Journal of Engineering and
Technology (IRJET) , vol. 4, no. 7, pp. 2248–2254 , Jul. 2017.

[4]. M. Q. Huynh and P. Ghimire, “Browser App Approach: Can It Be an Answer to the Challenges
in CrossPlatform App Development?,” Journal of Information Technology Education: Innovations
in Practice, vol. 16, pp. 047–068, 2017.

[5]. N. Litayem, B. Dhupia, and S. Rubab, “Review of Cross-Platforms for Mobile Learning
Application Development,” International Journal of Advanced Computer Science and
Applications, vol. 6, no. 1, pp. 31–39, 2015.

[6]. A. Kathuria and A. Gupta, “Challenges in Android Application Development: A Case Study”
International Journal of Computer Science and Mobile Computing, vol. 4, no. 5, pp. 294–299, May
2015.

[7]. L. Ma, L. Gu, and J. Wang, “Research and Development of Mobile Application for Android
Platform,” International Journal of Multimedia and Ubiquitous Engineering, vol. 9, pp. 187–198,
2014.

81

You might also like