0% found this document useful (0 votes)
71 views48 pages

AD Lab Manual

Uploaded by

kboy99527
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views48 pages

AD Lab Manual

Uploaded by

kboy99527
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

SSM

SSM COLLEGE OF ENGINEERING


KOMARAPALAYAM- 638 183

Department of Computer Science and Engineering Laboratory Record


NAME: COURSE:B.E (CSE)
REGISTER NO: YEAR: II Year VISem

Certified that this is bonafide record of work done by the


above student of the CCS332 - App Devolopment Laboratory
during the year 2023-2024.

Signature of Lab in Charge Signature of Head of the Department

Submitted for the Practical examination held on

Internal Examiner External Examiner

1
LIST OF EXPERIMENTS

Page
Ex.No. Date Title of the Experiment Marks Sign
No.
Using react native, build a cross platform
1, application for a BMI calculator.

Build a Cross Platform Application for Simple


2. Expense Manager

Developa cross platform application to convert


3 units from imperial system to metric system

Design and Develop a Cross Platform


4.
Application for Day to Day Task (To-Do)
Managerment

Design an Android Application using Cordova


5. for a User Login Screen

Design and develop an android application


using Apache Cordoba to find and display the
6.
current location

Write programs using Java to create Android


7a). application having Databases For a simple
library application.

Write programs using Java to create Android


application having Databases For displaying
7b). books, Assume that student information is
available in a database server

AVERAGE:

2
EXP NO :1 Using react native, build a cross platform application for a
BMIcalculator.

AIM;
To build a cross platform application for a BMI calculator.

PROCEDURE:

Step 1: Set Up Your React Native Environment:


Make sure you have Node.js and npm installed on your machine. Then, install React
Native CLI:
npm install -g react-native-cli

Create a new React Native project:


react-native init BMI Calculator

Navigate to your project directory:


cd BMICalculator

Step 2: Design the UI:


You'll need a simple Ulwith input fields for height and weight, a button to calculate BMI, and
a place to display the result.

Step 3: Implement the BMICalculation Logic:


Write the logic to calculate BMI based on the input height and weight.

Step 4: Display the Result:


Display the calculated BMI value along with a message indicating the BMI category (e.g.
underweight, normal weight, averweight, etc.).

3
Step 5: Testing:
Test your app on both ioS and Android simulators/emulators and real devices to ensure it
works corectly on different platforms.

Step 6: Deployment:
Once you're satisfied with your app, you can deploy it to the respective app stores (Google
Play Store for Android and Apple App Store for ioS).

PROGRAM:

import React, useState from 'react';


