0% found this document useful (0 votes)
37 views77 pages

Iv Sem - Ai23431 - Web Development and Mobile App

The document is a laboratory manual for the Web Development and Mobile Application Lab course at Rajalakshmi Engineering College, detailing the vision, mission, educational objectives, and outcomes of the Artificial Intelligence and Machine Learning program. It includes a syllabus with specific units covering PHP, JavaScript, Servlets, and Android application development, along with a list of experiments and course outcomes. The manual aims to equip students with practical skills in web and mobile application development, emphasizing ethical practices and innovative problem-solving.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views77 pages

Iv Sem - Ai23431 - Web Development and Mobile App

The document is a laboratory manual for the Web Development and Mobile Application Lab course at Rajalakshmi Engineering College, detailing the vision, mission, educational objectives, and outcomes of the Artificial Intelligence and Machine Learning program. It includes a syllabus with specific units covering PHP, JavaScript, Servlets, and Android application development, along with a list of experiments and course outcomes. The manual aims to equip students with practical skills in web and mobile application development, emphasizing ethical practices and innovative problem-solving.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

RAJALAKSHMI ENGINEERING COLLEGE

DEPARTMENT OF ARTIFICIAL INTILLEGENCE AND


MACHINE LEARNING

AI23431 - WEB DEVELOPMENT AND MOBILE


APPLICATION LAB

[Regulation 2023]
II Year – IV Semester
LABORATORY MANUAL

RAJALAKSHMI ENGINEERING COLLEGE

VISION & MISSION


OF
RAJALAKSHMI ENGINEERING COLLEGE
Vision

To be an institution of excellence in Engineering, Technology and Management Education &


Research. To provide competent and ethical professionals with a concern for society.

Mission

To impart quality technical education imbibed with proficiency and humane values. To provide
right ambience and opportunities for the students to develop into creative, talented and globally
competent professionals. To promote research and development in technology and management for the
benefit of the society.

Artificial Intelligence and Machine Learning / AI23431 / 1


RAJALAKSHMI ENGINEERING COLLEGE

B.Tech ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING

VISION :

 To promote highly Ethical and Innovative Computer Professionals through excellence


in teaching, training and research.

MISSION :

 To produce globally competent professionals, motivated to learn the emerging technologies


and to be innovative in solving real world problems.
 To promote research activities amongst the students and the members of faculty that
could benefit the society.
 To impart moral and ethical values in their profession.

PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)

PEO 1: To equip students with essential background in computer science, basic electronics and
applied mathematics.
PEO 2: To prepare students with fundamental knowledge in programming languages, and tools and
enable them to develop applications.
PEO 3: To encourage the research abilities and innovative project development in the field of AI, ML,
DL, networking, security, web development, Data Science and also emerging technologies for the
cause of social benefit.

Artificial Intelligence and Machine Learning / AI23431 / 2


PEO 4: To develop professionally ethical individuals enhanced with analytical skills, communication
skills and organizing ability to meet industry requirements.

PROGRAMME OUTCOMES (POs)


PO1: Engineering knowledge: Apply the knowledge of Mathematics, Science, Engineering
fundamentals, and
an engineering specialization to the solution of complex engineering problems.
PO2: Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences,
and engineering sciences.
PO3: Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate consideration
for the public health and safety, and the cultural, societal, and environmental considerations.
PO4: Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
PO5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with an
understanding of the limitations.
PO6: The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
PO7: Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development.
PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
PO9: Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.

Artificial Intelligence and Machine Learning / AI23431 / 3


PO10: Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive clear
instructions.
PO11: Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and leader in
a team, to manage projects and in multidisciplinary environments.
PO12: Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.

PROGRAM SPECIFIC OUTCOMES (PSOs)


A graduate of the Artificial Intelligence and Machine Learning Program will demonstrate

PSO 1: Foundation Skills: Ability to understand, analyze and develop computer programs in the
areas related to algorithms, system software, web design, AI, machine learning, deep learning, data
science, and networking for efficient design of computer-based systems of varying complexity.
Familiarity and practical competence with a broad range of programming language, tools and open
source platforms.

PSO 2: Problem Solving Skills: Ability to apply mathematical methodologies to solve computational
task, model real world problem using appropriate AI and ML algorithms. To understand the standard
practices and strategies in project development, using open-ended programming environments to
deliver a quality product.

PSO 3: Successful Progression: Ability to apply knowledge in various domains to identify research
gaps and to provide solution to new ideas, inculcate passion towards higher studies, creating
innovative career paths to be an entrepreneur and evolve as an ethically social responsible AI and ML
professional.

Artificial Intelligence and Machine Learning / AI23431 / 4


SYLLABUS

Subject Subject Name(Lab oriented Theory Courses) Category L T P C


Code
AI23431 WEB TECHNOLOGY AND MOBILE APPLICATION PC 1 0 4 5

Objectives:
 To teach students the basics of server side scripting using PHP
 To explain web application development procedures
 To impart servlet technology for writing business logic
 To facilitate students to connect to databases using JDBC
 To familiarize various concepts of application development using JSP
 To facilitate students to understand android SDK
 To help students to gain a basic understanding of Android application development

UNIT-I INTRODUCTION TO PHP 9


Declaring variables, data types, arrays, strings, operations, expressions, control structures,
functions, Reading data from web form controls like Text Boxes, radio buttons, lists etc., Handling
File Uploads, Connecting to database (My SQL as reference), executing simple queries, handling
results, Handling sessions and cookies. File Handling in PHP: File operations like opening,
closing, reading, writing, appending, deleting etc. on text and binary files, listing directories.
UNIT-II CLIENT SIDE SCRIPTING 9
Introduction to JavaScript: JavaScript language – declaring variables, scope of variables functions,
event handlers (on click, on submit etc.), Document Object Model, Form validations. Simple
AJAX applications. XML: Introduction to XML, Defining XML tags, their attributes and values,
Document type definition, XML Schemas, Document Object model, XHTML Parsing XML Data -
DOM and SAX parsers in java.
UNIT-III INTRODUCTION TO SERVLETS 9
Common Gateway Interface (CGI), Lifecycle of a Servlets, deploying a Servlets, The Servlets API,
Reading Servlets parameters, Reading initialization parameters, Handling Http Request &
Responses, Using Cookies and sessions, connecting to a database using JDBC. Introduction to JSP:
The Anatomy of a JSP Page, JSP Processing, Declarations, Directives, Expressions, Code
Snippets, implicit objects, Using Beans in JSP Pages, Using Cookies and session tracking,
connecting to database in JSP.
UNIT-IV MOBILE APPLICATION DEVELOPMENT 10
Introduction to Android-The Android Platform, Android SDK, Eclipse Installation, Android
Installation, Building you First Android application, Understanding Anatomy of Android
Application, Android Manifest file. Android Application Design Essentials: Anatomy of an
Android applications, Android terminologies, Application Context, Activities, Services, Intents,
Receiving and Broadcasting Intents, Android Manifest File and its common settings, Using Intent
Filter, Permissions.
UNIT-V ANDROID USER INTERFACE DESIGN 8
User Interface Screen elements, Designing User Interfaces with Layouts, Drawing and Working
with Animation. Testing Android applications, Publishing Android application, Using Android

