0% found this document useful (0 votes)
32 views56 pages

ccs332 App Developement Student Manual

The document is a student lab manual for the App Development Laboratory course (CCS332) in the Department of Computer Science and Engineering, detailing the course objectives, syllabus, and a list of experiments. It includes instructions for building cross-platform applications using React Native and Apache Cordova, along with a focus on practical applications like a BMI calculator and expense manager. Additionally, it outlines the vision and mission of the college and department, along with program educational objectives and outcomes.
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)
32 views56 pages

ccs332 App Developement Student Manual

The document is a student lab manual for the App Development Laboratory course (CCS332) in the Department of Computer Science and Engineering, detailing the course objectives, syllabus, and a list of experiments. It includes instructions for building cross-platform applications using React Native and Apache Cordova, along with a focus on practical applications like a BMI calculator and expense manager. Additionally, it outlines the vision and mission of the college and department, along with program educational objectives and outcomes.
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/ 56

DEPARTMENT OF COMPUTER SCIENCE AND

ENGINEERING

CCS332-APP
APP DEVELOPMENT LABORATORY
Semester VI

Student Lab Manual


Regulation 2021

NAME: …………………………………………………….

REGISTER NUMBER: …………………………………………………….

DEPARTMENT: COMPUTER SCIENCE AND ENGINEERING

YEAR &SEM:
SEM: III &VI

SUBJECT: CCS332- APP DEVELOPMENT LABORATORY


LABORATOR
Name:………………………………………………………………………………

Year:……………….…Semester…………………Branch..…………………….

University Register No

CERTIFIED that this a Bonafide Record work done by the above Student in the

_______________________________________________________________________________

Laboratory during the year 20 - 20

Signature of Lab. In-charge Signature of Head of the Department

Submitted for practical examination held on_________________________

Internal Examiner External Examiner


TABLE OF CONTENTS

S. Particulars Page
No. No.
1 College vision and mission statement 3
2 Department Vision, Mission, POs, PEOs, PSOs 4
3 Lab syllabus 5
4 List of Experiments Mapping with COs, POs &PSOs 6
5 University prescribed lab experiments
1. Using react native, build a cross platform application for a
14
BMI calculator
2. Build a cross platform application for a simple expense
manager which allows entering Expenses and income on each 21
day and displays category wise weekly income and expense
3. Develop a cross platform application for unit converter. 30
4. Design and develop a cross platform application for day to
36
day task (to-do) management
5. Design an android application using Cordova for a user login
screen with username, Password, reset button and a submit
41
button. Also, include header image and a label. Use Layout
managers
6. Design and develop an android application using Apache
49
Cordova to find and display the Current location of the user
7. Write programs using Java to create Android application for
56
simple library management system
NPR COLLEGE OF ENGINEERING& TECHNOLOGY,NATHAM

VISION

 To develop students with intellectual curiosity and technical expertise to meet the global needs.

MISSION

 To achieve academic excellence by offering quality technical education using best


teaching techniques.
 To improve Industry– Institute interactions and expose industrial atmosphere.
 To develop interpersonal skills along with value based education in a dynamic learning
environment.
 To explore solutions for real time problems in the society.

3
NPR COLLEGE OF ENGINEERING & TECHNOLOGY,NATHAM

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VISION
 To produce globally competent technical professionals for digitized society.
MISSION
 To establish conducive academic environment by imparting quality education and value
added training.
 To encourage students to develop innovative projects to optimally resolve the challenging
social problems.

PROGRAM EDUCATIONAL OBJECTIVES

Graduates of Computer Science and Engineering Program will be able to:

 Develop into the most knowledgeable professional to pursue higher education and Research or have
a successful carrier in industries.
 Successfully carry forward domain knowledge in computing and allied areas to solve complex and
real world engineering problems.
• Meet the technological revolution they are continuously upgraded with the technical knowledge
.Serve the humanity with social responsibility combined with ethics

4
CCS332 APP DEVELOPMENT LTPC
2023

OBJECTIVES:
 To learn development of native applications with basic GUI Components
 To develop cross-platform applications with event handling
 To develop applications with location and data storage capabilities
 To develop web applications with database access

LIST OF EXPERIMENTS:

1. Using react native, build a cross platform application for a BMI calculator.
2. 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.
3. Develop a cross platform application to convert units from imperial system to metric system
(Km to miles, kg to pounds etc.,)
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 a submit button. Also, include 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. Write programs using Java to create Android application having Databases
● For a simple library application.
● For displaying books available, books lend, book reservation. Assume that student
Information is available in a database which has been stored in a database server.

TOTAL: 30 PERIODS
OUTCOMES:

On completion of this course, the students will be able to:


CO1: Develop Native applications with GUI Components.
CO2: Develop hybrid applications with basic event handling.
CO3: Implement cross-platform applications with location and data storage capabilities.
CO4: Implement cross platform applications with basic GUI and event handling.
CO5: Develop web applications with cloud database access.

5
APP DEVELOPMENT LABORATORY

List of Experiments with COs, Pos and PSOs

Exp.
Name of the Experiment COs POs PSOs
No.
1 Using react native, build a cross platform application 1,2
CO1 1,2,3,4,5,9.10.11
,9.10.11
for a BMI calculator.
2 Build a cross platform application for a simple
expense manager which allows entering
C04 1,2,3,4,5,9.10.11 1,2
Expenses and income on each day and displays
category wise weekly income
ome and expense
3 Develop a cross platform application to convert units
from imperial system to metric system
CO4 1,2,3,4,5,9.10.11 1,2
(Km to miles, kg to pounds etc.,)

4 Design and develop a cross platform application for