{

import {
View, Text, Textlnput, Button }
from 'react-native';

const BMI Calculator = () >{

const [height, setHeight] = useState("):

const [weight, setWeight] = useState("):

const [bmi, setBMI] = useState(null);

const calculateBMI=()=>{
if (height && weight) {

const heightMeters = height / 100:

const bmi Value = weight / (hcightMeters * heightMeters);

sctBMI(bmiValuc.toFixcd(2):
} {
else

/Handle error if height or weight is empty

setBMI(null):

}:

4
return(

<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center }}>

<Textlnput

placeholder="Height (cm)"
keyboardType="numeric"

value={height)

onChangeText=(setHeight}

style={{ marginBottom: 10, paddingHorizontal: 10, height: 40, borderColor: 'gray'


borderWidth: 1, width: 200 }}

<TextInput

placeholder="Weight (kg)"
keyboardType="'numneric"

value={weight}

onChangeText={setWeight}

style={{ marginBottom: 10, paddingHorizontal: 10, height: 40, borderColor: 'gray'


borderWidth: 1, width: 200 }}

<Button title="Calculate BMI" onPress={calculateBMI} >


{bmi !== null && <Text>Your BMI is: {bmi}</Text>}

</View>

);

):

cxport default BMI_Calculator;

5
OUTPUT:
- -

File Edit Selection View Go Run TerminalHelp indexjs bmi Visual Studio Code D
08
RMCI921

JS App.js M JS indexjs UX ***

src > JS index,js >


tel styles BMI Calculator
>button
97 backgroundColor: #6862ae,
9 justifyContent:'center',
50
9g alignItems :' center'
10
:

101 buttonText { 120


102 fontSize: 29,
10: color: '#fff',
Calculate
fontWeight:'bold'
105 }
1AF resultview:{ 17.3
107 margin:15, Underweight, eat more!!
108
109 result:{
110 fontSize: 30,
111 color: ' #2c6975",
112 fontWeight: 'bold'
113
114 ):

9 master Ln 95.Col 25 Spaces 4 UTF-8 () JavaScript


0A0 RI

RESULT:

Thus the cross platform application for a BMlcalculator are built successfully by
using react native JS.

6
EXP NO:2 Build a Cross Platform Application for Simple Expense
Manager

AIM:
expense manager which allows
To build a cross-platform application for a simple
entering expenses and income on each day and displays category wise weekly income and
expense., you can use React Native along with some additional libraries for managing state
and navigation.

PROCEDURE:

Step 1: Set Up Your React Native Environment:


Ensure you have Node.js, npm, and React Native CLI installed on your machine. You
can install React Native CLI using npm:
npm install -g react-native-cli

Create a new React Native project:


react-native init ExpenseManager

Navigate to your project directory:


cd ExpenseManager

Step 2: Install Required Dependencies:


Install the required dependencies for managing state and navigation:

npm install @react-navigation/native @react-navigation/stack react-native-gesture-handler


rcact-native-reanimated

Step 3: Set Up Navigation:


Create a basic navigation structure for your app. In your "App.js" file:

import React from 'react':


{ }
import NavigationContaincr from '@rcact-navigation/native';
{ }
import createStackNavigator from '@react-navigation'stack';

7
import HomcSereen from'/screens/HomeScreen';

import AddTransactionScreen from '/screens/AddTransactionScreen';

import WeeklySummaryScreen from "/screens/WeeklySummaryScreen':

const Stack = createStackNavigator():

const App=) =>{


return (

<NavigationContainer>

<Stack.Navigator initialRoute Name-"Home">

<Stack.Screen name="Home" component={HomeScreen} />

<Stack.Screen name-"AddTransaction" component={AddTransactionScreen} >


<Stack.Screen name="WeeklySummary" component-(WeeklySummary Screen} >

<Stack.Navigator>

<NavigationContaincr>

Cxport default App:

Step 4: Create Screens:

Create the necessary screens for your application:

HomeScreen': Display the list of transactions and provide options to add new
transactions.
AddTransactionScreen': Allow users to add new expenses or income.
"WeeklySummaryšcreen': Display category-wise weekly income and expense
summary.
Step 5: Implement Functionality:
Implement the functionality for adding transactions, calculating weekly summaries, and
displaying them on the screens.

Step 6: Styling:
Style your application to make it visually appealing and user-friendly.

Step 7: Testing:
Test your application on both i0S and Android simulators/emulators and real devices to
ensure it works correctly on different platforms.

Step 8: Deployment:
Once you're satisfied with your app, you can deploy it to the respective app stores (Google
Play Store for Android and Apple App Store for iOs).

PROGRAM:
import React from 'react':

import {
View, Text, FlatList} from 'react-native':

const HomeScreen =)=> {

const transactions = [

{id: 1, type: 'Expense', category: 'Food', amount: 50 ),

{
id: 2, type: 'Income', catcgory: 'Salary', amount: 2000 },

/Add more transactions here

J:
return(

<View syle={{ flex: 1, justifyContent: 'center', alignItems: 'center' }>


}

<Text style={{ fontSize: 20, marginBottom: 10 }>Transactions</Text>

<FlatList

data={transactions}

keyExtractor=(item => item.id.toString)}

renderltem={(( item ) =>(

<View style={{ flexDirection: 'row', justifyContent: 'space-between',


paddingHorizontal: 20, paddingVertical: 10 }}>

<Text>{item.category }</Text>

<Text>(item.type Expense'?'-:+} ${item.amount}<Text>

</View>

<View

export default HomcScreen:

10
OUTPUT:

React App +

O localhost:3000

Expense Manager
Amount:
Category
Transaction Type: Expense
Add Transaction Expense
Incomne

Weekly Report:
Category: Salary
Incomne: 500

Expense: 0

Category: Food
Income: 0

Expense: 150

• Category: Transportation
Income: 0

Expense: 100

RESULT:

Thus the Cross Platform Application for Simple Expense Manager which allows
entering expenses and income on each day and displays category wise weekly income and
expense calculator are built successfully by using react native JS.

11
EX NO:3 Develop a cross platform application to convert units from
imperial system to metric system

AIM:
To develop a crosS-platform application in Java for unit conversion from the imperial
system to the metric system, you can use the JavaFX framework. JavaFX allows you to create
desktop applications that can run on multiple platforms.

PROCEDURE:

Step 1: Set Up Your Development Environment:


Make sure you have Java Development Kit (DK) instaled on your machine. You can
download it from the official Oracle website.

Step 2: Set Up Your Project:


Create a new JavaFX project in your favorite lDE (e.g., IntelliJ IDEA, Eclipse). Make sure to
configure your project to use JavaFX.

Step 3: Design the User Interface:


Design the user interface for your unit conversion application. You can create a simple UI
with input fields for the value to be converted and dropdown menus to select the conversion
units (e.g., km to miles, kg to pounds).

Step 4: Implement the Conversion Logic:


Write the conversion logic to convert units from the imperial system to the metric system
and vice versa. You can create separate methods for each type of conversion (e.g.,
kmToMiles, kgToPounds).

12
Step 5: Bind UI Elements to Conversion Logic:
Bind the input fields and dropdown menus in your Ul to the conversion logic. Whenever the
user enters a value or selects conversion units, trigger the appropriate conversion method
and update the result accordingly.

Step 6: Test Your Application:


Test your application thoroughly to ensure that it correctly converts units and handles edge
cases gracefully.

Step 7: Packaging and Distribution:


Once you're satisfied with your application, package it for distribution. You can create
executable JAR files for distribution to users on different platforms.

PROGRAM:

import javafx.application.Application;

import javafx.scene.Scene:

import javafx.sccnc.control.Button;

import javafx.scene.control.ComboBox;

import javafx.scene.control.Label;

import javafx.scene.control.TextField:

import javafx.scene.layout. VBox;

import javafx.stage.Stage:

{
public class UnitConverterApp extends Application

private TextField input ValueField:

private ComboBox<String> fromUnitComboBox;

private ComboBox<String> toUnitComboBox;

13
private Label resultLabel;

@Override

public void start(Stage primaryStage) {

primaryStage.setTitle("Unit Converter"):

/Initialize UI components

inputValueField = new TextField):

fromUnitComboBoX = new ComboBox<0:

toUnitComboBox= new ComboBox<0;

resultLabel = new Label();

! Add conversion units to ComboBoxes

fromUnitComboBox.getltems().addAll("km", "kg", ...):

toUnitComboBox.getItcms().addAll("miles", "pounds", ...):

1/ Set up event listener for conversion

Button convertButton = new Button("Convert");

convertButton.setOnAction(e -> convertUnits());

I/Layout UI components
VBox layout = new VBox(10);

layout.getChildren().addAll(input ValueField, fromUnitComboBox, toUnitComboBox,


convertButton, resultLabel):

Scene scene = new Scene(layout, 300, 200);

primaryStage.setScene(scene);

14
primaryStage.show():

{
private void convertUnits()

try {

double input Value = Double.parseDouble(input ValueField.getText():

String fromUnit = fromUnitComboBox.get Value);

String toUnit = toUnitComboBox.getValue();

double result = performConversion(input Value, fromUnit, toUnit);

resultLabel.setText(String.format("%.2f %s = %.2f %s", inputValue, fromUnit, result,


toUnit));
}
catch (NumberFormatException e) {

resultLabel.setText("Invalid input");

private double performConversion(double value, String fromUnit, String toUnit) {

I/ Implement conversion logic here

1/ Example: km to miles conversion

if (fromUnit.equals("km") && toUnit.equals("miles")) {

return value * 0.621371;


}
else if (..) {

/Add more conversion cases here


}

return 0.0:

15
public static void main( String[l args) {

launch(args):

OUTPUT:

Code

Enter the unit to convert from:


km

Enter the unit to convert to:


miles
Enter the value to convert:
1

The converted value is: 6.21371

RESULT:

Thus the cross-platform application in Java for unit conversion from the imperial
system to the metric system are developed successfuly by using javaScript.

16
EX NO:4 Design and Develop a Cross Platform Application for Day
to Day Task (To-Do) Management

AIM:

To design and develop a cross-platform application for day-to-day task management


using Java, you can utilize JavaFX for the user interface and logic, and then use a framework
like Gluon Mobile to package the application for deployment on multiple platforms such as
Android, iOS, and desktop.

PROCEDURE:

Step 1: Set Up Your Development Environment:


Ensure you have Java Development Kit (JDK) installed on your machine. You can download it
from the official Oracle website.

Step 2: Set Up Your Project:


Create a new JavaFX project in your favorite lDE (e.g., IntelliJ IDEA, Eclipse). Make sure to
configure your project to use JavaFX.

Step 3: Design the User Interface:


Design the user interface for your task management application. You can include features
such as adding tasks, setting priorities, setting due dates, marking tasks as completed, and
organizing tasks into categories.

Step 4: Implement Task Management Logic:


Write the logic to manage tasks within your application. This includes adding tasks, editing
tasks, deleting tasks, marking tasks as completed, filtering tasks based on various criteria, etc.

17
Step 5: Persist Data:
Implement data persistence to store tasks between app sessions. You can use a simple file
based storage mechanism or a database depending on the complexity of your application.

Step 6: Test Your Application:


Test your application thoroughly to ensure that it works correctly on different platforms and
handles edge cases gracetully.

Step 7: Packaging and Distribution:


Once you're satisfied with your application, package it for distribution. You can use Gluon
Mobile to package your application for deployment on Android, iOS, and desktop platforms.

PROGRAM:

import javafx.application.Application;

import javafx.scene.Scene;

import javafx.scene.control.Button;

import javafx.scene.control. Label;

import javafx.scene.control.TextField;

import javafx.scene.layout.VBox;

import javafx.stage.Stage:

public class TaskManagerApp extends Application{

@Override

public void start(Stage primaryStage) {

primaryStage.setTitle("Task Manager");

18
/ Initialize UI components
TextField taskInputField = new TextField();

Button addButton = new Button("Add Task");

Label taskListLabel = new Label("Task List:");

1/ Set up event listener for adding tasks

addButton.setOnAction(e -> {

String task = tasklnputField.getText():

/ Add task to task list

/Update Ul to display task list

);

/ Layout UI components

VBox layout = new VBox(10);

layout.getChildren().addAll(taskInputFicld, addButton. taskListLabel);

Scene scene = new Scene(layout, 300, 200):

primaryStage.setScene(scene):

primaryStage.show();

public static void main(String[]args) {

launch(args);
}

19
OUTPUT:
-
Projects: bash Konsole
File Edit View Bookmarks Settings Help
[adriandavid@localhost Projects]$ gradle -v

Gradle 4.3.1

Build time: 2018-04-30 11:59:57 UTC


Revision: cdb459eef3c887e603a49388c6e83c3ba6fd3567

Groovy: 2.4.8
Ant: Apache Ant (TM) version 1.10.1 compiled on June 26 2018
JVM: 1.8.0_181 (0racle Corporation 25.181-b13)
0S: Linux 4.17.9-200.fc28. x86 64 amd64

[adriandavid@localhost Proj ects ]$

:
Projects bash

RESULT:

Thus the design and develop of a cross-platform application for day-to-day task
management using Java, you can utilize JavaFX for the user interface and logic, and then use
a framework like Gluon Mobile to package the application for deployment on multiple

platforms such as Android, ioS, and desktop has been developed successfully

20
EXP NO:5 Design an Android Application using Cordova for a User
Login Screen.

AIM:

To Design anandroid application using Cordova for a user login screen with username,
password, reset button and a submit button. Also, include header image and a label. By
Using layout managers.

PROCEDURE:

Step 1: Set Up Your Cordova Project:


First, make sure you have Cordova installed on your system. Then create a new Cordova
project:

cordova reate LoginÁpp com.example. loginapp LoginApp

cd LoginApp

Step 2: Add Android Platform:


Add the Android platform to your Cordova project:

cordova platform add android

Step 3: Design the UI:


Create your HTML file with the login form. Let's name it 'index.html':

Step 4: Style the U:


Create a CSS file named index.css' in the 'www/css' directory and add your styles:

Step 5: Handle Login Logic:


Create a JavaScript file named index.js in the www/js directory to handle the login logic:

21
Step 6: Add Header Image:
Place your header image in the www/img' directory.

Step 7: Build and Run the App:


Build the Cordova project and run it on your Android device or emulator:

cordova build android


Cordova run android

PROGRAM:

Design UI:
<DOCTYPE html>

<html>

<head>

<meta charset="utf-8" >


<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1,
user-scalable=no"s

<title>Login</title>

<link rel-"'stylesheet" type-"text/css" href-"css/index.css">

<head>

<body>

<div class="container">

<img src="imgheader_image.png" alt="Header Image">

<h2>Login<h2>

<form id="loginForm">

<label for="username">Username:<Aabel>

<input type="text" id="username" name="username" required>

<label for-"password">Password:</label>

22
<input type="password" id="password" name="password" required>

<button type="reset">Reset</button>

<button type-"submit">Submit</button>

</form>

</div>

<script type="tcxtijavascript" src="js/index.js"></script>

<body>

<htm>

Style Ul:
.container

max-width: 400px;

margin: 0 auto;

text-align: center;

img

max-width: 100%;

form

margin-top: 20px;

label {

display: block;

margin-bottom: 5pX;

23
{
input

width: 100%:

margin-bottom: 10px;

padding: 8px;

button {

padding: 10px 20px:

margin-right: 10px;

button[type="submit"] {

background-color: #4CAF50;

color: white;

border: none;

button[type="reset"]{

background-color: #f44336;

color: white;

border: none;

Handle Login:
{
document.addEvent Listener('deviceready', function()

24
var loginForm = document.getElementByld('login Form');

{
loginForm.addEventListener('submit', function(e)

e.preventDefault()0;

var username =
document.getElementByld('username').value;

var password =
document.getElementByld('password').value;

// Perform your login authentication here


|/ For demo, let's just log the username and password

console.log('Username:', username);

console.log('Password:, password);

// Youcan navigate to another page upon successful login

25
OUTPUT:
new
2- Notepad

|File Edit Search View Encoding Language Settings Tools Macro Run Plugins Window 2

o
Noc
Redmi

sbu Selest CAWindows\system32Z\cr


32\cmd.ere
4G
4G m G

Task Cordovalib:transformiativeLibswithintermediateJnilibsForDebug UP. TO- DATE


2 Task tapp:processDebugJ avaRes NO-SOURCE
esourcesitergesavaResForDebug UP-TO- DATE
Task
3 Task tapp:assembleDebug UP-TO-DATE
Task app:cdvBuildDebug UP-TO-DATE
1
BUILD SUCCESSFUL in 135
542 -to-date

D:\CordovaApp\Hello\platforms\android\app\build\ outputs\apk\ debuglapp-debug. apk


Sny ponTdefned
(reromonded setting)
IANDROID_HOME-C:\Users \Naveen \AppData\LocalAndroid\sdk (DEPRECATED)

Qsne ank: D:\CordoNaADO\Hello\olatforns \android\app\build\outputs\apk\debug\app-debug.apk


c
Packape hae kavevant 92** on device: Eeror: adb: Comand
execute shell c ommand "out failed with exit code 137 Error outp

daenon not running; starting now at tcp: 5037


10 daemon started successfully
APACHE CORDOVA
11 b:\CordovaApp\Hello>

12

RESULT:

Thus the android application using Cordova for a user login screen with username,
password, reset button and a submit button are designed successfully. Using layout
managers.

26
EXP N0 6: Design and develop an android application using Apache
Cordova to find and display the current location

AIM:

To create an Android application using Apache Cordova to find and display the
current location of the user,

PROCEDURE:

Step 1: Set Up Your Cordova Project:


If you haven't already, create a new Cordova project:

cordova crcate LocationApp com.cxample.locationapp LocationApp


cd LocationApp

Step 2: Add Android Platform:


Add the Android platform to your Cordova project:

cordova platform add android

Step 3: Install Required Plugins:


Install the Cordova geolocation plugin to access the device's GPS:

cordova plugin add cordova-plugin-geolocation

Step 4: Design the UI:


Create your HTML file witha simple interface to display the location. Let's name it
index.html:

27
Step 5: JavaScript Logic:
Create a JavaScript file named 'index.js' in the 'www/js' directory to handle the location
retrieval and display:

Step 6: Build and Run the App:


Build the Cordova project and run it on your Android device or emulator:

cordova build android

cordova run android

PROGRAM:

Design UI:
<!DOCTYPE htm>

<htm>

<head>

<meta charset-"utf-8" >


<meta name="viewport" content="widthrdevice-width, initial-scale=1, maximum-scale=1,
user-scalable=no">

<title>Location App</title>

<script type="text/javascript" src="cordova.js"></script>

<head>
<body>

<div id="map" style="width:100% ;height:400px;">x/div>

<button id-"getLocationBtn">Get Location<button>

<script type="text/javascript" src="js/index.js"></script>

</body>

<html>

28
JavaScript Logic:
{
document.addEventListener(deviceready', function()
var getLocationBtn = document.getElementByld('getLocationBtn'):

var mapDiv = document. getElementByld('map');

getLocationBtn.addEventListener('click', function() {

navigator.geolocation.getCurrentPosition(onSuccess, onError);

D:

function onSuccess(position) {

var latitude = position.coords.latitude;

var longitude = position.coords.longitude:

var mapUrl = "htps:/maps.googleapis.com/maps/api/staticmap?center=" + latitude + 11

+ longitude + "&zoom=15&size=400x400&markers=color:red% 7C" + latitude +","


longitude:

mapDiv.inncrHTML=<img src="" + mapUrl + ">;

function onBrror(error)
{

alert('Error occurred:'+ error.message);

29
OUTPUT:

G CAWINDOWS\system 32\cmd.exe
Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.

You can use --warning-mode all' to show the individual deprecation warnings and determine if they come from
ripts or- plugins.
.
See https://docs gradle. org/7.1.1/userguide/command_line_interface .html#sec: command_line_warnings
BUILD SUCCESSFUL in 41s
48 actionable tasks : 48 executed
Built the following apk(s) :
C:\Users\conta\my FirstApp \platforms\android \app\build \outputs\apk\debug \app-debug. apk

C:\Users\conta \myFirstApp>cordova build android --release -packageType=bundle


Checking Java JDK and Android SDK versions
ANDROID_SDK_ROOT=C:\Users\conta\AppData\ Local\AndroiSdk (recommended setting)
ANDROID HOME=C: \Users\conta\AppData\Local\Android\Sdk (DEPRECATED)
Using Android SDK: C:\Users\conta\AppData\ Local\Android \Sdk
Subproject Path: Cordovalib . .
Warning: Mapping new ns http://schemas. android com/repos itory/android/common/02 to old ns http://schemas andr
ository/android/common /01 .
Warning: Mapping new ns http://schemas. android. com/repository/android/generic/02 to old ns http://schemas and
pository/android/generic/01 . .
Warning: Mapping new ns http://schemas android. com/sdk/ android/repo/addon 2/02 to old ns http://schemas androi
ndroid/repo/addon2/01

RESULT:

Thus the Android Applications are created using Apache Cordova to find and
display the current location of the user,

30
EXP NO: 7a) Write programs using Java to create Android application
having Databases For asimple library application.

AIM:
To create an Android application for a simple library system with a database,

IMPLEMENTATION:

1. Set Up Your Android Project:


Set up an Android project in Android Studio.

2. Design the UI:


Create XML layout files for the user interface components like buttons, text fields,
etc.,in the res/layout directory.

3. Create Database Schema:


Define the structure of your database, including tables and columns.

4. Implement Database Helper Class:


Create a class that extends SQLiteOpenHelper to manage database creation and version
management.

5. Perform Database Operations:


Write methods to perform CRUD (Create, Read, Update, Delete) operations on the
database.

6. Integrate Database Operations with UI:


Call database operations methods from your activity or fragment classes to interact
with the database based on user actions.

PROCEDURE:

Step 1: Set Up Your Android Project:


Create a new Android project in Android Studio.

31
Step 2: Set Up Your Android Project:

Design XML layout files for your library application UI, including screens for adding, editing.
and viewing books, and for searching.

Step 3: Create Database Schema:


Define the structure of your database.

Step 4: Implement Database Helper Class:


Create a class that extends SQLiteOpenHelper to manage database creation and
version management. Override onCreate) to create tables and onUpgrade) to
handle database schema changes.

Step 5: Perform Database Operations:


Write methods to perform CRUD operations on the database. For example, methods to add
a book, delete a book, update book details, and retrieve book information.

Step 6: Integrate Database Operations with UI:


Call methods from the LibraryDataSource class to interact with the database based
on user actions, such as adding a new book when the user submits a form.

PROGRAM:

Database Schema:
public class LibraryContract{

public static final int DATABASE VERSION = 1;

public static final String DATABASE NAME = "Library.db";

32
public static abstract class BookEntry implements BaseColumns {

public static final String TABLE NAME = "books";

public static final String COLUMN_NAME_TITLE =


"title";

public static final String COLUMN_ NAME AUTHOR = "author";


=
public static final String COLUMN_NAME_PAGES "pages";

Database Helper Class:


public class LibraryDbHelper extends SQLiteOpenHelper {

public LibraryDbHelper(Context context) {

super(context, LibraryContract.DATABASE_NAME, null,


LibraryContract.DATABASE_VERSION);

@Override

public void onCreate(SQLiteDatabase db) {

String SQL_CREATE_ENTRIES =

"CREATE TABLE"+ LibraryContract. Book Entry.TABLE_NAME +" ("+

LibraryContract.BookEntry._ID +" INTEGER PRIMARY KEY," +

LibraryContract.BookEntry.COLUMN_NAME_TITLE +" TEXT," +

LibraryContract.BookEntry.COLUMN_NAME_AUTHOR + " TEXT," +

LibraryContract.BookEntry.COLUMN_ NAME_ PAGES +" INTEGER)";

db.execSQL(SQL_CREATE_ENTRIES):

33
@Override
{
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)

# Handle database schema upgrades

Database Operations:
{
public class LibraryDataSource

private SQLiteDatabase database:

private LibraryDbHelper dbHelper;

public LibraryDataSource(Context context)


{

dbHelper = new LibraryDbHelper(context):

public void open() hrows SQLException {

database = dbHelper. get WritableDatabase(0:

public void close(){

dbHelper.close():

public long addBook(String title, String author, int pages) {

ContentValues values = new Content Values();

values.put(LibraryContract.BookEntry.COLUMN_NAME_TITLE, title);

34
values.put(LibraryContract.BookEntry.COLUMN_NAME_AUTHOR, author):

values.put(LibraryContract.BookEntry.COLUMN_NAME_PAGES, pages):

return database.insert(LibraryContract. BookEntry. TABLE_NAME, null, values);

I/ Implement other CRUD methods

OUTPUT:
File Add View Help

Book Issue Renew /Submission

p
Issued Books (1)

Book ID Total Books (2)

p Members with book D About Me

ID
Member YouTube Channel
Total Members (2)

GO
Blog

Linked In
Issue
Personal Facebook Page

Built with love and couple of lines of code

35
RESULT:

Thus the Android application having Databases For a simple library application are
successful created by using Java.

36
EXP NO: 7b)

Write programs using Java to create Android


application having Databases For displaying books, Assume that
student information is available in a database server.

AIM:

To create an Android application for managing books available, books lent, and book
reservations, you'llneed to integrate with a remote database server for managing student
information and a local database for managing books.

PROCEDURE:

Step 1: Set Up Your Android Project:


Create a new Android project in Android Studio.

Step 2: Design the UI:


Design XML layout files for your application UI, including screens for displaying available
books, lent books, and book reservations.

Step 3: Set Up Remote Database:


You need a server-side application to interact withthe student database. This server-side
application should expose APls for retrieving student information, such as their ID, name, etc.

Step 4: Integrate Remote Database Communication:


Use HTTP requests (e.g., Retrofit library) to communicate with the server-side application and
fetch student information based on actions taken in your app.

37
Step 5:Set Up Local Database:
Create a local SQLite database to manage the information about available books, lent books,
and book reservations.

Step 6: Implement Database Helper Class:


Create a class that extends sQLiteOpenHelper to manage the local database creation and
version management.

Step 7: Perform Database Operations:

Write methods to perform CRUD operations on the local database. For example, methods to
add a book, mark a book as lent, mark a book as reserved, etc.

Step 8: Integrate Database Operations with UI:


Callmethods from the database helper class to interact with the local database based on
user actions, such as displaying available books, marking a book as lent, reserving a book,
etc.

PROGRAM:
public class BookDataSource {

private SQLiteDatabase database;

private BookDbHelper dbHelper;

public BookDataSource(Context context) {

dbHelper = new BookDbHelper(context);

public void open() throws SQLException {

database = dbHelper.get WritableDatabase():

38
{
public void close)

dbHelper.close);
}

public long addBook(String title, String author, int quantity) {

ContentValues values = new Content Values():

values.put(BookContract.BookEntry.COLUMN_NAME_TITLE, title);

values.put(BookContract.BookEntry.COLUMN_NAME_AUTHOR, author);

values.put(BookContract.BookEntry.COLUMN_NAME_QUANTITY, quantity);

return database.insert(BookContract. BookEntry.TABLE NAME, null, values):

/ Method to mark a book as lent


{
public void lendBook(long bookld)

/ Update database to mark the book as lent


}

/ Method to marka book as reserved

public void reserveBook(long bookld)


{

/Update database to mark the book as reserved

/Method to retrieve available books

public List<Book> getAvailableBooks(){

39
/ Query the database for available books

/ Return list of available books

/ Method to retrieve lent books

public List<Book> getLentBooks() {

| Query the database for lent books

/ Return list of lent books

1/ Method to retrieve reserved books

public List<Book> getReservedBooks0


{

I/Query the database for reserved b0oks


/ Return list of reserved b0oks

40
OUTPUT:
Execute the application by clicking on the run button. Once, you execute you will see the
below dialog box. In the below dialog box, mention username and password as {admin,
admin). Then click on the Login button.

Login X

Username admin

Password

Once you click on the Login button, you willsee the below dialog box opening up.

Admin Functions

View Books View Users View Issued Books Issue Book

Add User Add Book Return Book CreatelReset

Here you have various options which you can explore. So, let us start with the
first one:
View Books
Once, you click on View Books button, you will see the below frame displaying all
the books present in the database, with their details.

41
Books Available X
BID BNAME GENRE PRICE
1 War and Peace Mystery 200
The Guest Book Fiction 300
3 The Perfect Murder Mystery 150
A Accidental Presidents Biography 250
The Wicked King Fiction 250

View Users
The View Users button is used to view the current users on the system. Since we
just have only one user present i.e the admin, it will show you output as below:

Users List

UID USERNAME PASSWORD ADMIN


admin admin true

Create/Reset
This functionality is used to create or reset a database. So, once you click on the
button Create/Rest, you will see the below output:

42
Message X

Database Created/Reset!

OK

Add User
To add a user, click on the option "Add User" and mention details such
as username, password and choose the radio button user or admin. By
default, it will be the user. Then, click on Create.

Enter User Details X

Username sahiti

Password

Admin User

Create

Issue Book
Suppose, if you are the user, once you click on the Issue Book button, you have
to mention the Book ID, User ID, Period(Number of days for issuing the
book), and the Issue Date as follows:

43
Enter Details X

Book ID(BID) 3

User ID(UID) 2

Period(days) 10

Issued Date(DD-MM-YYn 02-09-2019

Submit

Then click on Submit. Once, you click on Submit, you will see the below dialog
box:

Message

Book Issued!

OK

Now, if you want to see the issued books details, you can use the View Issued
Books functionality.

View Issued Books


Once you click on this button, you will see the following output:

44
Users List X
IID UID BID ISSUED_DATE RETURN_DATE PERIOD FINE
02-09-2019 10

Alright, so, now if the user logs in to the system, using the login function, as
below:

Login

Username sahiti

Password

Login

JThen the user will see the


below User Menu.

User Functions

View Books My Books

Here, the user can view all the books in the database by using the View Books
option and the books issued by the user in the My Books section as below:
Bccks Avalalle R M Becks n
Nar and
The GuestBpck
BUWE
Pead Meatery
GENRE PRICS
0UDBsED.D RETUReLDPERISOEePe
Presisents
Acoidental
Bipgrapty
The Wicked King

45
Now, if you wish to return the book, then you have to choose the option of
Return Book.

Return Book
Once, you click on the Return Book, mention the Issue ID and the return
date as below. Then click on Return.

Enter Details

Issue ID(ID)1
Return Date(DD-MM-YYYY 12-10-2019

Return
JThen, you see a message box
displaying the fine.

Message

Fine: Rs. 300

OK

After that, you again see a dialog box, showing the message "Book Returned".
Refer below.

Message

i Book Returned!

OK

Now, if you click on the View Issued Books, you will see the below output:

46
Users List X
ID UID BID ISSUED DATE RETURN_DATE PERIOD FINE
1 2 3 02-09-2019 |12-10-2019 10 300

Lastly, if you wish to add a book, you can use the option of Add Book.
Add Book
Click on the Add Book button, and mention the book name, genre and price.
Then, click on the Submit button. Refer below.

Enter Book Details

Book Name Murder on the Oriet Express

Genre Thriller

Price 1000|

Submit

Youwill see a dialog box displaying the below message:

Message

Book added!

OK

Apart from this, you can also, see the added books in the View Books section as
below:

47
Books Available X
BID BNAME GENRE PRICE
War and Peace |Mystery 200
2 The Guest Book Fiction 300
The Perfect Murder Mystery 160
Accidental Presidents Biography 250
The Wicked King Fiction 350
Murder on the Orient Express Thriller 1000

RESULT:

Thus the Android application for managing books available, books lent, and book
reservations, you'll need to integrate with a remote database server for managing student
information and a local database for managing books are created successfully.

48

You might also like