Artificial Intelligence and Machine Learning / AI23431 / 5


preferences, Managing Application resources in a hierarchy, working with different types of
resources. Using Android Data and Storage APIs, Managing data using Sqlite, Sharing Data
between Applications with Content Providers,
Contact Hours : 45

Contact hours : 30
Total Contact hours : 75

Artificial Intelligence and Machine Learning / AI23431 / 6


List of Experiments
1 Develop and demonstrate PHP Script for the following problems:
a) Write a PHP Script to find out the Sum of the Individual Digits.
b) Write a PHP Script to check whether the given number is Palindrome or not
2 Write JavaScript to validate the following fields of the Registration page.
a) First Name (Name should contains alphabets and the
length should not be less than 6 characters).
b) Password (Password should not be less than 6 characters length).
c) E-mail id (should not contain any invalid and must follow the
standard pattern [email protected])
d) Mobile Number (Phone number should contain 10 digits only).
e) Last Name and Address (should not be Empty).
3 Write an XML for person information and access the data using XSL.

4 Implement the web applications with Database using


(a) PHP, (b) Servlets and (c) JSP
5 Write a program to design a simple calculator using (a) JavaScript (b)
PHP (c) Servlet and (d) JSP.
6 Write a servlet for session tracking

7 Installation of Android studio

8 Develop an Android application using controls like Button, TextView, EditText for
designing a calculator having basic functionality like Addition, Subtraction, multiplication,
and Division
9 Implement an application that writes data to the SD card.

10 Program for building a simple user interface using a XML for UI layout.

11 Develop a mobile application to send an email

12 Create an android application to share the data between multiple applications by using
Content Provider
Hardware Intel i3, CPU @ 1.20GHz 1.19 GHz, 4 GB RAM,
32 Bit Operating System
Software PHP ADMIN(XAMPP/WAMPP) NET BEANS, APACHE, JAVA
LATEST VERSION
Operating System WINDOWS10,11

Artificial Intelligence and Machine Learning / AI23431 / 7


AI23431- WEB TECHNOLOGY AND MOBILE APPLICATION

Required
Exercise
Exercise Name Hours
no.

Develop and demonstrate PHP Script for the following problems:


a) Write a PHP Script to find out the Sum of the Individual
1 Digits. 3
b) Write a PHP Script to check whether the given number is
Palindrome or not
Write JavaScript to validate the following fields of the Registration
page.
a) First Name (Name should contains alphabets and the length
should not be less than 6 characters).
2 b) Password (Password should not be less than 6 characters 3
length).
c) E-mail id (should not contain any invalid and must follow the
standard pattern [email protected])
d) Mobile Number (Phone number should contain 10 digits only).
e) Last Name and Address (should not be Empty).
3 Write an XML for person information and access the data using 2
XSL.
4 Implement the web applications with Database using 3
(a) PHP, (b) Servlets and (c) JSP
Write a program to design a simple calculator using (a) JavaScript
5 (b) 3
PHP (c) Servlet and (d) JSP.
6 Write a servlet for session tracking 2
7 Installation of Android studio 3
Develop an Android application using controls like Button,
8 TextView, EditText for designing a calculator having basic 3
functionality like Addition, Subtraction, multiplication, and
Division
9 Implement an application that writes data to the SD card. 2

10 Program for building a simple user interface using a XML for UI 2


layout.
11 Develop a mobile application to send an email 2

12 Create an android application to share the data between multiple 2


applications by using Content Provider

Course Outcomes (COs)

Artificial Intelligence and Machine Learning / AI23431 / 8


Course Name: Web Development Course Code: AI19441

Outcome 1 Create web pages using PHP

Outcome 2 Identify the difference between the HTML PHP and XML documents.

Outcome 3 Identify the engineering structural design of XML and parse tree

Outcome 4 Analyze the difference between and PHP and XML.

Outcome 5 Understand the concept of JAVA SCRIPTS.

Outcome 6 Identify the difference between the JSP and Servlet.


Outcome 7 Identify various concepts of mobile programming that make it unique
from programming for other platforms

CO-PO –PSO matrices of course


PO/PSO

PO PO PO PO PO PO PO PO PO PO PO PO PSO PSO PSO


1 2 3 4 5 6 7 8 9 10 11 12 1 2 3
CO
AI23431.1 3 2 2 2 2 - - - - - - 2 3 2 -
AI23431.2 3 2 2 2 2 - - - - - - 2 3 2 -
AI23431.3 3 2 2 2 2 - - - - - - 2 3 2 -
AI23431.4 3 2 2 2 2 - - - - - - 2 3 2 -
AI23431.5 3 2 2 2 2 - - - - - - 2 3 2 -
Average 3 2 2 2 2 - - - - - - 2 3 2 -

Note: Enter correlation levels 1,2or3 as defined below:

1:Slight(Low) 2: Moderate(Medium) 3:Substantial(High)If there is no correlation, put“-“

Artificial Intelligence and Machine Learning / AI23431 / 9


Ex No: 1

DEVELOP AND DEMONSTRATE PHP SCRIPT FOR


THE FOLLOWING PROBLEMS

a. write a php script to find out the sum of the individual digits

Aim: To write a PHP script that calculates the sum of the individual digits of a given
number.

Algorithm:

1. Start.
2. Read the input number.
3. Initialize a variable sum to 0.
4. Use a loop to extract each digit from the number:
o Get the last digit using modulus operator (%).
o Add the digit to sum.
o Remove the last digit by dividing the number by 10.
5. Continue the loop until all digits are processed.
6. Display the sum.
7. Stop.

PROGRAM:

php
Copy code
<?php
function sumOfDigits($number) {
$sum = 0;
while ($number > 0) {
$digit = $number % 10;
$sum += $digit;
$number = (int)($number / 10);
}

Artificial Intelligence and Machine Learning / AI23431 / 10


return $sum;
}

// Example usage
$number = 1234;
echo "Sum of digits of $number is: " . sumOfDigits($number);
?>

OUTPUT:

csharp
Copy code
Sum of digits of 1234 is: 10

RESULT: The PHP script successfully calculates the sum of individual digits of a given
number.

b) Write a PHP Script to check whether the given number is Palindrome or not

Aim: To write a PHP script to check whether a given number is a palindrome or not.

Algorithm:

1. Start.
2. Read the input number.
3. Convert the number to a string.
4. Reverse the string.
5. Compare the reversed string with the original string.
6. If both are equal, the number is a palindrome; otherwise, it is not.
7. Display the result.
8. Stop.

