[go: up one dir, main page]

0% found this document useful (0 votes)
16 views32 pages

App Development

Uploaded by

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

App Development

Uploaded by

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

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

Algorithm:
 The program initializes necessary variables to store user inputs, results, and categories.
 It prompts the user to enter their weight and height. If either is left blank, the program
will alert the user and stop further execution.
 The height input (in centimeters) is converted to meters.
 The BMI is calculated using the formula:
BMI=weight/height2
The result is then rounded to 2 decimal places.
 Based on the calculated BMI, the program assigns a category:
Underweight: BMI < 18.5
Normal weight: 18.5 ≤ BMI < 24.9
Overweight: 25 ≤ BMI < 29.9
Obese: BMI ≥ 30
 The program displays the calculated BMI and the corresponding category.
 The program terminates after displaying the result.

Program
import React, { useState } from 'react';
import { View, Text, TextInput, Button, StyleSheet, Alert } from 'react-native';
const App = () => {
const [weight, setWeight] = useState('');
const [height, setHeight] = useState('');
const [bmi, setBmi] = useState(null);
const [category, setCategory] = useState('');
const handleCalculateBMI = () => {
if (weight && height) {
// Convert weight to number and height to meters
const weightInKg = parseFloat(weight);
const heightInM = parseFloat(height) / 100;
// Calculate BMI
const calculatedBmi = weightInKg / (heightInM * heightInM);
// Set BMI value
setBmi(calculatedBmi.toFixed(2));
// Determine BMI category
let bmiCategory = '';
if (calculatedBmi < 18.5) {
bmiCategory = 'Underweight';
} else if (calculatedBmi >= 18.5 && calculatedBmi < 24.9) {
bmiCategory = 'Normal weight';
} else if (calculatedBmi >= 25 && calculatedBmi < 29.9) {
bmiCategory = 'Overweight';
} else {
bmiCategory = 'Obese';
}
setCategory(bmiCategory);
} else {
Alert.alert('Invalid input', 'Please enter valid values for both weight and height');
} };
return (
<View style={styles.container}>
<Text style={styles.title}>BMI Calculator</Text>
<TextInput
style={styles.input}
placeholder="Enter weight (kg)"
keyboardType="numeric"
value={weight}
onChangeText={setWeight}
/>
<TextInput
style={styles.input}
placeholder="Enter height (cm)"
keyboardType="numeric"
value={height}
onChangeText={setHeight}
/>
<Button title="Calculate BMI" onPress={handleCalculateBMI} />
{bmi && (
<View style={styles.resultContainer}>
<Text style={styles.result}>Your BMI: {bmi}</Text>
<Text style={styles.category}>Category: {category}</Text>
</View>
)}
</View>
);};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
padding: 16,
backgroundColor: '#f4f4f9',
},
title: {
fontSize: 24,
fontWeight: 'bold',
marginBottom: 20,
textAlign: 'center',
},
input: {
height: 40,
borderColor: '#ccc',
borderWidth: 1,
borderRadius: 5,
marginBottom: 20,
paddingLeft: 10,
},
resultContainer: {
marginTop: 20,
alignItems: 'center',
},
result: {
fontSize: 24,
fontWeight: 'bold',
},
category: {
fontSize: 18,
color: '#666',
},});
export default App;

Input:
Weight:70kg
Height: 175 cm
Output:
Your BMI: 22.86
Category: Normal weight

Result:
Ex No: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.

Algorithm
 User launches the app.
 If the transaction is valid (amount is provided), the transaction is added to the list.
 If the transaction is invalid (amount is missing), show an alert to ask for a valid input.
 Transactions are displayed in a list showing Date, Category, and Amount.
 Filter transactions from the past 7 days.
 Group them by category and calculate totals for income and expenses.
 The summary is displayed in a neat format showing total income and expense for each
category over the last week.
 The process repeats as the user continues to add new transactions or check the weekly
summary.

