0% found this document useful (0 votes)
19 views49 pages

Ccs332 App Dev Lab Manual Aiml

The document outlines a record notebook for the CCS332 App Development course at Gojan School of Business and Technology, detailing various exercises focused on building cross-platform applications using frameworks like React Native and Flutter. It includes specific aims, procedures, and code implementations for projects such as a BMI calculator, unit converter, and expense manager. The document serves as a practical guide for students to develop their programming skills in app development.

Uploaded by

Deva Mahalingam
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)
19 views49 pages

Ccs332 App Dev Lab Manual Aiml

The document outlines a record notebook for the CCS332 App Development course at Gojan School of Business and Technology, detailing various exercises focused on building cross-platform applications using frameworks like React Native and Flutter. It includes specific aims, procedures, and code implementations for projects such as a BMI calculator, unit converter, and expense manager. The document serves as a practical guide for students to develop their programming skills in app development.

Uploaded by

Deva Mahalingam
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/ 49

GOJAN SCHOOL OF BUSINESS AND TECHNOLOGY

Approved by AICTE & Affiliated to Anna University Chennai


NAAC Accredited Institution
Recognized by UGC u/s 2(f) & 12 (B) of the UGC Act
EDAPALAYAM, REDHILLS, CHENNAI – 600 052

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CCS332 - APP DEVELOPMENT

RECORD NOTE BOOK 20 - 20

Name :

Roll. No :

Year :

Semester :

Subject :

Branch :
GOJAN SCHOOL OF BUSINESS AND TECHNOLOGY
Approved by AICTE & Affiliated to Anna University Chennai
NAAC Accredited Institution
Recognized by UGC u/s 2(f) & 12 (B) of the UGC Act
EDAPALAYAM, REDHILLS, CHENNAI – 600 052

BONAFIDE CERTIFICATE

Name :

Department :

Roll No :

Register No.

Certified that this is the bonafide record of work done by the above student in the
Laboratory during the year 20 – 20 .

Head of the Department Lab In-charge

Submitted for the practical examination held on

Internal Examiner External Examiner


TABLE OF CONTENTS

Exp Date of Title Page Date of Marks Sign


No Experiment No submission

1 Using React native, build a Cross


platform application for a BMI
calculator.
2 Develop a cross-platform
application to convert units from
imperial system to metric system
(km to miles, kg to pounds etc.,)

3 Build a cross-platform application


using Flutter for a simple expense
manager which allows entering
expenses and income on each day
and displays category wise weekly
income and expense.
4 Design and develop a Cross
platform application for day-to-day
task (to-do) management.
5 Design an Android application
using Cordova for a user login
screen with username, password,
reset button and submit button.
Also include a header image and a
label, Use layout managers
6 Design and develop an android
application using Apache Cordova
to find and display the current
location of the user
7 Design and implement a simple
library management system using a
switch statement in java, where
following operations are operated -
Add a new classes', check out a
book, display specific book status,
search specific book status and
display book details using different
classes
Date -
EXERCISE:1 Using react native, build a cross platform application for a BMI
calculator.

Aim:

To develop a cross-platform BMI (Body Mass Index) calculator application using React
Native, capable of running on both iOS and Android devices.

Body Mass Index (BMI) is a number calculated from a person's weight and height that helps
determine if they are underweight, normal weight, overweight, or obese.

Here’s how to calculate BMI:

BMI is the measure of body index: BMI= weight(kg)/height(m)]^ 2

Here are the general BMI ranges for adults:

 Underweight: BMI less than 18.5


 Normal weight: BMI 18.5 - 24.9
 Obese: BMI > 24.9

Procedure
Step 1: Install Required Tools:

a) Install Node.js

b) Ensure java 17 or above is installed

c) Ensure npm is installed

Step 2: Setup your IDE. (Visual studio code is recommended.)


a) Install the plugins
b) Cd to the Project Folder and open a cmd prompt here
c) Type code . to get the Vs code opened in the project folder

Step 3: Create your project .


Open terminal in VS Code from your project directory and run the following command