Program:

php
Copy code
<?php
function isPalindrome($number) {

Artificial Intelligence and Machine Learning / AI23431 / 11


$original = strval($number);
$reversed = strrev($original);
return $original === $reversed;
}

// Example usage
$number = 12321;
if (isPalindrome($number)) {
echo "$number is a palindrome.";
} else {
echo "$number is not a palindrome.";
}
?>

OUTPUT:

csharp
Copy code
12321 is a palindrome.

Result: The PHP script successfully checks whether a given number is a palindrome or
not.

Artificial Intelligence and Machine Learning / AI23431 / 12


Ex No: 2

JAVASCRIPT VALIDATION FOR REGISTRATION PAGE

Aim: To write JavaScript to validate the following fields of a registration page: First
Name, Password, Email ID, Mobile Number, Last Name, and Address.

Algorithm:

1. Start.
2. Define validation functions for each field:
o First Name: Check if it contains only alphabets and has a minimum length
of 6 characters.
o Password: Check if it has a minimum length of 6 characters.
o Email ID: Check if it follows the standard pattern.
o Mobile Number: Check if it contains exactly 10 digits.
o Last Name and Address: Check if they are not empty.
3. Attach these validation functions to the form's onsubmit event.
4. If all validations pass, allow form submission; otherwise, show appropriate error
messages.
5. Stop.

PROGRAM:

html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>Registration Form</title>
<script>
function validateForm() {
let firstName = document.forms["regForm"]["firstName"].value;

Artificial Intelligence and Machine Learning / AI23431 / 13


let password = document.forms["regForm"]["password"].value;
let email = document.forms["regForm"]["email"].value;
let mobile = document.forms["regForm"]["mobile"].value;
let lastName = document.forms["regForm"]["lastName"].value;
let address = document.forms["regForm"]["address"].value;

if (!/^[a-zA-Z]{6,}$/.test(firstName)) {
alert("First Name must contain only alphabets and be at least 6 characters
long.");

return false;
}
if (password.length < 6) {
alert("Password must be at least 6 characters long.");
return false;
}
if (!/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/.test(email)) {
alert("Invalid Email ID.");
return false;
}
if (!/^\d{10}$/.test(mobile)) {
alert("Mobile Number must contain exactly 10 digits.");
return false;
}
if (lastName == "" || address == "") {
alert("Last Name and Address must not be empty.");
return false;
}
return true;
}
</script>
</head>
<body>
<form name="regForm" onsubmit="return validateForm()">
First Name: <input type="text" name="firstName"><br>

Artificial Intelligence and Machine Learning / AI23431 / 14


Password: <input type="password" name="password"><br>
Email: <input type="text" name="email"><br>
Mobile: <input type="text" name="mobile"><br>
Last Name: <input type="text" name="lastName"><br>
Address: <input type="text" name="address"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Output:
When the form is filled out incorrectly, appropriate error messages are displayed. For
example:
vbnet
Copy code
Alert: "First Name must contain only alphabets and be at least 6 characters long."

Result: The JavaScript code successfully validates the registration form fields according
to the specified criteria.

Artificial Intelligence and Machine Learning / AI23431 / 15


Ex no: 3

Write an XML for person information and access the data using XSL.

Aim: To write an XML for person information and access the data using XSL.

Algorithm:

1. Start.
2. Create an XML document with person information (name, age, address, etc.).
3. Create an XSL stylesheet to transform and display the XML data.
4. Apply the XSL stylesheet to the XML document.
5. Display the transformed data.
6. Stop.

Program:

person.xml:

xml
Copy code
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person>
<name>John Doe</name>
<age>30</age>
<address>123 Main St</address>
</person>
<person>
<name>Jane Smith</name>
<age>25</age>
<address>456 Elm St</address>
</person>
</persons>

person.xsl:

xml

Artificial Intelligence and Machine Learning / AI23431 / 16


Copy code
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>Person Information</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Name</th>
<th>Age</th>
<th>Address</th>
</tr>
<xsl:for-each select="persons/person">
<tr>
<td><xsl:value-of select="name"/></td>
<td><xsl:value-of select="age"/></td>
<td><xsl:value-of select="address"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

Output: When the XML and XSL are processed, the output is an HTML table displaying
the person information.

Result: The XML document for person information is successfully transformed and
displayed using XSL.

Artificial Intelligence and Machine Learning / AI23431 / 17


Ex. No.: 4

IMPLEMENT THE WEB APPLICATIONS WITH DATABASE


USING

a) PHP with Database

Aim: To implement a web application using PHP that interacts with a database.

Algorithm:

1. Start.
2. Create a database and table using SQL.
3. Establish a connection to the database using PHP.
4. Write PHP scripts to perform CRUD (Create, Read, Update, Delete) operations.
5. Display the data from the database in a web page.
6. Stop.

Program:

Database Creation (SQL):

sql
Copy code
CREATE DATABASE webapp;
USE webapp;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100),
age INT
);

PHP Script:

db.php:

Artificial Intelligence and Machine Learning / AI23431 / 18


php
Copy code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "webapp";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>

index.php:

php
Copy code
<?php
include 'db.php';

$sql = "SELECT * FROM users";


$result = $conn->query($sql);
?>

<!DOCTYPE html>
<html>
<head>
<title>Web Application</title>
</head>
<body>
<h2>User List</h2>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>

Artificial Intelligence and Machine Learning / AI23431 / 19


<th>Email</th>
<th>Age</th>
</tr>
<?php
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>{$row['id']}</td>
<td>{$row['name']}</td>
<td>{$row['email']}</td>
<td>{$row['age']}</td>
</tr>";
}
} else {
echo "<tr><td colspan='4'>No users found</td></tr>";
}
$conn->close();
?>
</table>
</body>
</html>

Output:
An HTML table displaying user information from the database.

Result:
The web application using PHP and MySQL successfully interacts with the database to
display user information.

b) Servlets with Database

Aim: To implement a web application using Servlets that interacts with a database.

Algorithm:

1. Start.

Artificial Intelligence and Machine Learning / AI23431 / 20


2. Create a database and table using SQL.
3. Set up a Java Servlet project.
4. Write servlets to connect to the database and perform CRUD operations.
5. Display the data from the database in a web page.
6. Stop.

Program:

Database Creation (SQL):

sql
Copy code
CREATE DATABASE webapp;
USE webapp;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100),
age INT
);

Servlet Code:

DBConnection.java:

java
Copy code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnection {


public static Connection initializeDatabase() throws SQLException,
ClassNotFoundException {
String dbURL = "jdbc:mysql://localhost:3306/webapp";
String dbUsername = "root";
String dbPassword = "";

Artificial Intelligence and Machine Learning / AI23431 / 21


Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(dbURL, dbUsername,
dbPassword);
return con;
}
}