Program
import React, { useState } from 'react';
import { View, Text, TextInput, Button, StyleSheet, FlatList, Picker, Alert } from 'react-native';
const App = () => {
const [amount, setAmount] = useState('');
const [category, setCategory] = useState('Food');
const [type, setType] = useState('expense');
const [transactions, setTransactions] = useState([]);
// Define categories for expense/income
const categories = ['Food', 'Rent', 'Salary', 'Transport', 'Entertainment', 'Shopping', 'Other'];
const handleAddTransaction = () => {
if (!amount) {
Alert.alert('Input Error', 'Please enter an amount');
return;
}
const newTransaction = {
id: new Date().getTime().toString(),
amount: parseFloat(amount),
category,
type,
date: new Date().toLocaleDateString(),
};
setTransactions((prevTransactions) => [...prevTransactions, newTransaction]);
setAmount('');
};
const getWeeklySummary = () => {
// Get current date and filter transactions in the last 7 days
const oneWeekAgo = new Date();
oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);
const weeklyTransactions = transactions.filter((transaction) => {
const transactionDate = new Date(transaction.date);
return transactionDate >= oneWeekAgo;
});
// Calculate total income/expenses per category for the past week
const summary = {};
weeklyTransactions.forEach((transaction) => {
if (!summary[transaction.category]) {
summary[transaction.category] = { income: 0, expense: 0 };
}
if (transaction.type === 'expense') {
summary[transaction.category].expense += transaction.amount;
} else {
summary[transaction.category].income += transaction.amount;
}
});
return summary;
};
const renderTransactionItem = ({ item }) => (
<View style={styles.transactionItem}>
<Text>{item.date}</Text>
<Text>{item.category}</Text>
<Text>{item.type === 'expense' ? '-' : '+'} ${item.amount.toFixed(2)}</Text>
</View>
);
const renderWeeklySummary = () => {
const summary = getWeeklySummary();
return (
<View style={styles.summaryContainer}>
<Text style={styles.title}>Weekly Summary</Text>
{Object.keys(summary).map((category) => (
<View key={category} style={styles.summaryItem}>
<Text>{category}</Text>
<Text>Income: ${summary[category].income.toFixed(2)}</Text>
<Text>Expense: ${summary[category].expense.toFixed(2)}</Text>
</View>
))}
</View>
);
};
return (
<View style={styles.container}>
<Text style={styles.title}>Expense Manager</Text>
{/* Input form for adding daily expenses/income */}
<TextInput
style={styles.input}
placeholder="Enter Amount"
keyboardType="numeric"
value={amount}
onChangeText={setAmount}
/>
<Picker
selectedValue={category}
style={styles.picker}
onValueChange={(itemValue) => setCategory(itemValue)}
>
{categories.map((cat) => (
<Picker.Item key={cat} label={cat} value={cat} />
))}
</Picker>
<View style={styles.buttonContainer}>
<Button title="Add Expense" onPress={() => { setType('expense');
handleAddTransaction(); }} />
<Button title="Add Income" onPress={() => { setType('income');
handleAddTransaction(); }} />
</View>
{/* Display Transactions List */}
<FlatList
data={transactions}
renderItem={renderTransactionItem}
keyExtractor={(item) => item.id}
style={styles.transactionList}
/>
{/* Display Weekly Summary */}
{renderWeeklySummary()}
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'flex-start',
padding: 16,
backgroundColor: '#fff',
},
title: {
fontSize: 24,
fontWeight: 'bold',
textAlign: 'center',
marginBottom: 20,
},
input: {
height: 40,
borderColor: '#ccc',
borderWidth: 1,
borderRadius: 5,
marginBottom: 10,
paddingLeft: 10,
},
picker: {
height: 50,
width: '100%',
marginBottom: 20,
},
buttonContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
marginBottom: 20,
},
transactionItem: {
padding: 10,
borderBottomColor: '#ccc',
borderBottomWidth: 1,
},
transactionList: {
marginBottom: 20,
},
summaryContainer: {
marginTop: 20,
},
summaryItem: {
marginBottom: 10,
},});
export default App;

Output:
Weekly Summary:
----------------
Food:
Income: $0.00
Expense: $80.00

Rent:
Income: $0.00
Expense: $500.00

Salary:
Income: $3000.00
Expense: $0.00

Entertainment:
Income: $0.00
Expense: $20.00

Transport:
Income: $0.00
Expense: $100.00

Result
Ex No:3 Develop a cross platform application to convert units from imperial system to
metric system ( km to miles, kg to pounds etc.,)

Algorithm:
 Initialize the value, fromUnit, toUnit, and result state variables.
 Display fields to:
o Input the numeric value to be converted.
o Select the fromUnit and toUnit from a dropdown or picker list.
 User inputs a value and selects units.
 When the user presses the "Convert" button:
o If value is empty or non-numeric, show an alert to ask for valid input.
o If valid input is given:
 Check the fromUnit and toUnit combination.
 Use the corresponding conversion formula to compute the result.
 Update the result state with the converted value.
 Display the result in a formatted text:
o Example: "50 Kilometers is equal to 31.07 Miles".
 After displaying the result, the user can enter a new value and perform a new conversion
without resetting the app.
 The process repeats until the user closes the app or stops interacting with it.

import React, { useState } from 'react';