>> npx create-react-app bmi_calculator


Step 4: Directory bmi_calculator will be created. CD to the directory
Step 5: Run your application.

>> npm install react-native-web


>> npm start
Below default screen should be visible in browser if Application is successfully run,

Programme Implementation
Step 6: Open bmi_calculator/src/App.js and type code

import React, { useState } from 'react';

import { StyleSheet, Text, View, TextInput, Button, Alert } from 'react-native';

export default function App() {


const [weight, setWeight] = useState('');

const [height, setHeight] = useState('');


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

const [bmiCategory, setBmiCategory] = useState('');

const calculateBMI = () => {


if (weight === '' || height === '') {

Alert.alert('Error', 'Please enter weight and height.');


return;
}

const weightNum = parseFloat(weight);


const heightNum = parseFloat(height) / 100; // Convert cm to meters
const bmiValue = weightNum / (heightNum * heightNum);

setBmi(bmiValue.toFixed(2));

if (bmiValue < 18.5) {


setBmiCategory('Underweight');
} else if (bmiValue >= 18.5 && bmiValue < 25) {
setBmiCategory('Normal weight');
} else if (bmiValue >= 25 && bmiValue < 30) {
setBmiCategory('Overweight');

} else {
setBmiCategory('Obese');
}
};

return (

<View style={styles.container}>
<Text style={styles.title}>BMI Calculator</Text>
<TextInput
style={styles.input}

placeholder="Weight (kg)"
keyboardType="numeric"
value={weight}

onChangeText={setWeight}
/>
<TextInput
style={styles.input}

placeholder="Height (cm)"
keyboardType="numeric"
value={height}
onChangeText={setHeight}
/>
<Button title="Calculate BMI" onPress={calculateBMI} />
{bmi && (

<View>
<Text style={styles.result}>Your BMI:{bmi}</Text>
<Text style={styles.result}>Category: {bmiCategory}</Text>
</View>
)}

</View>
);
}

const styles = StyleSheet.create({


container: {
flex: 1,
padding: 20,
justifyContent: 'center',

},
title: {
fontSize: 24,
fontWeight: 'bold',
textAlign: 'center',
marginBottom: 20,

},
input: {
borderWidth: 1,
borderColor: 'gray',
borderRadius: 5,
padding: 10,
marginBottom: 10,
},

result: {
fontSize: 18,
textAlign: 'center',
marginTop: 20,
},
});

Output from Browser Output from an Android Stimulator


(Android studio)

Result :
BMI calculator App is built by the React native Cross Platform Framework.
Date -
Exercise:2 Develop a cross platform application to convert units from imperial system
to metric system (km to miles , kg to pounds etc.,)

Aim
To develop a cross-platform application for unit conversion from the imperial system to the
metric system, by using React Native Framework. This framework allows us to write code
once and deploy it on multiple platforms such as iOS, Android, and web.
Procedure
Step 1 - Set up your development environment: Install Node.js, npm (Node Package
Manager), and the chosen framework (React Native or Flutter) on your machine.
npm install convert-units

Step 2 - Create a new project: Use the command-line interface to create a new project using
the framework's CLI tool. For example, with React Native, use the command
npx create-react-app UnitConverter.

Step 3 - Design the user interface: Use the framework's components and layout system to
design the user interface for your unit converter application. Use text inputs for user input and
labels to display the converted values.
Step 4 - Implement the conversion logic: Write the code to convert units from the imperial
system to the metric system. For example, to convert kilometers to miles, you can use the
conversion formula miles = kilometers * 0.621371. Implement similar conversion formulas
for other unit conversions.

Step 5 - Handle user input: Capture user input from the text inputs and trigger the conversion
logic when the user submits the form or presses a button.
Step 6 - Display the converted values: Update the labels or text fields with the converted
values based on the user input and the conversion logic.
Step 7 - Test the application: Run the application on different platforms (iOS, Android, web)
to ensure it works correctly and displays the converted values accurately.

Programme Implementation
Step 1: Setup your IDE. (Visual studio code is recommended.)
a) Install the plugins Live Server, babel JavaScript, Prettier – code and Es7 – react* in
Vs code