UserServlet.java:

java
Copy code
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out =
response.getWriter(); try {
Connection con = DBConnection.initializeDatabase();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");

Artificial Intelligence and Machine Learning / AI23431 / 22


out.println("<html><body><h2>User List</h2><table border='1'>");

out.println("<tr><th>ID</th><th>Name</th><th>Email</th><th>Age</th></tr>");
while (rs.next()) {
out.println("<tr><td>" + rs.getInt("id") + "</td><td>" + rs.getString("name") +
"</td><td>" + rs.getString("email") + "</td><td>" + rs.getInt("age") + "</td></tr>");
}
out.println("</table></body></html>");
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

OUTPUT:
An HTML table displaying user information from the database.

RESULT:
The web application using Servlets successfully interacts with the database to display user
information.

c) JSP with Database

Aim: To implement a web application using JSP that interacts with a database.

Algorithm:

1. Start.
2. Create a database and table using SQL.
3. Set up a JSP project.
4. Write JSP pages to connect to the database and perform CRUD operations.
5. Display the data from the database in a web page.
6. Stop.

Program:

Database Creation (SQL):

sql

Artificial Intelligence and Machine Learning / AI23431 / 23


Copy code
CREATE DATABASE webapp;
USE webapp;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100),
age INT
);

JSP Code:

db.jsp:

jsp
Copy code
<%@ page import="java.sql.*" %>
<%
String dbURL = "jdbc:mysql://localhost:3306/webapp";
String dbUsername = "root";
String dbPassword = "";
Connection conn = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(dbURL, dbUsername, dbPassword);
} catch (Exception e) {
e.printStackTrace();
}
%>

index.jsp:

jsp
Copy code
<%@ include file="db.jsp" %>
<%

Artificial Intelligence and Machine Learning / AI23431 / 24


Statement stmt = conn.createStatement();

Artificial Intelligence and Machine Learning / AI23431 / 25


ResultSet rs = stmt.executeQuery("SELECT * FROM users");
%>
<!DOCTYPE html>
<html>
<head>
<title>Web Application</title>
</head>
<body>
<h2>User List</h2>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Age</th>
</tr>
<%
while (rs.next()) {
out.println("<tr><td>" + rs.getInt("id") + "</td><td>" + rs.getString("name") +
"</td><td>" + rs.getString("email") + "</td><td>" + rs.getInt("age") + "</td></tr>");
}
conn.close();
%>
</table>
</body>
</html>

OUTPUT:

An HTML table displaying user information from the database.

RESULT:
The web application using JSP successfully interacts with the database to display user
information.

Artificial Intelligence and Machine Learning / AI23431 / 26


Ex. No.: 5

WRITE A PROGRAM TO DESIGN A SIMPLE CALCULATOR USING

a) JavaScript Calculator

Aim: To design a simple calculator using JavaScript.

Algorithm:

1. Start.
2. Create an HTML form for the calculator with input fields and buttons.
3. Write JavaScript functions to perform basic arithmetic operations (addition,
subtraction, multiplication, division).
4. Display the result in the input field.
5. Stop.

PROGRAM:

html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>Simple Calculator</title>
<script>
function calculate(val) {
document.getElementById("result").value += val;
}

function solve() {
let x = document.getElementById("result").value;
let y = eval(x);
document.getElementById("result").value = y;
}

Artificial Intelligence and Machine Learning / AI23431 / 27


function clearScreen() {
document.getElementById("result").value = "";
}
</script>
</head>
<body>
<form name="calc">
<input type="text" id="result">
<br>
<input type="button" value="1" onclick="calculate('1')">
<input type="button" value="2" onclick="calculate('2')">
<input type="button" value="3" onclick="calculate('3')">
<input type="button" value="+" onclick="calculate('+')">
<br>
<input type="button" value="4" onclick="calculate('4')">
<input type="button" value="5" onclick="calculate('5')">
<input type="button" value="6" onclick="calculate('6')">
<input type="button" value="-" onclick="calculate('-')">
<br>
<input type="button" value="7" onclick="calculate('7')">
<input type="button" value="8" onclick="calculate('8')">
<input type="button" value="9" onclick="calculate('9')">
<input type="button" value="*" onclick="calculate('*')">
<br>
<input type="button" value="C" onclick="clearScreen()">
<input type="button" value="0" onclick="calculate('0')">
<input type="button" value="=" onclick="solve()">
<input type="button" value="/" onclick="calculate('/')">
</form>
</body>
</html>

OUTPUT:

Artificial Intelligence and Machine Learning / AI23431 / 28


A web page with a simple calculator that performs basic arithmetic operations.

RESULT:
The JavaScript code successfully creates a simple calculator that performs addition,
subtraction, multiplication, and division.

b) PHP Calculator

AIM: To design a simple calculator using PHP.

ALGORITHM:

1. Start.
2. Create an HTML form for the calculator with input fields and buttons.
3. Write a PHP script to perform basic arithmetic operations based on the user input.
4. Display the result in the input field.
5. Stop.

PROGRAM:

php
Copy code
<!DOCTYPE html>
<html>
<head>
<title>Simple Calculator</title>
</head>
<body>
<form method="post">
<input type="text" name="num1">
<select name="operator">
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select>
<input type="text" name="num2">

Artificial Intelligence and Machine Learning / AI23431 / 29


<input type="submit" name="submit" value="Calculate">
</form>
<?php
if (isset($_POST['submit'])) {
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$operator = $_POST['operator'];
$result = 0;
switch ($operator) {
case '+':
$result = $num1 + $num2;
break;
case '-':
$result = $num1 - $num2;
break;
case '*':
$result = $num1 * $num2;
break;
case '/':
if ($num2 != 0) {
$result = $num1 / $num2;
} else {
echo "Division by zero is not allowed.";
}
break;
}
echo "Result: " . $result;
}
?>
</body>
</html>

OUTPUT:
A web page with a simple calculator that performs basic arithmetic operations.

Artificial Intelligence and Machine Learning / AI23431 / 30


RESULT:
The PHP script successfully creates a simple calculator that performs addition, subtraction,
multiplication, and division.

c) Servlet Calculator

AIM: To design a simple calculator using Servlets.

ALGORITHM:

1. Start.
2. Create an HTML form for the calculator with input fields and buttons.
3. Write a servlet to perform basic arithmetic operations based on the user input.
4. Display the result in the input field.
5. Stop.

PROGRAM:

CalculatorServlet.java:

java
Copy code
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/CalculatorServlet")
public class CalculatorServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {
response.setContentType("text/html"); PrintWriter out = response.getWriter(); try {

Artificial Intelligence and Machine Learning / AI23431 / 31


double num1 = Double.parseDouble(request.getParameter("num1"));
double num2 = Double.parseDouble(request.getParameter("num2"));
String operator = request.getParameter("operator");
double result = 0;

switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 != 0) {
result = num1 / num2;
} else {
out.println("Division by zero is not allowed.");
return;
}
break;
}
out.println("Result: " + result);
} catch (Exception e) {
e.printStackTrace();
}
}
}

