Iv Sem - Ai23431 - Web Development and Mobile App
Iv Sem - Ai23431 - Web Development and Mobile App
[Regulation 2023]
II Year – IV Semester
LABORATORY MANUAL
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.
VISION :
MISSION :
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.
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.
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
Contact hours : 30
Total Contact hours : 75
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.
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
Required
Exercise
Exercise Name Hours
no.
Outcome 2 Identify the difference between the HTML PHP and XML documents.
Outcome 3 Identify the engineering structural design of XML and parse tree
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);
}
// 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) {
// 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.
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;
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>
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.
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
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.
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:
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:
index.php:
php
Copy code
<?php
include 'db.php';
<!DOCTYPE html>
<html>
<head>
<title>Web Application</title>
</head>
<body>
<h2>User List</h2>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
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.
Aim: To implement a web application using Servlets that interacts with a database.
Algorithm:
1. Start.
Program:
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;
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;
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.
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:
sql
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" %>
<%
OUTPUT:
RESULT:
The web application using JSP successfully interacts with the database to display user
information.
a) JavaScript Calculator
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;
}
OUTPUT:
RESULT:
The JavaScript code successfully creates a simple calculator that performs addition,
subtraction, multiplication, and division.
b) PHP Calculator
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">
OUTPUT:
A web page with a simple calculator that performs basic arithmetic operations.
c) Servlet Calculator
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;
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
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
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.
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) {
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.
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 {
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"
<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.
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;
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"
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.
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;
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");
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>
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.
Algorithm:
Program:
#include <SPI.h>
#include <SD.h>
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);
The output of this program is a file named example.txt on the SD card with the following
content:
This is a test.
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.
Aim: To develop an Android application with a simple user interface using XML for UI
layout.
Algorithm:
Program:
<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>
@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 + "!");
}
});
}
}
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.
Aim: To develop a mobile application that allows users to compose and send emails
directly from the application using an Android device.
Algorithm:
Program:
<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"
<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"
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;
@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);
// Replace with your email and password (or better use OAuth for security)
final String email = "[email protected]";
final String password = "your_password";
// Send message
Transport.send(mimeMessage);
} 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
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.
Aim:
Algorithm:
package com.example.sharedataprovider;
import android.net.Uri;
import android.provider.BaseColumns;
private MyDataContract() {}
package com.example.sharedataprovider;
import android.content.ContentProvider;
@Override
public boolean onCreate() {
mDbHelper = new MyDbHelper(getContext());
return true;
}
@Override
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
@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;
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,
if (rowsDeleted != 0) {
getContext().getContentResolver().notifyChange(uri, null);
}
return rowsDeleted;
}
@Override
public String getType(Uri uri) {
throw new UnsupportedOperationException("Not yet implemented");
}
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" +
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " +
MyDataContract.DataEntry.TABLE_NAME);
onCreate(db);
}
}
}
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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_app);
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:
Result: Thus the android application shared the data between multiple applications by
using Content Provider Successfully.