b) Cd to the Project Folder and open a cmd prompt here


c) Type code . to get the Vs code opened in the project folder
Step 2: Create your project .
Open terminal in VS Code from your project directory and run the following command
>> npx create-react-app unit_convert
Step 3: Directory unit_convert will be created. CD to the directory
Step 4: Run your application.

>> npm install react-native-web

>> npm start


Below default screen should be visible in browser if Application is successfully run,

Step 5: Open unit_convert /src/App.js and type code


import React, { useState } from 'react';
import { View, Text, TextInput, StyleSheet, Button } from 'react-native';
import convert from 'convert-units';

const UnitConverter = () => {


const [inputValue, setInputValue] = useState('');
const [fromUnit, setFromUnit] = useState('mi'); // Default to miles

const [toUnit, setToUnit] = useState('km'); // Default to kilometers


const [result, setResult] = useState('');
const handleConversion = () => {
try {
const convertedValue = convert(parseFloat(inputValue))
.from(fromUnit)
.to(toUnit);

setResult(convertedValue.toFixed(2));
} catch (error) {

setResult('Invalid input or unit');


}

};

return (
<View style={styles.container}>
<Text>Unit Converter</Text>

<TextInput
style={styles.input}
keyboardType="numeric"
value={inputValue}

onChangeText={setInputValue}
placeholder="Enter value"
/>

{/* Add pickers or dropdowns for selecting fromUnit and toUnit */}

<Button title="Convert" onPress={handleConversion} />


{result !== '' && <Text style={styles.result}>{result}</Text>}

</View>
);
};
const styles = StyleSheet.create({
container: {

flex: 6,
// justifyContent: 'center',
alignItems: 'center',
marginLeft: -1100,
padding: 20,

},
input: {
borderWidth: 1,

borderColor: 'graykl',
padding: 10,
marginBottom: 10,
width: 200,

},
result: {
fontSize: 18,
marginTop: 10,
},
});

export default UnitConverter;


Output from browser Output from Android studio

Result :
A cross Platform Application is build which converts units from imperial system to
metric system.
Date -
Exercise : 3
Build a cross-platform application for a simple expense manager which allows entering
expenses and income on each day and displays category wise weekly income and
expense.

Aim : To build a cross-platform application fusing Flutter Framework for a simple expense
manager which allows entering expenses and income on each day and displays category wise
weekly income and expense

Procedure
Step1:
Create APP: Android Studio, and create a new Flutter Give the project name
"expense today”. And click. Next and follow the same to use the default settings.
Step 2: Now delete all the code from the main.dart file.

Step3: Create the Main App Widget

main.dart

import 'package:flutter/material.dart';
final String appTitle = "Expense App";
void main() {
runApp(ExpenseApp());
}
class ExpenseApp extends Stateless Widget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {

return MaterialApp(
title: appTitle,

theme: ThemeData(
primarySwatch: Colors.green,
visualDensity: VisualDensity.adaptivePlatformDensity, ),
home: Text(appTitle),
debugShowCheckedModeBanner: false);
}}
Step 4: Run the app:

Step 5: Create a HomeScreen Stateful widget