C04 1,2,3,4,5,9.10.11 1,2
day to day task (to-do)
do) management
5 Design an android application using Cordova for a
user login screen with username, Password, reset
button and a submit button. Also, includ
include header CO2 1,2,3,4,5,9.10.11
2,3,4,5,9.10.11 1,2
image and a label. Use Layout managers.

6 Design and develop an android application using


Apache Cordova to find and display the CO3 1,2,3,4,5,9.10.11 1,2
Current location of the user.
7 Write programs using Java to create Android
application having Databases
● For a simple library application.
● for displaying books available, books lend, book
CO5 1,2,3,4,5,9.10.11 1,2
reservation. Assume that student
Information is available in a database which has bbeen
stored in a database server

6
Program Outcomes

1. Engineering Knowledge 7.Environment and Sustainability


2. Problem Analysis 8.Ethics
3. Design/Development of Solutions 9. Individual and Team Work
4. Conduct Investigations of Complex Problems 10.Communication
5. Modern Tool Usage 11.Project Management and Finance
6. The Engineer and Society 12. Life-long Learning

Program Specific Outcomes

At the end of the program students will be able to


 Deal with real time problems by understanding the evolutionary changes in computing, applying
Standard practices and strategies in software project development using open-ended programming
environments.
 Employ modern computer languages, environments and platforms in creating innovative career
paths by inculcating moral values and ethics.
 Achieve additional expertise through add-on and certificate programs.

7
Installation Procedure:

1. Install Android Studio for getting Android Emulator by using the link
https://developer.android.com/studio?gclid=Cj0KCQiAoKeuBhCoARIsAB4WxtcGMRHkja88yHX
_RjtIdJ_WnhmK74E-PKdghIczx4s3YbEx8fLCkoEaAksFEALw_wcB&gclsrc=aw.ds
PKdghIczx4s3YbEx8fLCkoEaAksFEALw_wcB&gclsrc=aw.ds

2. In the mean time download JAVA JDK and JRE from the below lin
link.
k. Choose the bits based on your
system like 64-bit or 32-bit.

For JAVA JRE - https://www.java.com/en/download/

For JAVA JDK- https://www.oracle.com/in/java/technologies/downloads/#java8-windows


https://www.oracle.com/in/java/technologies/downloads/#java8

3. After Installing Android studio, Go to More Actions menu and click Virtual Device Manager for
creating an Emulator.

4. Then You will see the screen and go to create virtual device option. Then you need to select the
device based on your preference and click next. Then you need to select the OS for the chosen
Device and download it by clicking download symbol.

8
5. Let the OS gets download and once it is downloaded click Finish. Now select the downloaded OS
image and click next.

9
6. Then create a AVD name and click Finish. Now you can able to see the Emulator device that you
have created. Then click play button symbol to run the Emulator

10
7. Go to the link https://code.visualstudio.com/docs/?dv=win64user
https://code.visualstudio.com/docs/?dv=win64user,, download Visual Studio code.

8. Once download double double


double-click to Install VS code and accept the agreement.Select the

11
Destination folder and click next

9. After Installing VS code, Install Node JS using the below link


https://nodejs.org/en/download
https://nodejs.org/en/download. Download either 64-bit or 32-bit
bit depending on your system.

10. After Installing Node Js, open Command Prompt and type node –v
v or node –v to check the
version of Node Js whether it is installed or not. Then type the command
npm install –g expo-cli

11. Npm command is used to install Node Package manager. After installing npm, they type
npx create
create-expo-app <PROJECT NAME>.

12. After creating a project, Go to visual studio. In the top left corner, click the explorer menu. Then
click open Window and select created project folder in its destination folder.
13. You may see this window and click Yes, I trust the authors.

12
14. After this click the App.js file. In the top menu, click Terminal ->
> New Terminal
Inside the terminal type the command
npm run web - to run in browser
npm run android - to run in android emulator

then your output got displayed in the preferred interface.


15. Suppose you got an error while running in the web browser, then type npm install react-native-
react
web@~0.19.6, [email protected],
[email protected], @expo/metro
@expo/metro-runtime@~3.1.3 and give enter.

13
Ex No. 1
Using react native, build a cross platform application for a BMI calculator.

Aim:

To build a cross platform application for a BMI calculator using React native

Description:

Cross-platform Application:

A cross-platform mobile app is an application that is developed to work on multiple


mobile operating systems, such as Android and iOS, using a single codebase. Cross-platform
mobile apps can be developed using different frameworks or technologies, such as React
Native, Xamarin, Flutter, and others.

React js:

React's primary role in an application is to handle the view layer of that application just
like the V in a model-view-controller (MVC) pattern by providing the best and most efficient
rendering execution. Rather than dealing with the whole user interface as a single unit, React.

Node.js:

A cross-platform mobile app is an application that is developed to work on multiple


mobile operating systems, such as Android and iOS, using a single codebase. Cross-platform
mobile apps can be developed using different frameworks or technologies, such as React
Native, Xamarin, Flutter, and others.

Node Package Manager:

Node Package Manager provides two main functionalities: It provides online


repositories for node.js packages/modules which are searchable on search.nodejs.org. It also
provides a command line utility to install Node. The name npm (Node Package Manager)
stems from when npm first was created as a package manager for Node.js. All npm packages
are defined in files called package. Json. The content of package. Json must be written in
JSON. At least two fields must be present in the definition file: name and version.

BMI Calculation:

Body Mass Index is a simple calculation using a person’s height and weight. The
formula is BMI = kg/m2 where kg is a person’s weight in kilograms and m2 is their height in
meters squared. A BMI of 25.0 or more is overweight, while the healthy range is 18.5 to 24.9.
BMI applies to most adults 18-65 years.Metric Formula
weight (kg) / [height (m)]2
Or
[weight (kg) / height (cm) / height (cm)] x 10,000

14
Program:
App.js
import { StyleSheet, Text, View } from 'react-native';
import BmiCalculator from './src';

export default function App() {


return (
<View style={styles.container}>
<BmiCalculator/>
</View>
);
}

const styles = StyleSheet.create({


container: {
flex: 1,
},
});

Index.js
import { View, Text, StyleSheet,TextInput,TouchableOpacity} from 'react-native'
import React, {useState} from 'react'
import Constants from 'expo-constants'

constBmiCalculator = () => {
const [weight, setweight]= useState('')
const [height, setheight]= useState('')
const [bmi,setbmi]= useState('')
const [description,setdescription]= useState('')

constcalculateBMI = () => {
constbmi=weight/((height/100)*(height/100))
setbmi(bmi.toFixed(1))

if(bmi<18.5){
setdescription('Underweight, Eat More!!!')
}
else if(bmi>=18.5 &&bmi<=24.9){
15
setdescription('Normal, Keep it up and stay healthy')
}
else if(bmi>= 25 &&bmi<= 29.9)
{
setdescription('Overweight,Start doing exercises!!')
}
else{
setdescription('Obese, Work hard in Gym!!')
}
}
return (
<View style={styles.container}>
<View style={styles.title}>
<Text style={styles.titleText}>BMI Calculator</Text>
</View>
<TextInput
style={styles.input}
value={weight}
onChangeText={(text) =>setweight(text)}
placeholder='Weight in Kg'
keyboardType='numeric'
/>
<TextInput
style={styles.input}
value={height}
onChangeText={(text) =>setheight(text)}
placeholder='Height in Cm'
keyboardType='numeric'
/>
<TouchableOpacity
style={styles.button}
onPress={calculateBMI}
>
<Text style={styles.buttonText}>calculate</Text>
</TouchableOpacity>
<View style={styles.resultView}>
<Text style={styles.result}>{bmi}</Text>
<Text style={styles.result}>{description}</Text>

16
</View>
</View>
)
}

export default BmiCalculator

const styles = StyleSheet.create({


container: {
flex: 1,
paddingTop: Constants.statusBarHeight,
backgroundColor:'#e0ecde'
},
title: {
backgroundColor:'#2c6975',
height:80,
justifyContent:'center',
alignItems:'center',
marginBottom:10
},
titleText:{
fontSize:30,
color:'#fff',
fontWeight:'bold'
},
input:{
height:55,
margin:15,
borderWidth:1/2,
padding:10,
borderRadius:5,
backgroundColor:'#cde0c9',
fontSize:18
},
button:{
height:55,
margin:15,
borderWidth:1/2,
padding:10,
17
borderRadius:5,
backgroundColor:'#68b2a0',
justifyContent:'center',
alignItems:'center'
},
buttonText:{
fontSize:20,
color:'#fff',
fontWeight:'bold'
},
resultView:{
margin:15
},
result:{
fontSize:25,
color:'#2c6975',
fontWeight:'bold'
}
});

18
Result:
Thus, the cross-platform application for the BMI calculator was built and executed successfully

19
Ex No. 2
Build a cross-platform application for a simple expense manager

Aim :

To 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.

Description:

Cross-platform Application:

A cross-platform mobile app is an application that is developed to work on multiple


mobile operating systems, such as Android and iOS, using a single codebase. Cross-platform
mobile apps can be developed using different frameworks or technologies, such as React
Native, Xamarin, Flutter, and others.

React js:

React's primary role in an application is to handle the view layer of that application just
like the V in a model-view-controller (MVC) pattern by providing the best and most efficient
rendering execution. Rather than dealing with the whole user interface as a single unit.

Node.js:

A cross-platform mobile app is an application that is developed to work on multiple


mobile operating systems, such as Android and iOS, using a single codebase. Cross-platform
mobile apps can be developed using different frameworks or technologies, such as React
Native, Xamarin, Flutter, and others.

Node Package Manager:

Node Package Manager provides two main functionalities: It provides online


repositories for node.js packages/modules which are searchable on search.nodejs.org. It also
provides a command line utility to install Node. The name npm (Node Package Manager)
stems from when npm first was created as a package manager for Node.js. All npm packages
are defined in files called package. Json. The content of package. Json must be written in
JSON. At least two fields must be present in the definition file: name and version.

Algorithm:

Step 1: Initialize state variables using `useState` for `transactions`, `amount`, `category`, and
`transactionType`.

Step 2: When the "Add income" button is clicked. Check if both `amount` and `category` fields
have values.

Step 3: If they do, then create a new transaction object with type, amount, category.
20
Step 4: Add this transaction to the `transactions` array using `setTransactions`.

Step 5: Reset `amount` and `category` to empty strings. Then calculate WeeklyReport
function.

Step 6: Group transactions by category, summing their income and expenses separately.

Step 7: Construct an object containing categories with their respective income and expensesfor
the week.

Step 8: Display input fields for `amount`, `category`, and a dropdown for `transactionType`.

Step 9: Allow users to input values for these fields. Provide an "Add Transaction" button to
add transactions based on user input.