index.html:

html
Copy code

Artificial Intelligence and Machine Learning / AI23431 / 32


<!DOCTYPE html>
<html>
<head>
<title>Simple Calculator</title>
</head>
<body>
<form action="CalculatorServlet" method="post">
<input type="text" name="num1">
<select name="operator">
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select>
<input type="text" name="num2">
<input type="submit" value="Calculate">
</form>
</body>
</html>

Output:

A web page with a simple calculator that performs basic arithmetic operations.

Result:

The servlet successfully creates a simple calculator that performs addition, subtraction,
multiplication, and division.

d) JSP Calculator

AIM: To design a simple calculator using JSP.

ALGORITHM:

1. Start.
2. Create an HTML form for the calculator with input fields and buttons.
3. Write JSP code to perform basic arithmetic operations based on the user input.

Artificial Intelligence and Machine Learning / AI23431 / 33


4. Display the result in the input field.
5. Stop.

Program:

index.jsp:

jsp
Copy code
<!DOCTYPE html>
<html>
<head>
<title>Simple Calculator</title>
</head>
<body>
<form method="post">
<input type="text" name="num1">
<select name="operator">
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select>
<input type="text" name="num2">
<input type="submit" value="Calculate">
</form>
<%
if (request.getParameter("num1") != null && request.getParameter("num2") != null)
{
double num1 = Double.parseDouble(request.getParameter("num1"));
double num2 = Double.parseDouble(request.getParameter("num2"));
String operator = request.getParameter("operator");
double result = 0;

switch (operator) {

Artificial Intelligence and Machine Learning / AI23431 / 34


case "+":

Artificial Intelligence and Machine Learning / AI23431 / 35


result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 != 0) {
result = num1 / num2;
} else {
out.println("Division by zero is not allowed.");
return;
}
break;
}
out.println("Result: " + result);
}
%>
</body>
</html>

OUTPUT:

A web page with a simple calculator that performs basic arithmetic operations.

RESULT:

The JSP code successfully creates a simple calculator that performs addition, subtraction,
multiplication, and division.

Artificial Intelligence and Machine Learning / AI23431 / 36


Ex no: 6

WRITE A SERVLET FOR SESSION TRACKING

Aim: To create an Android application that interacts with a SQLite database.

Algorithm:

1. Start.
2. Set up an Android project.
3. Create a SQLite database.
4. Write code to perform CRUD (Create, Read, Update, Delete) operations on the
database.
5. Implement a user interface to interact with the database.
6. Test the application on an Android device or emulator.
7. Stop.

Program:

MainActivity.java:
java
Copy code
package com.example.androiddatabase;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {

Artificial Intelligence and Machine Learning / AI23431 / 37


EditText name, age;
Button insert, read;
SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = findViewById(R.id.name);
age = findViewById(R.id.age);
insert = findViewById(R.id.insert);
read = findViewById(R.id.read);
db = openOrCreateDatabase("UserDB", MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS users(name VARCHAR, age
INT);");
insert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String userName = name.getText().toString();
int userAge = Integer.parseInt(age.getText().toString());
ContentValues values = new ContentValues();
values.put("name", userName);
values.put("age", userAge);
db.insert("users", null, values);
Toast.makeText(MainActivity.this, "Data Inserted",
Toast.LENGTH_SHORT).show();
}
});
read.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Cursor cursor = db.rawQuery("SELECT * FROM users", null);
StringBuilder data = new StringBuilder();
if (cursor.moveToFirst()) {
do {

Artificial Intelligence and Machine Learning / AI23431 / 38


String userName = cursor.getString(0);
int userAge = cursor.getInt(1);
data.append("Name: ").append(userName).append(", Age:
").append(userAge).append("\n");
} while (cursor.moveToNext());
}
Toast.makeText(MainActivity.this, data.toString(),
Toast.LENGTH_LONG).show();
cursor.close();
}
});
}
}

activity_main.xml:

xml
Copy code
<?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"
tools:context=".MainActivity">

<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name"
android:layout_margin="16dp" />

<EditText
android:id="@+id/age"
android:layout_width="match_parent"

Artificial Intelligence and Machine Learning / AI23431 / 39


android:layout_height="wrap_content"
android:hint="Age"
android:inputType="number"
android:layout_below="@id/name"
android:layout_margin="16dp" />

<Button
android:id="@+id/insert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Insert"
android:layout_below="@id/age"
android:layout_margin="16dp"
android:layout_alignParentStart="true" />

<Button
android:id="@+id/read"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Read"
android:layout_below="@id/age"
android:layout_margin="16dp"
android:layout_alignParentEnd="true" />
</RelativeLayout>

Output:

An Android application that allows the user to insert and read data from a SQLite
database.

Result:

The Android application successfully interacts with a SQLite database to perform CRUD
operations.

Artificial Intelligence and Machine Learning / AI23431 / 40


Ex. No.: 7

INSTALLATION OF ANDROID STUDIO

Aim: To parse XML data in an Android application.

Algorithm:

1. Start.
2. Set up an Android project.
3. Create an XML file with sample data.
4. Write code to parse the XML file.
5. Display the parsed data in a user interface.
6. Test the application on an Android device or emulator.
7. Stop.

Program:

MainActivity.java:

java
Copy code
package com.example.xmlparsing;
import android.os.Bundle;
import android.util.Xml;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
TextView textView;

Artificial Intelligence and Machine Learning / AI23431 / 41


Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
InputStream inputStream = getAssets().open("sample.xml");
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES,
false);
parser.setInput(inputStream, null);
StringBuilder stringBuilder = new StringBuilder();
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
String tagName;
switch (eventType) {
case XmlPullParser.START_TAG:
tagName = parser.getName();
if (tagName.equals("employee")) {
stringBuilder.append("Employee:\n");
} else if (tagName.equals("name")) {
stringBuilder.append("Name:
").append(parser.nextText()).append("\n");
} else if (tagName.equals("age")) {
stringBuilder.append("Age:
").append(parser.nextText()).append("\n");
} else if (tagName.equals("department")) {
stringBuilder.append("Department:
").append(parser.nextText()).append("\n");

Artificial Intelligence and Machine Learning / AI23431 / 42


}
break;
}
eventType = parser.next();
}
textView.setText(stringBuilder.toString());
} catch (XmlPullParserException | IOException e) {
e.printStackTrace();
}
}
});
}
}

activity_main.xml:

xml
Copy code
<?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"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent
"
android:layout_height="wrap_content"
android:text="Parsed XML Data will appear here"
android:layout_margin="16dp"
android:textSize="16sp" />