main.dart file at the bottom after Expense App class, write the Following code.
class HomeScreen extends StatefulWidget {
constHomeScreen( ({Key key}): super(key: key);
@override
_HomeScreenStatecreateState() =>_HomeScreenState();

class_HomeScreenState extends State<HomeScreen> {


String title appTitle;

@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: ListView(
children: [

Text("ABC"),
Text("DEF"),
],

),
),
appBar: AppBar(

title: Text(title),
),
floating ActionButton: Pressed: () {}, Floating ActionButton.extended(
onPressed : ( ) { },
label: Text('Add'),
icon: Icon(Icons.add),

backgroundColor: Colors.pink,
),
);
}}
Step 6: Update ExpenseApp Widget
class ExpenseApp extends Stateless Widget {

//
This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(


home: HomeScreen(),

}

Step 7: Fix Test Code red line is showing under the widget_test.dart. To remove it just
change MyApp() to Expense App()

Step 8: Create a Row Widget

Step:9 Creating the Widget UI. write the following code in the category_widget.dart file

import package flutter/material.dart';

class CategoryWidget extends StatefulWidget {


Category Widget({Key key, this rowNumber, this.callback)) super(key: key);
int rowNumber;
Function callback;

@override
_Category WidgetStatecreateState() => _CategoryWidgetState();

}
class_CategoryWidgetState extends State<CategoryWidget> {
@override
Widget build(BuildContext context) {
return Card(
child: Padding(

padding: constEdgeInsets.all(15.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.space Between, children: [
Padding(

padding: constEdgeInsets.only(right: 20),

child: Text(

"$(widget.rowNumber + 1}",
style: TextStyle(
fontSize: 20,
font Weight: Font Weight.bold,
),
),

),
Expanded(
child: TextField(

onChanged: (text) {
print(text);
},
decoration: InputDecoration(
border: OutlineInputBorder(),

labelText: 'Category',
),

),
),
Icon(Icons.attach_money),
Expanded(

child: TextField(

onChanged: (text) {

print(text);

},
decoration: InputDecoration(
border: OutlineInputBorder(),

labelText: 'Cost',
),
),
],
),

),
),
}
}
Step 10: Update the ListView within the class. _HomeScreenstate
class_HomeScreenState extends State<HomeScreen> {
@override

Widget build(BuildContext context) {


return Scaffold(

body: SafeArea(
child: ListView(
children: [

Category Widget(
rowNumber: 0,

callback: () {},
),
Category Widget(
rowNumber: 1,

callback: () {},
),
],
),

),

);
}
}

Step 11: Create the "+ Add" Functionality

click the pink +Add button new row will be added.


add int totalRow = 0; within the_HomeScreenState
class_HomeScreenState extends State<HomeScreen>
String title appTitle;
int totalRow = 0;
….
Step 12: addRow function within the HomeScreen State
Class_HomeScreenState extends State<Home Screen>{

void addRow() {

setState(() {
totalRow+1:

});}...)

Step 13: Listview within the _ HomeScreen Widget again:

Widget build(BuildContext context) {

return Scaffold(
body: SafeArea(

child: ListView(
children: [
for (int i = 0; i<totalRow; ++i)
Category Widget(
rowNumber: i,
callback: () {}, ), ], ),

),
],
),
),

Step 14: onPressed function of the floating ActionButton widget and add a reference of
addRow function.

floatingActionButton: Floating ActionButton.extended(
onPressed: addRow,

label: Text('Add'),
icon: Icon(Icons.add),

backgroundColor: Colors.pink,
),

Step 15: save the file to hot reload the app. You see, the app screen is blank, and if

you click + Add continuously a new Category Widget will be added within the ListView.

Step 16: Update main.dart file

Now update the main.dart file by importing the new widget here.
import package:expense_today/category_widget.dart';

Step 17: update the ListView within the _HomeScreenstate class.

class_HomeScreenState extends State<HomeScreen> {



@override

Widget build(BuildContext context) {


return Scaffold(
body: SafeArea(
child: ListView(
children: [
Category Widget(
rowNumber: 0,

callback: () {},

),
Category Widget(
rowNumber: 1,
callback: () {},
),
],
),
),


);
}}
Within the ListView you remove the old Text widgets and adds 2 CategoryWidget. You
also pass rowNumber:0 for the first one and rowNumber: 1 for the second one. Currently the
callback function is empty.

Step 11: Create the "+ Add" Functionality

A user will click the pink +Add button new row will be added. To do that, let's add int
totalRow = 0; within the HomeScreenState

class_HomeScreenState extends State<HomeScreen> {


String title appTitle;
int totalRow = 0;

addRow function within the _HomeScreenState


class_HomeScreenState extends State< HomeScreen> {

void_addRow() {
setState(() {

totalRow += 1;
});
}

List View within the_HomeScreenWidget again: {

Widget build(BuildContext context)

return Scaffold(
body: SafeArea(

child: ListView(
children: [

for (int i = 0; i<totalRow; ++i)


Category Widget(
rowNumber: i,
callback: () {},

),
],
),
),

onPressed function of the floatingActionButton widget and add a reference of the_addRow


function.

...
floating ActionButton: FloatingActionButton.extended(
onPressed: _addRow,
label: Text('Add'),
icon.Icon(Icons.add),
background Color:Colors.pink,
),

.

Result :
A cross-platform Application for a simple expense manager is built which allows
entering expenses and income.
Date -
Exercise:4
Design and develop a Cross platform application for day to day task (to-do)
management.

Aim
The aim of this project is to design and develop a cross-platform task management
application using React Native that enables users to efficiently create, manage, and track their
daily to-do tasks. The application will allow users to:
 Add new tasks.
 Mark tasks as complete or incomplete.
 Categorize tasks.
 Store tasks locally for persistence between app sessions using AsyncStorage.
This project aims to provide a simple, user-friendly interface for managing personal or work-
related tasks, ensuring users can keep track of their daily responsibilities across Android, iOS,
and Web platforms.

Procedure
Step 1: Install Required Tools:

d) Install Node.js

e) Ensure java 17 or above is installed

f) Ensure npm is installed

Step 2: Setup your IDE. (Visual studio code is recommended.)


d) Install the plugins Live Server, babel JavaScript, Prettier – code and Es7 – react* in
Vs code
e) Cd to the Project Folder and open a cmd prompt here
f) Type code . to get the Vs code opened in the project folder
Step 3: Create your project .
Open terminal in VS Code from your project directory and run the following command