Step 10: Show a categorized list of income and expenses for the week, generated from
calculateWeeklyReport`.

Program:
App.js
import { useState } from "react";
import {
View,
Text,
Button,
StyleSheet,
TextInput,
TouchableOpacity,
} from "react-native";

constExpenseManager = () => {
const [category, setCategory] = useState("Grocery");
const [amount, setAmount] = useState("");
const [income, setIncome] = useState("");
const [expenses, setExpenses] = useState([]);
const [showDropdown, setShowDropdown] = useState(false);
const [weeklyIncome, setWeeklyIncome] = useState(0);

consthandleAddExpense = () => {
constnewExpense = {
category,

21
amount: parseFloat(amount),
};
setExpenses([...expenses, newExpense]);
setAmount("");
};

consttotalWeeklyIncome = () => {
const a = parseFloat(income) + parseFloat(weeklyIncome);
setWeeklyIncome(a);
};

constcategoryExpenses = () => {
constcategoryExpenses = {};
expenses.forEach((expense) => {
if (categoryExpenses[expense.category]) {
categoryExpenses[expense.category] += expense.amount;
} else {
categoryExpenses[expense.category] = expense.amount;
}
});
return categoryExpenses;
};

consttoggleDropdown = () => {
setShowDropdown(!showDropdown);
};

constselectCategory = (selectedCategory) => {


setCategory(selectedCategory);
setShowDropdown(false);
};

return (

22
<View style={styles.container}>
<Text style={styles.title}>Expense Manager</Text>
<View style={styles.inputContainer}>
<TextInput
style={styles.input}
value={income}
onChangeText={setIncome}
placeholder="Enter Today Income"
keyboardType="numeric"
/>
<Button title="Add Income" onPress={totalWeeklyIncome} />
<TouchableOpacity
style={styles.dropdownButton}
onPress={toggleDropdown}
>
<Text style={styles.dropdownButtonText}>Category: {category}</Text>
</TouchableOpacity>
{showDropdown&& (
<View style={styles.dropdown}>
<TouchableOpacityonPress={() =>selectCategory("Grocery")}>
<Text style={styles.dropdownOption}>Grocery</Text>
</TouchableOpacity>
<TouchableOpacityonPress={() =>selectCategory("Utilities")}>
<Text style={styles.dropdownOption}>Utilities</Text>
</TouchableOpacity>
<TouchableOpacityonPress={() =>selectCategory("Transportation")}>
<Text style={styles.dropdownOption}>Transportation</Text>
</TouchableOpacity>
<TouchableOpacityonPress={() =>selectCategory("Entertainment")}>
<Text style={styles.dropdownOption}>Entertainment</Text>
</TouchableOpacity>
</View>
)}

23
<TextInput
style={styles.input}
value={amount}
onChangeText={setAmount}
placeholder="Enter Expense Amount"
keyboardType="numeric"
/>
<Button title="Add Expense" onPress={handleAddExpense} />
</View>
<View style={styles.summaryContainer}>
<View style={styles.summary}>
<Text style={styles.summaryTitle}>Weekly Income:</Text>
<Text style={styles.summaryValue}>Rs.{weeklyIncome}</Text>
</View>
<Text style={styles.summaryTitle}>Weekly Expense by Category:</Text>
{Object.keys(categoryExpenses()).map((cat) => (
<View key={cat} style={styles.summary}>
<Text style={styles.summaryCategory}>{cat}:</Text>
<Text style={styles.summaryValue}>
Rs.{categoryExpenses()[cat]}
</Text>
</View>
))}
</View>
</View>
);
};

const styles = StyleSheet.create({


container: {
flex: 1,
justifyContent: "center",
alignItems: "center",

24
backgroundColor: "#f0f0f0",
},
inputContainer: {
backgroundColor: "#fff",
padding: 20,
borderRadius: 10,
marginBottom: 20,
width: "90%",
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 2,
},
shadowOpacity: 0.25,
shadowRadius: 3.84,
elevation: 5,
},
title: {
fontSize: 24,
fontWeight: 'bold',
marginBottom: 20,
},
input: {
height: 40,
borderColor: "gray",
borderWidth: 1,
marginBottom: 10,
paddingHorizontal: 10,
},
dropdownButton: {
height: 40,
backgroundColor: "#e3e3e3",
justifyContent: "center",

25
alignItems: "center",
marginBottom: 10,
borderRadius: 5,
marginTop: 10,
},
dropdownButtonText: {
fontSize: 16,
},
dropdown: {
backgroundColor: "#f9f9f9",
borderColor: "gray",
borderWidth: 1,
borderRadius: 5,
paddingHorizontal: 10,
marginBottom: 10,
},
dropdownOption: {
fontSize: 16,
paddingVertical: 5,
},
summaryContainer: {
backgroundColor: "#fff",
padding: 20,
borderRadius: 10,
width: "90%",
},
summary: {
flexDirection: "row",
justifyContent: "space-between",
marginBottom: 5,
},
summaryTitle: {
fontSize: 16,

26
fontWeight: "bold",
},
summaryCategory: {
flex: 1,
fontSize: 16,
},
summaryValue: {
fontSize: 16,
color: "#007bff",
},
});

export default ExpenseManager;

Result:
Thus, the cross-platform application for the Expense Manager was built and executed
successfully.

27
Ex No. 3
Develop a cross platform application to convert units from imperial
system to metric system

Aim:

To develop a cross platform application for a simple metric conversion which allows
entering units conversion from imperial system to metric system.

Description:

Cross-platform Application:

A cross-platform mobile app is an application that is developed to work on multiple


mobile operating systems, such as Android and iOS, using a single codebase. Cross-platform
mobile apps can be developed using different frameworks or technologies, such as React
Native, Xamarin, Flutter, and others.

Unit Conversion:
For many factors, the metric system is the preferred scientific unit system.
● The metric method of measurement is used by most countries in the world.
● They are easily converted by shifting the decimal point since metric units are decimal-
based.
● The metric system is designed to make it easy to perform and understand
measurements and calculations, which is one of the key reasons scientists use it.
Algorithm:

Step 1: Initialize Project : Set up a cross-platform application using a framework like React
Native.

Step 2: Design UI : Create components for entering daily expenses and income
(amount,category, date).

Step 3: Manage Data : Implement state management to store and organize user entered expense
and income data.

Step 4: Calculate Weekly Summary : Write functions to aggregate and categorize daily
expenses and income into a weekly view.

Step 5: Display Category-wise Summary : Show category-wise totals for weekly income and
expenses in an organized format.

Step 6: Apply Styling : Apply styles for an intuitive and visually appealing interface.

Step 7: Testing and Validation:Thoroughly test the app to ensure accurate calculations and
functionality.

Step 8: Deployment : Prepare the app for deployment on iOS and Android platforms.

28
Step 9: Publishing : Publish the app on app stores or distribute it through suitable channels.

Program:
App.js
import React, { useState } from 'react';
import { View, Text, TextInput, TouchableOpacity, StyleSheet } from 'react-native';
import RNPickerSelect from 'react-native-picker-select';
const Converter = () => {
const [inputValue, setInputValue] = useState('');
const [selectedUnit, setSelectedUnit] = useState('km');
const [convertedValue, setConvertedValue] = useState('');
const [unitType, setUnitType] = useState('distance');
constconvertUnits = () => {
const value = parseFloat(inputValue);
if (isNaN(value)) {
setConvertedValue('Invalid input');
return;
}
let result;
if (unitType === 'distance') {
if (selectedUnit === 'km') {
// Convert kilometers to miles
constconversionRate = 0.621371; // 1 km = 0.621371 miles
result = value * conversionRate;
} else if (selectedUnit === 'mi') {
// Convert miles to kilometers
constconversionRate = 1.60934; // 1 mi = 1.60934 km
result = value * conversionRate;
}
} else if (unitType === 'weight') {
if (selectedUnit === 'kg') {
// Convert kilograms to pounds
constconversionRate = 2.20462; // 1 kg = 2.20462 pounds
result = value * conversionRate;
} else if (selectedUnit === 'lbs') {
29
// Convert pounds to kilograms
constconversionRate = 0.453592; // 1 lb = 0.453592 kg
result = value * conversionRate;
}
}
setConvertedValue(result.toFixed(2));
};
return (
<View style={styles.container}>
<Text style={styles.header}>Unit Converter</Text>
<TextInput
style={styles.input}
placeholder="Enter value"
keyboardType="numeric"
value={inputValue}
onChangeText={(text) =>setInputValue(text)}
/>
<RNPickerSelect
placeholder={{ label: 'Select Type', value: null }}
onValueChange={(value) =>setUnitType(value)}
items={[
{ label: 'Distance', value: 'distance' },
{ label: 'Weight', value: 'weight' },
]}
style={{
inputIOS: styles.pickerInput,
inputAndroid: styles.pickerInput,
}}
/>
<RNPickerSelect
placeholder={{ label: 'Select Unit', value: null }}
onValueChange={(value) =>setSelectedUnit(value)}
items={unitType === 'distance' ? [

30
{ label: 'Kilometers (km)', value: 'km' },
{ label: 'Miles (mi)', value: 'mi' },
]:[
{ label: 'Kilograms (kg)', value: 'kg' },
{ label: 'Pounds (lbs)', value: 'lbs' },
]}
style={{
inputIOS: styles.pickerInput,
inputAndroid: styles.pickerInput,
}}
/>
<TouchableOpacity style={styles.convertButton} onPress={convertUnits}>
<Text style={styles.convertButtonText}>Convert</Text>
</TouchableOpacity>
<Text style={styles.result}>Converted Value: {convertedValue}</Text>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
justifyContent: 'center',
backgroundColor: '#3498db',
},
header: {
fontSize: 24,
color: 'white',
marginBottom: 20,
},
input: {
height: 40,
borderColor: 'white',

31
borderWidth: 1,
color: 'white',
marginBottom: 20,
padding: 10,
},
pickerInput: {
height: 40,
borderColor: 'white',
borderWidth: 1,
color: 'white',
marginBottom: 20,
padding: 10,
},
convertButton: {
backgroundColor: '#2980b9',
padding: 10,
borderRadius: 5,
},
convertButtonText: {
color: 'white',
textAlign: 'center',
},
result: {
color: 'white',
fontSize: 18,
marginTop: 20,
},
});
export default Converter;

32
Result:
Thus, the cross-platform application for the conversion of units from imperial system to
metric system was developed and executed successfully.

33
Ex No. 4
Design and develop a cross platform application for day to day task (to-do)
management

Aim :

To develop a cross platform application for managing a day to day task of our daily life.

Description:

Cross-platform Application:

A cross-platform mobile app is an application that is developed to work on multiple


mobile operating systems, such as Android and iOS, using a single codebase. Cross-platform
mobile apps can be developed using different frameworks or technologies, such as React
Native, Xamarin, Flutter, and others.

Algorithm:

Step 1: Initialize State: - Initialize the state variables task and tasks using the useState hook.

Step 2: Add Task:


● Create the addTask function to add a new task to the tasks array.
● Check if the task is not empty before adding.
● Update the state with the new task and reset the input.

Step 3: Remove Task:

● Create the removeTask function to remove a task from the tasks array.
● Use the filter method to create a new array excluding the task with the
specified taskId.
● Update the state with the new array.

Step 4: Render UI:

● Render the UI with input fields, buttons, and the task list.
● Map through the tasks array to display each task along with a remove button

Step 5: Styles: - Define the styles object for consistent styling throughout the application

Step 6: Component Structure: - The `App` component is the main entry point and encapsulates
the entire application structure.

Step 7: Execution: - Ensure the required React Native components and environment are
properly set up to run the app.

34
Program:
App.js

import React, { useState } from 'react';


import { View, TextInput, Button, FlatList, StyleSheet, TouchableOpacity, Text } from
'react-native';
const App = () => {
const [task, setTask] = useState('');
const [tasks, setTasks] = useState([]);
constaddTask = () => {

if (task.trim() !== '') {


setTasks([...tasks, { id: Date.now().toString(), text: task, completed: false }]);
setTask('');
}
};

consttoggleTask = (taskId) => {


setTasks((prevTasks) =>
prevTasks.map((t) =>
t.id === taskId ? { ...t, completed: !t.completed } : t
)
);
};

constrenderItem = ({ item }) => (

<TouchableOpacity
style={styles.taskItem}
onPress={() =>toggleTask(item.id)}
>
<View style={[styles.checkbox, { borderColor: item.completed ? 'gray' : 'black' }]}>

35
{item.completed&&<View style={styles.checkmark} />}
</View>

<Text style={[styles.taskText, { textDecorationLine: item.completed ? 'line-through' :


'none' }]}>
{item.text}
</Text>
</TouchableOpacity>
);

return (

<View style={styles.container}>
<TextInput
style={styles.input}
placeholder="Add a new task"
value={task}
onChangeText={(text) =>setTask(text)}
/>
<Button title="Add" onPress={addTask} />
<FlatList
data={tasks}
renderItem={renderItem}
keyExtractor={(item) =>item.id}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 16,
marginTop:50,
},

36
input: {
height: 40,
borderColor: 'gray',
borderWidth: 1,
marginBottom: 8,
paddingHorizontal: 8,
},
taskItem: {
flexDirection: 'row',
alignItems: 'center',

marginVertical: 8,
},
checkbox: {
width: 20,
height: 20,
borderWidth: 1,
marginRight: 8,
alignItems: 'center',
justifyContent: 'center',
},
checkmark: {
width: 5,
height: 10,
borderBottomWidth: 2,
borderRightWidth: 2,

transform: [{ rotate: '45deg' }],


},
taskText: {
marginLeft: 8,},});

export default App;

37
Result:
Thus, the cross-platform application for the management of daily task application was built
and executed successfully.

38
Ex No. 5
Design an android application using Cordova for a user login screen with
layout managers

Aim :

To develop an android application for a simple User login page with username, password,
reset button and a submit button with the use of layout managers using Cordova.

Description:

Android Application:
Android applications are organized as a collection of components. There are four
types of components, and applications can be composed of one or more of each type. A
dynamic instance of a component corresponds to an application subset that can be executed
independently of the others. So, in many ways, an Android application can be thought of as a
collection of interacting components. Android application components come in four flavors:

● Activities. User-facing components that implement display and input capture.

● Services. Background components that operate independent of any user-visible


activity.

● Broadcast receivers. A component that listens for and responds to system-wide


broadcast announcements.

● Content providers. Components that make application data accessible to external


applications and system components.

Cordova:

Cordova is an open-source mobile development framework. It allows you to use


standard web technologies such as HTML5, CSS3, and JavaScript for cross-platform
development, avoiding each mobile platforms' native development language. Applications
execute within wrappers targeted to each platform, and rely on standards-compliant API
bindings to access each device's sensors, data, and network status.

Use Cordova if you are:

● a mobile developer and want to extend an application across more than one platform,
without having to re-implement it with each platform's language and tool set.
● a web developer and want to deploy a web app that's packaged for distribution in
various app store portals.
39
● a mobile develop

● per interested in mixing native application components with a WebView (browser


window) that can access device-level APIs, or if you want to develop a plugin
interface between native and WebView components.

Algorithm:
Step 1: Setup Cordova Project : Create a new Cordova project using the Cordova CLI.
Step 2: Design User Interface : Use HTML, CSS, and JavaScript to design the login screen.
Include HTML elements for username input, password input, reset button, submit button,
header image, and label.
Step 3: Reset Button Functionality : Write JavaScript logic to reset the input fields when
the reset button is clicked.
Step 4: Submit Button Functionality : Implement JavaScript validation for the entered
username and password.
Step 5: Include Header Image and Label : Add an HTML element for the header image,
ensuring its proper placement and styling.
Step 6: Responsive Design : Ensure the layout and components are responsive and
compatible with various screen sizes and orientations using appropriate CSS and layout
management techniques.
Step 7: Testing and Validation : Test the login screen functionality on different devices and
screen sizes to ensure proper behavior.
Step 8: Integration with Cordova : Integrate the HTML, CSS, and JavaScript files into the
Cordova project structure.
Step 9: Build and Deployment : Build the Cordova application for the Android platform.
Deploy the application to an Android device or distribute it through appropriate channels

Program:
Code using Cordova:

<html>

<head>
<meta charset="utf-8">
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data:
https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data:
content:;">
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="initial-scale=1, width=device-width, viewport- fit=cover">
<meta name="color-scheme" content="light dark">
<link rel="stylesheet" href="css/index.css">
<title>Hello World</title>

40
<style>
body {
padding-top: 20px;
}

.header {

text-align: center;
}

.login-form {

max-width: 400px; margin: 0 auto;


}
</style>
</head>
<body>
<div class="app">
<div class="container">
<div class="header">
<h2>Login</h2>
</div>

<div class="login-form">

<form id="loginForm">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" placeholder="Enter your
username" required>
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" id="password" placeholder="Enter your
password" required>
</div>
<button type="button" class="btnbtn-link" id="resetButton">Reset</button>
<button type="submit" class="btnbtn-primary" id="submitButton">Submit</button>
</form>
</div>
</div>

41
</div>
<script>
document.addEventListener('deviceready', onDeviceReady, false);

function onDeviceReady() {

// Add your device ready code here if needed.


// For simplicity, we are not adding any device ready code in this example.
}
document.getElementById('resetButton').addEventListener('click', function () {

document.getElementById('username').value = ''; document.getElementById('password').value


= '';

});

document.getElementById('loginForm').addEventListener('submit', function (e) { e.preventDefault();

// Add your login logic here.

var username = document.getElementById('username').value; var password =


document.getElementById('password').value;

// Example: Check if the username and password are not empty if (username.trim() === '' ||
password.trim() === '') {
alert('Please enter both username and password.');
} else {
alert('Login successful!');
// Add your navigation logic to another page or perform further actions.
}
});
</script>
<script src="cordova.js"></script>
<script src="js/index.js"></script>
</body>
</html>

42
Code Using Flutter:
import 'package:flutter/material.dart';

void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Simple Login App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: LoginScreen(),
);
}
}
class LoginScreen extends StatelessWidget {
final TextEditingControllerusernameController = TextEditingController();
final TextEditingControllerpasswordController = TextEditingController();

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Login'),
),
body: Padding(
padding: constEdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [

43
TextField(
controller: usernameController,
decoration: InputDecoration(labelText: 'Username'),
),
SizedBox(height: 16),
TextField(
controller: passwordController,
obscureText: true,
decoration: InputDecoration(labelText: 'Password'),
),
SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
ElevatedButton(
onPressed: () {
// Reset button functionality goes here
usernameController.clear();
passwordController.clear();
},
child: Text('Reset'),
),
ElevatedButton(
onPressed: () {
String username = usernameController.text;
String password = passwordController.text;
if (username == 'user' && password == 'password') {
print('Login successful!');
} else {
print('Login failed. Please check your credentials.');
}
},
child: Text('Submit'),

44
),],),],),),);}
}

Result:
Thus, the android application using cordova for the User login screen was developed and
implemented successfully.

45
Ex No. 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 for finding the current location of
the user and also display the same.

Description:

Android Application:
Android applications are organized as a collection of components. There are four
types of components, and applications can be composed of one or more of each type. A
dynamic instance of a component corresponds to an application subset that can be executed
independently of the others. So, in many ways, an Android application can be thought of as a
collection of interacting components. Android application components come in four flavors:

● Activities. User-facing components that implement display and input capture.

● Services. Background components that operate independent of any user-visible


activity.

● Broadcast receivers. A component that listens for and responds to system-wide


broadcast announcements.

● Content providers. Components that make application data accessible to external


applications and system components.

Cordova:

Cordova is an open-source mobile development framework. It allows you to use


standard web technologies such as HTML5, CSS3, and JavaScript for cross-platform
development, avoiding each mobile platforms' native development language. Applications
execute within wrappers targeted to each platform, and rely on standards-compliant API
bindings to access each device's sensors, data, and network status.

Use Cordova if you are:

● a mobile developer and want to extend an application across more than one platform,
without having to re-implement it with each platform's language and tool set.
● a web developer and want to deploy a web app that's packaged for distribution in
various app store portals.
● a mobile developer interested in mixing native application components with a
46
WebView (browser window) that can access device-level APIs, or if you want to
develop a plugin interface between native and WebView components.

Algorithm:
Step 1: Initialize Cordova Project : Create a new Cordova project using the Cordova CLI.

Step 2: Add Geolocation Plugin : Use the Cordova CLI or npm to add the Geolocation plugin
to the project.Design.
Step 3:User Interface : Create UI elements to display the user's current location information
(latitude, longitude, address).
Step 4: Request Location Permission : Implement Cordova's Geolocation API to request
permission from the user to access their device location.
Step 5: Fetch User's Current Location : Write JavaScript code to retrieve the user's current
geolocation using the Geolocation plugin.
Step 6: Display Location Information : Update the UI elements with the retrieved location
information, displaying the latitude, longitude, and address (if available) to the user.
Step 7: Build and Deployment : Build the Cordova application specifically for the Android
platform.Deploy the application to an Android device or distribute it through suitable
channels.

Program:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-
scale=1, user-scalable=no">
<title>Location App</title>
<link rel="stylesheet" href="css/bootstrap.min.css" />
<link rel="stylesheet" href="css/location.css" />
<style> body {
padding-top: 20px;
}

.header {

text-align: center;
}
.location-info {
text-align: center; margin-top: 20px;
}
47
</style>
</head>
<body>
<div class="container">
<div class="header">
<h2>Current Location</h2>
</div>

<div class="location-info">

<p id="latitude">Latitude: </p>


<p id="longitude">Longitude: </p>
<button class="btnbtn-primary" id="getLocationButton">Get Location</button>
</div>
</div>
<script>
document.addEventListener('deviceready', onDeviceReady, false);
document.getElementById('getLocationButton').addEventListener('click', function ()
{
navigator.geolocation.getCurrentPosition(onSuccess, onError);
});
function onSuccess(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
document.getElementById('latitude').textContent = 'Latitude: ' + latitude;
document.getElementById('longitude').textContent = 'Longitude: ' + longitude;
}

function onError(error) {

alert('Error getting location: ' + error.message);


}

</script>

<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/location.js"></script>
</body>
</html>

48
Code using Flutter:
Dependencies
Open the pubspec.yaml file and add the geolocator package:
dependencies:
flutter:
sdk: flutter
geolocator: ^8.0.1

Code:
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: LocationScreen(),
);
}
}
class LocationScreen extends StatefulWidget {
@override
_LocationScreenStatecreateState() => _LocationScreenState();
}
class _LocationScreenState extends State<LocationScreen> {

String locationMessage = "";


@override
void initState() {
super.initState();
_getCurrentLocation();
}

49
Future<void> _getCurrentLocation() async {
try {
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high);
setState(() {
locationMessage =
"Latitude: ${position.latitude}, Longitude: ${position.longitude}";
});
} catch (e) {
print(e);

setState(() {
locationMessage = "Unable to fetch location";
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Location App"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [

Icon(Icons.location_on, size: 50),


SizedBox(height: 20),
Text(
locationMessage,
style: TextStyle(fontSize: 18),
),
],
50
),
),
);
}
}

Result:
Thus, the android application using cordova for finding the User location was developed
and implemented successfully.
51
Ex No. 7 write programs using Java to create Android application having Databases
for a simple library application.

Aim :

To develop an android application for the simple Library management system to display
books availability, books lend, book reservation using JAVA

Description:

Android Application:
Android applications are organized as a collection of components. There are four
types of components, and applications can be composed of one or more of each type. A
dynamic instance of a component corresponds to an application subset that can be executed
independently of the others. So, in many ways, an Android application can be thought of as a
collection of interacting components. Android application components come in four flavors:

● Activities. User-facing components that implement display and input capture.

● Services. Background components that operate independent of any user-visible


activity.

● Broadcast receivers. A component that listens for and responds to system-wide


broadcast announcements.

● Content providers. Components that make application data accessible to external


applications and system components.

Android database:

A database for Android is a form of persistent data storage intended for use in apps for
Android devices. It often consists of on-device, local storage so the app continues to be available
even if the device loses connectivity. Due to its inclusion in the Android Software Development Kit
(SDK), SQLite, an open-source relational database, is the most common database technology
associated with Android applications. For Android apps, SQLite is most often paired with Room, a
framework for managing the lifecycle of objects. However, as this article will go on to discuss, there
are other simpler options for modern mobile applications.

SQLite Database:

SQLite is an open source SQL database that stores data to a text file on a device. Android comes in
with built in SQLite database implementation.

SQLite supports all the relational database features. In order to access this database, you don't need to
establish any kind of connections for it like JDBC,ODBC e.t.c
52
Algorithm:

Step 1: Set Up Android Project : Create a new Android project in Android Studio for the
application.

Step 2: Design User Interface : Design the UI layout using XML in Android Studio,
incorporating RecyclerViews, TextViews, and Buttons for displaying book information.

Step 3: Database Connection Setup : Establish database connectivity using SQLite, Room, or
connect to an external database server by configuring connection parameters.

Step 4: Retrieve Book Data : Write Java code to query the database server, executing SQL
queries to fetch details about available, lent, and reserved books.

Step 5: Display Book Information : Populate UI components with the retrieved book data,
structuring the display using adapters and layouts.

Step 6: Implement Book Reservation and Lending : Enable users to reserve and lend books
via UI components, updating database records accordingly.

Step 7: Handle User Interactions : Implement event listeners or click handlers to manage user
interactions like viewing book details or performing book reservations.

Step 8: Error Handling and Validation : Implement error handling for database connectivity
issues and validate user actions to prevent invalid operations.

Step 9: Deployment : Build the Android application APK, test it on emulators or physical
devices, and deploy it on Android devices or distribution channels.

Program:

public class Book {


private int id;
private String title;
private String author;
private booleanisAvailable;
private booleanisLent;
private booleanisReserved;
}

import android.content.Context;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "LibraryDB";

private static final int DATABASE_VERSION = 1;


53
// Define table and column names

private static final String TABLE_BOOKS = "books";


private static final String COLUMN_ID = "id";
private static final String COLUMN_TITLE = "title";
private static final String COLUMN_AUTHOR = "author";
private static final String COLUMN_AVAILABLE = "available";
private static final String COLUMN_LENT = "lent";
private static final String COLUMN_RESERVED = "reserved";
private static final String CREATE_TABLE_BOOKS = "CREATE TABLE " +
TABLE_BOOKS + " (" + COLUMN_ID + " INTEGER PRIMARY KEY
AUTOINCREMENT," + COLUMN_TITLE + " TEXT," + COLUMN_AUTHOR + "
TEXT," + COLUMN_AVAILABLE + " INTEGER," + COLUMN_LENT + "
INTEGER," + COLUMN_RESERVED + " INTEGER)";

public DatabaseHelper(Context context) {

super(context, DATABASE_NAME, null, DATABASE_VERSION);


}

@Override

public void onCreate (SQLiteDatabasedb) { db.execSQL(CREATE_TABLE_BOOKS);


}
@Override
public void onUpgrade(SQLiteDatabasedb, intoldVersion, intnewVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_BOOKS);
onCreate(db);
}
}

ManiActivity:

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import java.util.List;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Example usage

BookRepositorybookRepository = new BookRepository(this);

// Add a book

Book newBook = new Book();


54
newBook.setTitle("Sample Book");
newBook.setAuthor("John Doe");
newBook.setAvailable(true);
newBook.setLent(false);
newBook.setReserved(false);
bookRepository.addBook(newBook);

// Get all books

List<Book>allBooks = bookRepository.getAllBooks();

// Now you can use the list of books as needed

}
}

Result:
Thus, the android application having Databases for displaying books available, books lend,
book reservation using Java was developed and implemented successfully.

55

You might also like