<Button
android:id="@+id/button"

Artificial Intelligence and Machine Learning / AI23431 / 43


android:layout_width="wrap_content"

Artificial Intelligence and Machine Learning / AI23431 / 44


android:layout_height="wrap_content"
android:text="Parse XML"
android:layout_below="@id/textView"
android:layout_margin="16dp"
android:layout_centerHorizontal="true" />
</RelativeLayout>

sample.xml:

xml
Copy code
<?xml version="1.0" encoding="utf-8"?>
<employees>
<employee>
<name>John Doe</name>
<age>30</age>
<department>Engineering</department>
</employee>
<employee>
<name>Jane Smith</name>
<age>25</age>
<department>Marketing</department>
</employee>
</employees>

Output:

An Android application that parses and displays data from an XML file.

Result:

The Android application successfully parses XML data and displays it in the user interface.

Artificial Intelligence and Machine Learning / AI23431 / 45


Ex. No.: 8

DEVELOP AN ANDROID APPLICATION USING CONTROLS LIKE


BUTTON, TEXTVIEW, EDITTEXT FOR DESIGNING A CALCULATOR
HAVING BASIC FUNCTIONALITY LIKE ADDITION, SUBTRACTION,
MULTIPLICATION, AND DIVISION

Aim: To parse JSON data in an Android application.

Algorithm:

1. Start.
2. Set up an Android project.
3. Create a JSON file with sample data.
4. Write code to parse the JSON file.
5. Display the parsed data in a user interface.
6. Test the application on an Android device or emulator.
7. Stop.

Program:

MainActivity.java:

java
Copy code
package com.example.jsonparsing;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

Artificial Intelligence and Machine Learning / AI23431 / 46


import java.io.IOException;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity {

TextView textView;
Button button;

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

textView = findViewById(R.id.textView);
button = findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
InputStream inputStream = getAssets().open("sample.json");
int size = inputStream.available();
byte[] buffer = new byte[size];
inputStream.read(buffer);
inputStream.close();
String json = new String(buffer, "UTF-8");

JSONArray jsonArray = new JSONArray(json);


StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
stringBuilder.append("Name:
").append(jsonObject.getString("name")).append("\n");

Artificial Intelligence and Machine Learning / AI23431 / 47


stringBuilder.append("Age:
").append(jsonObject.getInt("age")).append("\n");
stringBuilder.append("Department:
").append(jsonObject.getString("department")).append("\n\n");
}
textView.setText(stringBuilder.toString());
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
});
}
}

activity_main.xml:

xml
Copy code
<?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"
tools:context=".MainActivity">

<TextView
android:id="@+id/textView"
android:layout_width="match_parent
"
android:layout_height="wrap_content"
android:text="Parsed JSON Data will appear here"
android:layout_margin="16dp"
android:textSize="16sp" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Parse JSON"
android:layout_below="@id/textView"
android:layout_margin="16dp"
android:layout_centerHorizontal="true" />
</RelativeLayout>

Artificial Intelligence and Machine Learning / AI23431 / 48


sample.json:

Artificial Intelligence and Machine Learning / AI23431 / 49


json
Copy code
[
{
"name": "John Doe",
"age": 30,
"department": "Engineering"
},
{
"name": "Jane Smith",
"age": 25,
"department": "Marketing"
}
]

Output:

An Android application that parses and displays data from a JSON file.

Result:

The Android application successfully parses JSON data and displays it in the user interface.

Artificial Intelligence and Machine Learning / AI23431 / 50


Ex. No.: 9

IMPLEMENT AN APPLICATION THAT WRITES DATA TO THE


SD CARD

Aim: To develop an application that writes data to an SD card using a microcontroller or


single-board computer.

Algorithm:

1. Initialize the System:


o Set up the microcontroller or single-board computer.
o Include necessary libraries for SD card interfacing.
2. Initialize the SD Card:
o Configure the SD card interface (e.g., SPI for microcontrollers).
o Initialize the SD card and check for successful initialization.
3. Open/Create a File:
o Open an existing file or create a new file on the SD card for writing data.
4. Write Data to the File:
o Write the required data to the file.
o Ensure data is written in the correct format.
5. Close the File:
o Properly close the file to ensure data integrity.
6. Verify Data:
o Optionally, read back the data to verify it was written correctly.

Program:

Below is an example program written in Arduino C for an Arduino microcontroller with


an SD card module.

#include <SPI.h>
#include <SD.h>

Artificial Intelligence and Machine Learning / AI23431 / 51


const int chipSelect = 4;

void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}

Serial.print("Initializing SD card...");

if (!SD.begin(chipSelect)) {
Serial.println("Initialization failed!");
return;
}
Serial.println("Initialization done.");

// Open the file. Note that only one file can be open at a time,
// so you have to close this one before opening another.
File dataFile = SD.open("example.txt",
FILE_WRITE);

// if the file opened okay, write to it:


if (dataFile) {
Serial.print("Writing to example.txt...");
dataFile.println("This is a test.");
dataFile.println("Writing data to the SD card.");
dataFile.close();
Serial.println("Done.");
} else {
// if the file didn't open, print an error:
Serial.println("Error opening example.txt");
}
}

Artificial Intelligence and Machine Learning / AI23431 / 52


void loop() {
// nothing happens after setup
}
Output:

The output of this program is a file named example.txt on the SD card with the following
content:

This is a test.

Writing data to the SD card.

Result:

The application successfully writes data to an SD card, demonstrating basic file operations
like opening, writing, and closing a file on an SD card using a microcontroller.

Artificial Intelligence and Machine Learning / AI23431 / 53


Ex. No.: 10

PROGRAM FOR BUILDING A SIMPLE USER INTERFACE USING


A XML FOR UI LAYOUT

Aim: To develop an Android application with a simple user interface using XML for UI
layout.

Algorithm:

1. Set up Android Studio:


o Install and set up Android Studio.
o Create a new Android project.
2. Define the XML Layout:
o Open the res/layout directory.
o Create an XML file for the layout (e.g., activity_main.xml).
3. Design the UI:
o Use XML tags to define UI elements (e.g., TextView, Button, EditText).
o Arrange UI elements using layout managers (e.g.,
LinearLayout, RelativeLayout, ConstraintLayout).
4. Link the XML Layout to Activity:
o Open the MainActivity.java or MainActivity.kt file.
o Set the content view to the XML layout using setContentView() method.
5. Add Event Listeners:
o Add event listeners in the Activity file to handle user interactions (e.g.,
button clicks).
6. Build and Run the Application:
o Build the application.
o Run the application on an emulator or physical device.

Program:

XML Layout (activity_main.xml)

Artificial Intelligence and Machine Learning / AI23431 / 54


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

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter your name:"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"/>

<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/textView"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"/>

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:layout_below="@id/editText"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"/>
</RelativeLayout>