>> npx create-react-app day_to_day


Step 4: Directory day_to_day will be created. CD to the directory
Step 5: Run your application.
>> npm install react-native-web
>> npm start
Below default screen should be visible in browser if Application is successfully run,

Step 6: Add Data Persistence Using AsyncStorage to Install AsyncStorage to persist task data
even after the app is closed, run the below command in Vscode Terminal

npm install @react-native-async-storage/async-storage


Step 7: Open day_tgo_day/src/App.js and type code

import React, { useState, useEffect } from 'react';


import { View, Text, TextInput, Button, FlatList, StyleSheet } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';

const App = () => {

const [task, setTask] = useState('');


const [tasks, setTasks] = useState([]);

useEffect(() => {
loadTasks();
}, []);
useEffect(() => {
saveTasks();
}, [tasks]);

const saveTasks = async () => {


try {
const jsonValue = JSON.stringify(tasks);

await AsyncStorage.setItem('tasks', jsonValue);


} catch (e) {
console.log(e);

}
};

const loadTasks = async () => {


try {
const jsonValue = await AsyncStorage.getItem('tasks');
if (jsonValue != null) {
setTasks(JSON.parse(jsonValue));
}

} catch (e) {
console.log(e);
}
};

const addTask = () => {


if (task) {
setTasks([...tasks, { id: tasks.length.toString(), name: task, completed: false }]);

setTask('');
}
};

const toggleTaskComplete = (id) => {


setTasks(tasks.map(task =>
task.id === id ? { ...task, completed: !task.completed } : task

));
};

return (
<View style={styles.container}>

<Text style={styles.title}>To-Do List</Text>


<TextInput
style={styles.input}
placeholder="Add a new task"
value={task}
onChangeText={setTask}
/>

<Button title="Add Task" onPress={addTask} />

<FlatList
data={tasks}
keyExtractor={(item) => item.id}
renderItem={({ item }) => (
<View style={styles.taskItem}>
<Text

style={{
textDecorationLine: item.completed ? 'line-through' : 'none'
}}

>
{item.name}
</Text>
<Button
title={item.completed ? 'Undo' : 'Complete'}

onPress={() => toggleTaskComplete(item.id)}


/>

</View>
)}
/>
</View>
);

};