import { View, Text, TextInput, Button, Picker, StyleSheet } from 'react-native';
const App = () => {
const [value, setValue] = useState('');
const [fromUnit, setFromUnit] = useState('kilometers');
const [toUnit, setToUnit] = useState('miles');
const [result, setResult] = useState(null);
// Conversion logic
const handleConvert = () => {
if (!value) {
alert('Please enter a value to convert');
return;
}
const inputValue = parseFloat(value);
if (isNaN(inputValue)) {
alert('Please enter a valid number');
return;
}
let convertedValue;
if (fromUnit === 'kilometers' && toUnit === 'miles') {
convertedValue = inputValue * 0.621371;
} else if (fromUnit === 'miles' && toUnit === 'kilometers') {
convertedValue = inputValue / 0.621371;
} else if (fromUnit === 'kilograms' && toUnit === 'pounds') {
convertedValue = inputValue * 2.20462;
} else if (fromUnit === 'pounds' && toUnit === 'kilograms') {
convertedValue = inputValue / 2.20462;
} else if (fromUnit === 'celsius' && toUnit === 'fahrenheit') {
convertedValue = (inputValue * 9/5) + 32;
} else if (fromUnit === 'fahrenheit' && toUnit === 'celsius') {
convertedValue = (inputValue - 32) * 5/9;
} else if (fromUnit === 'liters' && toUnit === 'gallons') {
convertedValue = inputValue * 0.264172;
} else if (fromUnit === 'gallons' && toUnit === 'liters') {
convertedValue = inputValue / 0.264172;
} else {
alert('Invalid conversion');
return;
}
setResult(convertedValue.toFixed(2));
};
return (
<View style={styles.container}>
<Text style={styles.title}>Unit Converter</Text>
<TextInput
style={styles.input}
placeholder="Enter value"
keyboardType="numeric"
value={value}
onChangeText={setValue}
/>
<View style={styles.pickerContainer}>
<Text>From Unit</Text>
<Picker
selectedValue={fromUnit}
style={styles.picker}
onValueChange={(itemValue) => setFromUnit(itemValue)}
>
<Picker.Item label="Kilometers" value="kilometers" />
<Picker.Item label="Miles" value="miles" />
<Picker.Item label="Kilograms" value="kilograms" />
<Picker.Item label="Pounds" value="pounds" />
<Picker.Item label="Celsius" value="celsius" />
<Picker.Item label="Fahrenheit" value="fahrenheit" />
<Picker.Item label="Liters" value="liters" />
<Picker.Item label="Gallons" value="gallons" />
</Picker>
</View>
<View style={styles.pickerContainer}>
<Text>To Unit</Text>
<Picker
selectedValue={toUnit}
style={styles.picker}
onValueChange={(itemValue) => setToUnit(itemValue)}
>
<Picker.Item label="Miles" value="miles" />
<Picker.Item label="Kilometers" value="kilometers" />
<Picker.Item label="Pounds" value="pounds" />
<Picker.Item label="Kilograms" value="kilograms" />
<Picker.Item label="Fahrenheit" value="fahrenheit" />
<Picker.Item label="Celsius" value="celsius" />
<Picker.Item label="Gallons" value="gallons" />
<Picker.Item label="Liters" value="liters" />
</Picker>
</View>
<Button title="Convert" onPress={handleConvert} />
{result !== null && (
<View style={styles.resultContainer}>
<Text style={styles.resultText}>
{value} {fromUnit} is equal to {result} {toUnit}
</Text>
</View>
)}
</View>
);};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'flex-start',
padding: 20,
backgroundColor: '#fff',
},
title: {
fontSize: 24,
fontWeight: 'bold',
marginBottom: 20,
textAlign: 'center',
},
input: {
height: 40,
borderColor: '#ccc',
borderWidth: 1,
borderRadius: 5,
marginBottom: 20,
paddingLeft: 10,
},
pickerContainer: {
marginBottom: 20,
},
picker: {
height: 50,
width: '100%',
},
resultContainer: {
marginTop: 20,
alignItems: 'center',
},
resultText: {
fontSize: 18,
fontWeight: 'bold',
},});
export default App;
Output:
Converting Liters to Gallons
1. User Input:
o Value: 10
o From Unit: Liters
o To Unit: Gallons
2. Conversion Formula:
o Liters to Gallons = value * 0.264172
o Result: 10 * 0.264172 = 2.64
Ex No:4 Design and develop a cross platform application for day to day task (to-do)
management.