Main Activity (MainActivity.java)

Artificial Intelligence and Machine Learning / AI23431 / 55


package com.example.simpleui;

Artificial Intelligence and Machine Learning / AI23431 / 56


import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private EditText editText;


private Button button;
private TextView textView;

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

editText = findViewById(R.id.editText);
button = findViewById(R.id.button);
textView = findViewById(R.id.textView);

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = editText.getText().toString();
textView.setText("Hello, " + name + "!");
}
});
}
}

Artificial Intelligence and Machine Learning / AI23431 / 57


Output:

When the application runs, it displays a UI with a TextView prompting the user to enter
their name, an EditText for the user to input their name, and a Button labeled "Submit".
After entering the name and clicking the "Submit" button, the TextView updates to greet
the user by name.

Result:

The application successfully demonstrates the creation of a simple user interface using
XML for layout definition and Java for event handling in an Android environment. The
user can interact with the UI by entering their name and receiving a personalized greeting.

Artificial Intelligence and Machine Learning / AI23431 / 58


Ex. No.:11

DEVELOP A MOBILE APPLICATION TO SEND AN EMAIL

Aim: To develop a mobile application that allows users to compose and send emails
directly from the application using an Android device.

Algorithm:

1. Set Up the Development Environment:


o Install Android Studio.
o Create a new Android project.
2. Design the User Interface (UI):
o Create an XML layout for the UI with EditText fields for email recipient,
subject, message body, and a Button to send the email.
3. Implement Email Sending Functionality:
o Configure permissions in the AndroidManifest.xml file for sending emails.
o Use JavaMail API (or similar) for email sending functionality.
o Set up an SMTP server for sending emails (e.g., Gmail SMTP server).
4. Handle User Input and Send Email:
o Retrieve user input from EditText fields.
o Validate input fields (optional).
o Use Java code to send an email with the provided details.
5. Run the Application:
o Compile and run the application on an Android device or emulator.
o Test sending emails with different recipient addresses and content.

Program:

XML Layout (activity_main.xml)

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"

Artificial Intelligence and Machine Learning / AI23431 / 59


tools:context=".MainActivity">

<EditText
android:id="@+id/editTextRecipient"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Recipient Email"
android:inputType="textEmailAddress"
android:layout_margin="16dp"/>

<EditText
android:id="@+id/editTextSubject"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Subject"
android:inputType="text"
android:layout_below="@id/editTextRecipient"
android:layout_margin="16dp"/>

<EditText
android:id="@+id/editTextMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Message"
android:inputType="textMultiLine"
android:layout_below="@id/editTextSubject"
android:layout_margin="16dp"/>

<Button
android:id="@+id/buttonSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send Email"
android:layout_below="@id/editTextMessage"

Artificial Intelligence and Machine Learning / AI23431 / 60


android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"/>
</RelativeLayout>

Main Activity (MainActivity.java)

Ensure you add the necessary permissions in your AndroidManifest.xml and also include
the JavaMail dependencies in your build.gradle file.

package com.example.sendemail;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class MainActivity extends AppCompatActivity {

private EditText editTextRecipient, editTextSubject, editTextMessage;

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

editTextRecipient = findViewById(R.id.editTextRecipient);
editTextSubject = findViewById(R.id.editTextSubject);
editTextMessage = findViewById(R.id.editTextMessage);

Artificial Intelligence and Machine Learning / AI23431 / 61


Button buttonSend = findViewById(R.id.buttonSend);
buttonSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendEmail();
}
});
}

private void sendEmail() {


String recipient = editTextRecipient.getText().toString().trim();
String subject = editTextSubject.getText().toString().trim();
String message = editTextMessage.getText().toString().trim();

// Replace with your email and password (or better use OAuth for security)
final String email = "[email protected]";
final String password = "your_password";

// Setup mail server properties


Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");

// Authenticate with mail server


Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(email, password);
}
});

Artificial Intelligence and Machine Learning / AI23431 / 62


try {
// Create a MimeMessage object.
Message mimeMessage = new MimeMessage(session);

// Set From: header field of the header.


mimeMessage.setFrom(new InternetAddress(email));

// Set To: header field of the header.


mimeMessage.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(recipient));

// Set Subject: header field


mimeMessage.setSubject(subject);

// Now set the actual message


mimeMessage.setText(message);

// Send message
Transport.send(mimeMessage);

Toast.makeText(getApplicationContext(), "Email sent successfully.",


Toast.LENGTH_LONG).show();

} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}

Output:

When the application runs, it displays a UI with EditText fields for recipient email,
subject, message body, and a Button labeled "Send Email". After filling in the recipient

Artificial Intelligence and Machine Learning / AI23431 / 63


email, subject, and message, and clicking the "Send Email" button, the application sends
the email using the configured SMTP server (in this case, Gmail).

Result:

The application successfully demonstrates how to send an email from an Android device
using JavaMail API and a configured SMTP server. Users can compose emails directly
within the application and send them to specified recipients.

Artificial Intelligence and Machine Learning / AI23431 / 64


Ex. No.:12

CREATE AN ANDROID APPLICATION TO SHARE THE DATA


BETWEEN MULTIPLE APPLICATIONS BY USING CONTENT
PROVIDER

Aim:

To develop an Android application that implements a Content Provider to share data


securely between multiple applications on the same device.

Algorithm:

1. Set Up the Development Environment:


o Install Android Studio.
o Create a new Android project.
2. Define the Data Contract:
o Create a class that defines the contract for your data, including
column names and URIs.
3. Implement the Content Provider:
o Create a class that extends ContentProvider.
o Implement CRUD (Create, Read, Update, Delete) operations (insert, query,
update, delete) within this class to manage access to your data.
4. Configure Permissions:
o Define permissions for accessing your Content Provider in the
AndroidManifest.xml.

5. Access Content Provider from Client Applications:


o Create one or more client applications that interact with the Content
Provider.
o Use ContentResolver to perform CRUD operations on the shared data.
6. Run the Applications:
o Compile and run both the Content Provider application and at least
one client application on an Android device or emulator.
o Test data sharing functionality by writing data from one application
and reading it from another.

Artificial Intelligence and Machine Learning / AI23431 / 65


Program:

Data Contract (MyDataContract.java)

package com.example.sharedataprovider;

import android.net.Uri;
import android.provider.BaseColumns;

public final class MyDataContract {

private MyDataContract() {}

public static final String AUTHORITY = "com.example.sharedataprovider.provider";


public static final Uri BASE_CONTENT_URI = Uri.parse("content://" +
AUTHORITY);
public static final String PATH_DATA = "data";

public static class DataEntry implements BaseColumns {


public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_DATA).build();

public static final String TABLE_NAME = "data";


public static final String COLUMN_ID = BaseColumns._ID;
public static final String COLUMN_NAME = "name";
public static final String COLUMN_VALUE = "value";
}
}