const styles = StyleSheet.create({


container: {

flex: 1,
padding: 20,

backgroundColor: '#f5f5f5'
},
title: {
fontSize: 24,
fontWeight: 'bold',

marginBottom: 20
},
input: {
borderWidth: 1,
borderColor: '#ccc',
padding: 10,

marginBottom: 20,
borderRadius: 5
},
taskItem: {
flexDirection: 'row',

justifyContent: 'space-between',
padding: 15,

backgroundColor: '#fff',
borderBottomWidth: 1,
borderBottomColor: '#eee'
}
});

export default App;


Result :
A cross platform application with React Native is build for day to day task (to-do)
management.
Date -
Experiment 5 :
Design an Android application using Cordova for a user login screen with username,
password, reset button and submit button. Also include a header image and a label, Use
layout managers

Aim:- Program to design an android application using Cordova for a user login screen with
username, password, reset button and a submit button. Also, include header image and a
label. Use layout managers.

Objective: Develop an Android application using Cordova to create a user-friendly


login screen with input fields for username and password, along with reset and submit
buttons. Additionally, include a header image and a label for enhanced visual appeal.

Theory: The aim of the program is to develop an Android application using Cordova
framework, featuring a user login screen. The login screen includes input fields for
username and password, along with buttons for resetting the form and submitting the
login details. Additionally, the application incorporates a header image and a label for
visual appeal. Layout managers are utilized to organize the elements on the screen
efficiently, ensuring a user-friendly interface.

Procedure:

Set Up Cordova Project: Ensure Cordova is installed, then create a new project
with cordova create.

Add Android Platform: Add the Android platform to the project using cordova
platform add android.

Design User Interface: Create an HTML file (index.html) for the login screen layout,
including input fields for username and password, along with reset and submit buttons.
Utilize CSS for styling.

Add JavaScript Functionality: Implement JavaScript functionality (index.js) for


resetting the form and handling form submission. Capture the input values and perform
necessary actions (e.g., logging credentials for demo purposes).

Build and Run: Build the Cordova project using cordova build android, then run it on an
Android device or emulator using cordova run android.

Test: Test the application to ensure the login screen functions as expected, allowing
users to input their credentials and submit the form.
Code

Set Up Your Cordova Project:


First, make sure you have Cordova installed. Then create a new Cordova project:
cordova create UserLoginApp com.example.userloginapp UserLoginApp

cd UserLoginApp

Add Android Platform:


Add Android platform to your Cordova project:

Create your HTML file with the login screen layout. You can use CSS for styling.

<!−− index.html −−>


<!DOCTYPE html>
<html>

<head>
<meta charset="utf−8" />
<meta name="viewport" content="width=device−width, initial−scale=1"
/>
<title>User Login</title>
<link rel="stylesheet" type="text/css" href="css/index.css" />
</head>

<body>
<div class="header">
<img src="header_image.png" alt="Header Image" />
<h1>Login</h1>
</div>

<div class="container">
<form id="loginForm">
<label for="username">Username:</label>
<input type="text" id="username" name="username" />
<label for="password">Password:</label>
<input type="password" id="password" name="password" />

<button type="button" onclick="resetForm()">Reset</button>


<button type="submit">Submit</button>
</form>
</div>

<script src="js/index.js"></script>
</body>

</html>
Css:
/* css/index.css */ body {
font−family: Arial, sans−serif;
}
.header {
text−align: center;
}

.container {
margin: 20px auto; width: 80%;
}
label {
display: block; margin−bottom: 5px;
}
input {
width: 100%; padding: 8px;
margin−bottom: 10px;
}
button {
padding: 10px; margin−top: 10px;
}
JavaScript Functionality:

Add JavaScript file for handling form submission and resetting.

// js/index.js
function resetForm() { document.getElementById("loginForm").reset();
}

document.addEventListener('deviceready', onDeviceReady, false);

function onDeviceReady() {
// Get the elements
const usernameField = document.getElementById('username');
const passwordField = document.getElementById('password');
const submitButton = document.getElementById('submitButton');
const resetButton = document.getElementById('resetButton');

// Submit button logic


submitButton.addEventListener('click', function () {
const username = usernameField.value;
const password = passwordField.value;

if (username && password) {


alert('Login successful!');
} else {
alert('Please fill in both fields');
}
});

// Reset button logic


resetButton.addEventListener('click', function () {
usernameField.value = '';
passwordField.value = '';
});
}
Build and Run Your App:
Build your Cordova project and run it on an Android device or emulator:

cordova build
cordova run android

Result :
An Android Application is built using Cordova for a user login screen with username
and password.
Date -

Exercise : 6
Design and develop an android application using Apache Cordova to find and display
the current location of the user.

Aim : To develop an android application using Apache Cordova to find and display the
current location of the user.

Procedure
Step 1 - Install Apache Cordova:
Run the following command to install Cordova globally:
npm install -g cordova
Step 2 - Create a New Cordova Project

In the terminal, create a new Cordova project using the following commands:
cordova create LocationApp com.example.locationapp LocationApp
cd LocationApp
Step 3 - Install the Geolocation Plugin
To access the device's location, install the Cordova geolocation plugin:
cordova plugin add cordova-plugin-geolocation

Step 4 - Add Android Platform


Now, add the Android platform to your Cordova project:

cordova platform add android


Step 5 - Modify index.html
Open the www/index.html file and modify it to create a user interface to display the
location.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-
scalable=no" />

<title>Location App</title>
</head>
<body>

<h1>Find My Location</h1>
<button onclick="getLocation()">Get Location</button>
<div id="locationOutput"></div>
<script type="text/javascript">
function getLocation() {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
// onSuccess Geolocation
function onSuccess(position) {

var latitude = position.coords.latitude;


var longitude = position.coords.longitude;
document.getElementById('locationOutput').innerHTML =
'Latitude: ' + latitude + '<br>' +
'Longitude: ' + longitude;

}
// onError Callback
function onError(error) {
document.getElementById('locationOutput').innerHTML = 'Error: ' +
error.message;
}
</script>

</body>
</html>
Step 6 - Build the Application
Run the following command to build the application for Android:
cordova build android
Run the Application on an Android Device
To run the app on a connected Android device or emulator, execute:
cordova run android

Result :
An Android Application is built using Cordova to find and display the current location
of user.
Date -
Exercise 7:
Design and implement a simple library management system using a switch statement in
java, where following operations are operated - Add a new classes', check out a book,
display specific book status, search specific book status and display book details using
different classes

Aim : To design and implement a simple Library Management System in Android using
Java and a switch statement for controlling operations, we can use Android Studio to create
the app which uses multiple classes that perform the following operations:

Add a new book.


Check out a book.
Display the status of a specific book.
Search for a specific book.

Display book details.


We’ll use Object-Oriented Programming (OOP) principles by creating different classes like
Book for individual book properties and LibraryManager for handling operations.

Procedure:
Step 1 - Project Setup

 Open Android Studio and create a new project with an Empty Activity.
 Name the project LibraryManagementSystem.

Step 2 - Create the Book Class


The Book class will store information about each book, such as its title, author, and status
(available or checked out).

Create Book.java in the java folder:


public class Book {

private String title;


private String author;
private boolean isAvailable;

public Book(String title, String author) {


this.title = title;
this.author = author;
this.isAvailable = true; // Book is available by default
}

public String getTitle() {


return title;
}

public String getAuthor() {


return author;

public boolean isAvailable() {


return isAvailable;
}

public void checkOutBook() {


isAvailable = false;
}

public void returnBook() {


isAvailable = true;
}

public void displayDetails() {


System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.println("Status: " + (isAvailable ? "Available" : "Checked Out"));
}
}

1) Create the LibraryManager Class

This class will manage the library’s operations, such as adding books, checking out, and
displaying statuses.

Create LibraryManager.java:

import java.util.ArrayList;

public class LibraryManager {

private ArrayList<Book> bookList;

public LibraryManager() {
bookList = new ArrayList<>();
}

public void addBook(String title, String author) {


Book newBook = new Book(title, author);
bookList.add(newBook);
System.out.println("Book added successfully: " + title);
}

public void checkOutBook(String title) {


for (Book book : bookList) {

if (book.getTitle().equalsIgnoreCase(title) && book.isAvailable()) {


book.checkOutBook();
System.out.println("Book checked out successfully: " + title);
return;
}
}
System.out.println("Book not available or not found.");
}

public void displayBookStatus(String title) {

for (Book book : bookList) {

if (book.getTitle().equalsIgnoreCase(title)) {
book.displayDetails();
return;

}
}
System.out.println("Book not found.");

public void displayAllBooks() {


if (bookList.isEmpty()) {
System.out.println("No books in the library.");
} else {
for (Book book : bookList) {
book.displayDetails();
System.out.println(" ---------------------- ");

}
}
}
}

Step 3 - Implement Switch Case Logic in MainActivity


The switch statement in the MainActivity will manage user interaction with the library
system, offering options to add a book, check out a book, or display statuses.
Modify MainActivity.java:

package com.example.librarymanagementsystem;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

LibraryManager libraryManager = new LibraryManager();

@Override

protected void onCreate(Bundle savedInstanceState) {


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

Button btnAddBook = findViewById(R.id.btnAddBook);


Button btnCheckoutBook = findViewById(R.id.btnCheckoutBook);
Button btnDisplayStatus = findViewById(R.id.btnDisplayStatus);
Button btnShowAllBooks = findViewById(R.id.btnShowAllBooks);

// Set up click listeners for each button to perform operations


btnAddBook.setOnClickListener(v -> performLibraryOperation(1));

btnCheckoutBook.setOnClickListener(v -> performLibraryOperation(2));


btnDisplayStatus.setOnClickListener(v -> performLibraryOperation(3));

btnShowAllBooks.setOnClickListener(v -> performLibraryOperation(4));


}

private void performLibraryOperation(int operation) {


String bookTitle = "1984";
String author = "George Orwell";
switch (operation) {
case 1:

// Add a new book


libraryManager.addBook(bookTitle, author);

Toast.makeText(this, "Book Added", Toast.LENGTH_SHORT).show();


break;
case 2:
// Check out a book
libraryManager.checkOutBook(bookTitle);

Toast.makeText(this, "Book Checked Out", Toast.LENGTH_SHORT).show();


break;
case 3:
// Display the status of a specific book

libraryManager.displayBookStatus(bookTitle);
Toast.makeText(this, "Displaying Book Status", Toast.LENGTH_SHORT).show();

break;
case 4:

// Show all books


libraryManager.displayAllBooks();
Toast.makeText(this, "Displaying All Books", Toast.LENGTH_SHORT).show();
break;
default:

Toast.makeText(this, "Invalid Operation", Toast.LENGTH_SHORT).show();


break;
}
}
}
Step 4 - Design the Main Screen Layout
Now let's create the main layout for the activity.

Open res/layout/activity_main.xml and design the layout:

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"

android:gravity="center">

<TextView
android:id="@+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Library Management System"

android:textSize="24sp"
android:layout_marginBottom="20dp"/>

<Button
android:id="@+id/btnAddBook"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:text="Add Book" />

<Button
android:id="@+id/btnCheckoutBook"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:text="Check Out Book"


android:layout_marginTop="10dp"/>

<Button

android:id="@+id/btnDisplayStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:text="Display Book Status"


android:layout_marginTop="10dp"/>

<Button

android:id="@+id/btnShowAllBooks"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show All Books"
android:layout_marginTop="10dp"/>

</LinearLayout>

Step 5 - Run the Application


Connect an emulator or a physical device.
Run the project in Android Studio.

You will see the main screen with buttons for the following operations:
Add Book
Check Out Book
Display Book Status
Show All Books
Upon interacting with the buttons, you’ll get feedback (via Toast) and view the results in the
Logcat.

Step 6 - Output in Logcat

For every operation, you will see relevant logs:


Adding a book will show: Book added successfully: 1984.

Checking out a book will display: Book checked out successfully: 1984.
Displaying a book's status will show details like title, author, and availability.

Result :
A simple LMS is Built in Android studio using a switch statement in java.

You might also like