Algorithm:
 Wait for user input.
 Validate input (check if it is non-empty).
 Create a task object with:
 ID: A unique identifier.
 Title: The user-provided task description.
 Completed: Initially set to false.
 Add the new task to the current task list.
 Save the updated task list to local storage.
 On task completion (checkbox click):
 Toggle the completed status of the selected task.
 Update the task list in the state.
 Save the updated list to local storage.
 On delete (button click):
 Find the task in the list by ID.
 Remove the task from the list.
 Update the state and save the updated task list to local storage.
 On filter selection (e.g., All, Completed, Pending):
 Apply the filter logic to display the tasks that meet the selected condition.
 Update the UI to display the filtered tasks.

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


import { View, Text, TextInput, Button, FlatList, StyleSheet, TouchableOpacity, CheckBox }
from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
const App = () => {
const [tasks, setTasks] = useState([]);
const [task, setTask] = useState('');
const [filter, setFilter] = useState('all');
// Load tasks from AsyncStorage
useEffect(() => {
loadTasks();
}, []);
const loadTasks = async () => {
try {
const storedTasks = await AsyncStorage.getItem('tasks');
if (storedTasks) {
setTasks(JSON.parse(storedTasks));
}
} catch (error) {
console.log('Error loading tasks:', error);
} };
// Save tasks to AsyncStorage
const saveTasks = async (tasks) => {
try {
await AsyncStorage.setItem('tasks', JSON.stringify(tasks));
} catch (error) {
console.log('Error saving tasks:', error);
}
};
// Add a new task
const addTask = () => {
if (task.trim()) {
const newTask = {
id: Math.random().toString(),
title: task,
completed: false,
};
const updatedTasks = [...tasks, newTask];
setTasks(updatedTasks);
saveTasks(updatedTasks);
setTask('');
}
};
// Toggle task completion
const toggleTaskCompletion = (id) => {
const updatedTasks = tasks.map((task) => {
if (task.id === id) {
task.completed = !task.completed;
}
return task;
});
setTasks(updatedTasks);
saveTasks(updatedTasks);
};
// Delete a task
const deleteTask = (id) => {
const updatedTasks = tasks.filter((task) => task.id !== id);
setTasks(updatedTasks);
saveTasks(updatedTasks);
};
// Filter tasks
const filteredTasks = tasks.filter((task) => {
if (filter === 'completed') return task.completed;
if (filter === 'pending') return !task.completed;
return true; // Show all tasks
});
return (
<View style={styles.container}>
<Text style={styles.header}>To-Do List</Text>
<TextInput
style={styles.input}
value={task}
onChangeText={setTask}
placeholder="Enter task..."
/>
<Button title="Add Task" onPress={addTask} />
<View style={styles.filters}>
<Button title="All" onPress={() => setFilter('all')} />
<Button title="Completed" onPress={() => setFilter('completed')} />
<Button title="Pending" onPress={() => setFilter('pending')} />
</View>
<FlatList
data={filteredTasks}
keyExtractor={(item) => item.id}
renderItem={({ item }) => (
<View style={styles.taskItem}>
<CheckBox value={item.completed} onValueChange={() =>
toggleTaskCompletion(item.id)} />
<Text style={item.completed ? styles.completed : styles.pending}>{item.title}</Text>
<TouchableOpacity onPress={() => deleteTask(item.id)}>
<Text style={styles.delete}>Delete</Text>
</TouchableOpacity>
</View>
)}
/>
</View>
);};

const styles = StyleSheet.create({


container: {
flex: 1,
padding: 20,
backgroundColor: '#f4f4f4',
},
header: {
fontSize: 24,
fontWeight: 'bold',
textAlign: 'center',
marginBottom: 20,
},
input: {
height: 40,
borderColor: '#ccc',
borderWidth: 1,
borderRadius: 5,
marginBottom: 10,
paddingLeft: 10,
},
filters: {
flexDirection: 'row',
justifyContent: 'space-evenly',
marginBottom: 15,
},
taskItem: {
flexDirection: 'row',
alignItems: 'center',
marginVertical: 10,
},
completed: {
textDecorationLine: 'line-through',
color: 'gray',
marginLeft: 10,
flex: 1,
},
pending: {
marginLeft: 10,
flex: 1,
},
delete: {
color: 'red',
marginLeft: 10,
},});
export default App;

output:
Filter Buttons: [All] [Completed] [Pending]
Task List: - [✓] Buy groceries (completed)
- [ ] Read book (pending)
Ex No: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.

Algorithm
Initialize Cordova project.
Design the HTML structure for login screen with form elements.
Style the layout using CSS, implementing Flexbox for responsive design.
Write JavaScript functions to handle form submission and reset behavior.
Test on Android device via Cordova command.