Content Provider (MyContentProvider.java)

package com.example.sharedataprovider;

import android.content.ContentProvider;

Artificial Intelligence and Machine Learning / AI23431 / 66


import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;

public class MyContentProvider extends ContentProvider {

private static final int DATA = 100;


private static final int DATA_ID = 101;

private static final UriMatcher sUriMatcher = buildUriMatcher();

private MyDbHelper mDbHelper;

private static UriMatcher buildUriMatcher() {


UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(MyDataContract.AUTHORITY,
MyDataContract.PATH_DATA, DATA);
uriMatcher.addURI(MyDataContract.AUTHORITY,
MyDataContract.PATH_DATA + "/#", DATA_ID);
return uriMatcher;
}

@Override
public boolean onCreate() {
mDbHelper = new MyDbHelper(getContext());
return true;
}

@Override

Artificial Intelligence and Machine Learning / AI23431 / 67


public Cursor query(Uri uri, String[] projection, String selection, String[]
selectionArgs, String sortOrder) {
final SQLiteDatabase db = mDbHelper.getReadableDatabase();
Cursor cursor;
int match = sUriMatcher.match(uri);
switch (match) {
case DATA:
cursor = db.query(
MyDataContract.DataEntry.TABLE_NAME,
projection,
selection,
selectionArgs,
null,
null,
sortOrder);
break;
case DATA_ID:
String id = uri.getLastPathSegment();
String[] selectionArguments = new String[]{id};
cursor = db.query(
MyDataContract.DataEntry.TABLE_NAME,
projection,
MyDataContract.DataEntry.COLUMN_ID + "=?",
selectionArguments,
null,
null,
sortOrder);
break;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}

cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;

Artificial Intelligence and Machine Learning / AI23431 / 68


}

@Override
public Uri insert(Uri uri, ContentValues values) {
final SQLiteDatabase db =
mDbHelper.getWritableDatabase(); int match =
sUriMatcher.match(uri);
Uri returnUri;
switch (match) {
case DATA:
long id = db.insert(MyDataContract.DataEntry.TABLE_NAME, null, values);
if (id > 0) {
returnUri =
ContentUris.withAppendedId(MyDataContract.DataEntry.CONTENT_URI, id);
} else {
throw new android.database.SQLException("Failed to insert row into " +
uri);

}
break;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}

getContext().getContentResolver().notifyChange(uri, null);
return returnUri;
}

@Override
public int update(Uri uri, ContentValues values, String selection, String[]
selectionArgs) {
final SQLiteDatabase db =
mDbHelper.getWritableDatabase(); int match =
sUriMatcher.match(uri);
int rowsUpdated;

Artificial Intelligence and Machine Learning / AI23431 / 69


switch (match) {
case DATA:

Artificial Intelligence and Machine Learning / AI23431 / 70


rowsUpdated = db.update(MyDataContract.DataEntry.TABLE_NAME, values,
selection, selectionArgs);
break;
case DATA_ID:
String id = uri.getLastPathSegment();
String[] selectionArguments = new String[]{id};
rowsUpdated = db.update(MyDataContract.DataEntry.TABLE_NAME, values,
MyDataContract.DataEntry.COLUMN_ID + "=?", selectionArguments);
break;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}

if (rowsUpdated != 0) {
getContext().getContentResolver().notifyChange(uri, null);
}
return rowsUpdated;
}

@Override
public int delete(Uri uri, String selection, String[] selectionArgs)
{ final SQLiteDatabase db =
mDbHelper.getWritableDatabase(); int match =
sUriMatcher.match(uri);
int rowsDeleted;
switch (match) {
case DATA:
rowsDeleted = db.delete(MyDataContract.DataEntry.TABLE_NAME,
selection, selectionArgs);
break;
case DATA_ID:
String id = uri.getLastPathSegment();
String[] selectionArguments = new String[]{id};
rowsDeleted = db.delete(MyDataContract.DataEntry.TABLE_NAME,

Artificial Intelligence and Machine Learning / AI23431 / 71


MyDataContract.DataEntry.COLUMN_ID + "=?", selectionArguments);

Artificial Intelligence and Machine Learning / AI23431 / 72


break;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}

if (rowsDeleted != 0) {
getContext().getContentResolver().notifyChange(uri, null);
}
return rowsDeleted;
}

@Override
public String getType(Uri uri) {
throw new UnsupportedOperationException("Not yet implemented");
}

private static class MyDbHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "mydata.db";


private static final int DATABASE_VERSION = 1;

MyDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
final String SQL_CREATE_DATA_TABLE = "CREATE TABLE " +
MyDataContract.DataEntry.TABLE_NAME + " (" +
MyDataContract.DataEntry.COLUMN_ID + " INTEGER PRIMARY
KEY
AUTOINCREMENT, " +
MyDataContract.DataEntry.COLUMN_NAME + " TEXT NOT NULL, " +
MyDataContract.DataEntry.COLUMN_VALUE + " TEXT NOT NULL" +

Artificial Intelligence and Machine Learning / AI23431 / 73


");";

Artificial Intelligence and Machine Learning / AI23431 / 74


db.execSQL(SQL_CREATE_DATA_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " +
MyDataContract.DataEntry.TABLE_NAME);
onCreate(db);
}
}
}

Client Application (ClientAppActivity.java)


This is an example client application that interacts with the Content Provider to read
and display data.
package com.example.clientapp;

import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import com.example.sharedataprovider.MyDataContract;

public class ClientAppActivity extends AppCompatActivity {

private static final String TAG = ClientAppActivity.class.getSimpleName();

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

Artificial Intelligence and Machine Learning / AI23431 / 75


// Example usage: Query data from Content Provider
Uri uri = MyDataContract.DataEntry.CONTENT_URI;
Cursor cursor = getContentResolver().query(uri, null, null, null, null);

if (cursor != null) {
while (cursor.moveToNext()) {
int id =
cursor.getInt(cursor.getColumnIndexOrThrow(MyDataContract.DataEntry.COLUMN_I
D));
String name =
cursor.getString(cursor.getColumnIndexOrThrow(MyDataContract.DataEntry.COLUMN
_NAME));
String value =
cursor.getString(cursor.getColumnIndexOrThrow(MyDataContract.DataEntry.COLUMN
_VALUE));

Log.d(TAG, "ID: " + id + ", Name: " + name + ", Value: " + value);
}
cursor.close();
}
}
}

Output:

When both applications run:

 The Content Provider application (MyContentProvider) initializes and manages a


SQLite database (mydata.db) with a table (data) defined by MyDataContract.
 The client application (ClientAppActivity) queries the Content Provider to

Result: Thus the android application shared the data between multiple applications by
using Content Provider Successfully.

Artificial Intelligence and Machine Learning / AI23431 / 76

You might also like