Program:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Login</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="login-container">
<!-- Header Image -->
<img src="header-image.png" alt="Header Image" class="header-image" />
<!-- Login Form -->
<div class="form-container">
<label for="username">Username</label>
<input type="text" id="username" placeholder="Enter username">

<label for="password">Password</label>
<input type="password" id="password" placeholder="Enter password">
<!-- Buttons -->
<div class="button-container">
<button id="submit" onclick="submitLogin()">Submit</button>
<button id="reset" onclick="resetForm()">Reset</button>
</div>
</div>
<!-- Status Message Label -->
<label id="status" class="status-label"></label>
</div>
<script src="app.js"></script>
</body>
</html>

Style.css
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f4;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;}
.login-container {
background-color: white;
border-radius: 10px;
padding: 20px;
box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
width: 90%;
max-width: 400px;
}
.header-image {
width: 100%;
height: auto;
border-radius: 10px;
margin-bottom: 20px;
}
.form-container {
display: flex;
flex-direction: column;
gap: 15px;
}
label {
font-size: 16px;
font-weight: bold;
}
input {
padding: 10px;
font-size: 16px;
border-radius: 5px;
border: 1px solid #ccc;
}
.button-container {
display: flex;
justify-content: space-between;
gap: 10px;
}
button {
padding: 10px;
font-size: 16px;
border-radius: 5px;
cursor: pointer;
background-color: #007bff;
color: white;
border: none;
}
button:hover {
background-color: #0056b3;
}
.status-label {
text-align: center;
font-size: 16px;
color: green;}

App.js

// Function to handle form submission


function submitLogin() {
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
// Validate the input fields
if (username === '' || password === '') {
document.getElementById('status').innerText = 'Please fill in both fields.';
document.getElementById('status').style.color = 'red';
} else {
// Simulate successful login
document.getElementById('status').innerText = 'Login successful!';
document.getElementById('status').style.color = 'green';
// Handle further actions after successful login
// For example, you can redirect the user or load a different page
// window.location.href = "dashboard.html"; // Example
}
}
// Function to reset the form
function resetForm() {
document.getElementById('username').value = '';
document.getElementById('password').value = '';
document.getElementById('status').innerText = '';
}
Exno:6 Design and develop an android application using Apache Cordova to find and display the
current location of the user

Algorithm
 Initialize the HTML and CSS for the app.
 Add a button for Get Current Location.
 Prepare a section to display the latitude and longitude.
 Include the cordova.js and app.js files for functionality.
 Button Click Event (Get Location):
 Wait for the user to click the Get Current Location button.
 Retrieve Location:
 Use the navigator.geolocation.getCurrentPosition() method to get the location.
 If the location is successfully retrieved:
o Display the latitude and longitude in the HTML.
o Update the status message to "Location Retrieved Successfully".
 If there's an error:
o Show an error message such as "Unable to retrieve location" or "Permission
Denied".
 Handle Error Scenarios:
 If the user denies location permission, alert the user with "Location permission is
required to retrieve your location."
 If the device does not support geolocation or GPS is unavailable, display "Geolocation is
not supported by your device."
 End:
 After displaying the result, the app waits for the next interaction (button click) to get the
new location.

Program
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Location Finder</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<h1>Current Location</h1>
<button onclick="getLocation()">Get Current Location</button>
<div id="location">
<p><strong>Latitude:</strong> <span id="latitude">Not Available</span></p>
<p><strong>Longitude:</strong> <span id="longitude">Not Available</span></p>
</div>
</div>

<script src="cordova.js"></script>
<script src="app.js"></script>
</body>
</html>

Style.css
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f4;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
flex-direction: column;
}
.container {
text-align: center;
background-color: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
width: 90%;
max-width: 400px;
}
h1 {
font-size: 24px;
font-weight: bold;
margin-bottom: 20px;
}
button {
padding: 10px;
font-size: 16px;
border-radius: 5px;
cursor: pointer;
background-color: #007bff;
color: white;
border: none;
}
button:hover {
background-color: #0056b3;
}
#location p {
font-size: 18px;
margin-top: 10px;
}

App.js
// Function to get the current location
function getLocation() {
if (navigator.geolocation) {
// Use the geolocation API to get current position
navigator.geolocation.getCurrentPosition(onSuccess, onError);
} else {
// Geolocation is not supported by the browser/device
alert("Geolocation is not supported by this browser/device.");
}
}
// Success callback for geolocation
function onSuccess(position) {
// Get latitude and longitude from position object
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
// Display the location in the HTML
document.getElementById('latitude').textContent = latitude;
document.getElementById('longitude').textContent = longitude;
}
// Error callback for geolocation
function onError(error) {
alert("Error: " + error.message);
}

You might also like