0% found this document useful (0 votes)
2 views

App Development Record(2024-25) (1)

The document outlines the development of multiple cross-platform applications using React Native, including a BMI calculator, expense manager, unit converter, and to-do management app. Each application includes an algorithm detailing the steps for user input handling, validation, and result display, along with the corresponding React Native code. The applications aim to provide essential functionalities such as calculating BMI, managing expenses, converting units, and organizing tasks.

Uploaded by

Surya Shaswat
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)
2 views

App Development Record(2024-25) (1)

The document outlines the development of multiple cross-platform applications using React Native, including a BMI calculator, expense manager, unit converter, and to-do management app. Each application includes an algorithm detailing the steps for user input handling, validation, and result display, along with the corresponding React Native code. The applications aim to provide essential functionalities such as calculating BMI, managing expenses, converting units, and organizing tasks.

Uploaded by

Surya Shaswat
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/ 46

EX NO: 1 CROSS PLATFORM APPLICATION FOR A BMI CALCULATOR

DATE:
AIM:
To develop an application using React Native, Build a cross platform application for a
bmi calculator.

ALGORITHM:
Step 1: Initialize state variables weight, height, bmi, and category using useState.
Step 2: Handle user input changes for weight and height.
Step 3: Validate input values to ensure they are numeric and greater than zero. If invalid,
show an alert.
Step 4: Convert height from centimeters to meters.
Step 5: Calculate BMI using the formula BMI = weight / (height²) and round it to one
decimal place.
Step 6: Determine the BMI category based on the calculated value.
Step 7: Display the BMI and category if the calculation is valid.
Step 8: Reset input fields and results when necessary.

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 calculateBMI = () => {


const h = parseFloat(height);
const w = parseFloat(weight);
if (!w || !h || h <= 0 || w <= 0) {
Alert.alert("Invalid Input", "Please enter valid numeric values for weight and height.");
return;
}

const heightInMeters = h / 100;


const bmiValue = (w / (heightInMeters * heightInMeters)).toFixed(1);
setBmi(bmiValue);

if (bmiValue < 18.5) setCategory("Underweight");


else if (bmiValue < 24.9) setCategory("Normal weight");
else if (bmiValue < 29.9) setCategory("Overweight");
else setCategory("Obese");
};

const resetBMI = () => {


setBmi(null);
setCategory("");
setWeight("");
setHeight("");
};

return (
<View style={styles.container}>
<Text style={styles.title}>BMI Calculator</Text>

<TextInput
style={styles.input}
placeholder="Enter weight (kg)"
placeholderTextColor="#999"
keyboardType="numeric"
value={weight}
onChangeText={(text) => {
setWeight(text);
if (text === "") resetBMI();
}}
/>

<TextInput
style={styles.input}
placeholder="Enter height (cm)"
placeholderTextColor="#999"
keyboardType="numeric"
value={height}
onChangeText={(text) => {
setHeight(text);
if (text === "") resetBMI();
}}
/>

<Button title="Calculate BMI" onPress={calculateBMI} color="#007BFF" />

{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",
alignItems: "center",
padding: 20,
backgroundColor: "#f5f5f5",
},
title: {
fontSize: 24,
fontWeight: "bold",
marginBottom: 20,
color: "#333",
},
input: {
width: "80%",
borderColor: "#ccc",
borderWidth: 1,
borderRadius: 5,
padding: 10,
marginBottom: 15,
backgroundColor: "#fff",
fontSize: 16,
color: "#000",
},
resultContainer: {
marginTop: 20,
alignItems: "center",

},
result: {
fontSize: 20,
fontWeight: "bold",
color: "#333",
},
category: {
fontSize: 18,
marginTop: 5,
color: "#666",
},
});
export default App;
OUTPUT:

RESULT:
EX NO: 2 SIMPLE EXPENSE MANAGER
DATE:

AIM:
To Develop an application using React-Native. Build a cross-platform application for a
BMI calculator.

ALGORITHM:
Step 1: Initialize state variables for transactions, category, amount, date, and summary.
Step 2: Handle user input for category, amount, and date.
Step 3: Validate input values to ensure all fields are filled, amount is positive, and date
format is correct.
Step 4: Create a new transaction object with a unique ID, category, amount, date, and
type (Income/Expense).
Step 5: Add the new transaction to the list and update the state.
Step 6: Update the income/expense summary based on the transaction type.
Step 7: Display the transaction list and summary of income and expenses.
Step 8: Reset input fields after adding a transaction.

PROGRAM:
import React, { useState } from "react";
import {
View,
Text,
TextInput,
Button,
FlatList,
StyleSheet,
Alert,
} from "react-native";
const App = () => {
const [transactions, setTransactions] = useState([]);
const [type, setType] = useState("Expense");
const [category, setCategory] = useState("");
const [amount, setAmount] = useState("");
const [date, setDate] = useState("");

const [summary, setSummary] = useState({ income: 0, expense: 0 });

// Add a new transaction


const addTransaction = (transactionType) => {
if (!category.trim() || !amount.trim() || !date.trim()) {
Alert.alert("Error", "Please fill in all fields.");
return;
}

if (isNaN(amount) || parseFloat(amount) <= 0) {


Alert.alert("Error", "Amount must be a positive number.");
return;
}

const dateRegex = /^\d{4}-\d{2}-\d{2}$/;


if (!dateRegex.test(date)) {
Alert.alert("Error", "Date must be in the format YYYY-MM-DD.");
return;
}

const newTransaction = {
id: Date.now().toString(),
type: transactionType, // Use passed argument instead of state
category: category.trim(),
amount: parseFloat(amount),
date,
};

setTransactions([...transactions, newTransaction]);
updateSummary(newTransaction);
resetFields();
};

// Update income/expense summary


const updateSummary = (transaction) => {
if (transaction.type === "Income") {
setSummary((prev) => ({
...prev,
income: prev.income + transaction.amount,
}));
} else {
setSummary((prev) => ({
...prev,
expense: prev.expense + transaction.amount,
}));
}
};

// Reset input fields


const resetFields = () => {
setCategory("");
setAmount("");
setDate("");
setType("Expense"); // Reset type to default
};

return (
<View style={styles.container}>
<Text style={styles.title}>Expense Manager</Text>

{/* Input Section */}


<TextInput
placeholder="Enter Category"
value={category}
onChangeText={setCategory}
style={styles.input}
placeholderTextColor="#999"
/>
<TextInput
placeholder="Enter Amount"
value={amount}
onChangeText={setAmount}
keyboardType="numeric"
style={styles.input}
placeholderTextColor="#999"
/>
<TextInput
placeholder="Enter Date (YYYY-MM-DD)"
value={date}
onChangeText={setDate}
style={styles.input}
placeholderTextColor="#999"
/>
<View style={styles.buttons}>
<Button
title="Add Expense"
color="red"
onPress={() => addTransaction("Expense")} // Pass type directly
/>
<Button
title="Add Income"
color="green"
onPress={() => addTransaction("Income")} // Pass type directly
/>

</View>

{/* Summary Section */}


<View style={styles.summary}>
<Text style={styles.summaryText}>
Income: ${summary.income.toFixed(2)}
</Text>
<Text style={styles.summaryText}>
Expense: ${summary.expense.toFixed(2)}
</Text>
</View>

{/* Transactions List */}


{transactions.length > 0 ? (
<FlatList
data={transactions}
keyExtractor={(item) => item.id}
renderItem={({ item }) => (
<View style={styles.transaction}>
<Text style={styles.transactionText}>
{item.date} - {item.category}: ${item.amount.toFixed(2)} (
{item.type})
</Text>
</View>
)}
/>
):(
<Text style={styles.noTransactionsText}>
No transactions added yet.
</Text>
)}
</View>
);
};

const styles = StyleSheet.create({


container: {
flex: 1,
padding: 20,
backgroundColor: "#f5f5f5",
},
title: {
fontSize: 24,
fontWeight: "bold",
marginBottom: 20,
textAlign: "center",
},
input: {
borderWidth: 1,
borderColor: "#ccc",
padding: 10,
marginVertical: 10,
borderRadius: 5,
backgroundColor: "#fff",
},
buttons: {
flexDirection: "row",
justifyContent: "space-between",
marginBottom: 20,
},
summary: {
marginVertical: 20,
padding: 10,
backgroundColor: "#fff",
borderRadius: 5,
elevation: 2,
},
summaryText: {
fontSize: 18,
fontWeight: "bold",
marginVertical: 5,
},
transaction: {
padding: 10,
borderBottomWidth: 1,
borderBottomColor: "#ccc",
},
transactionText: {
fontSize: 16,
},
noTransactionsText: {
textAlign: "center",
fontSize: 16,
color: "#666",
marginTop: 20,
},
});

export default App;

OUTPUT:

RESULT:
EX NO: 3 IMPERIAL SYSTEM TO METRIC SYSTEM
DATE:
AIM:
To Develop a cross platform App to convert units from imperial system to metric system.

ALGORITHM:
Step 1: Initialize state variables for input value, conversion type, and result.
Step 2: Define a conversion dictionary with functions for different unit conversions.
Step 3: Handle user input for entering a value.
Step 4: Allow users to select a conversion type using a dropdown (Picker).
Step 5: Validate the input to ensure it is a number.
Step 6: Perform the conversion based on the selected type and update the result.
Step 7: Display the converted result on the screen.
Step 8: Provide a button to trigger the conversion process.

PROGRAM:
import React, { useState } from "react";
import {
View,
Text,
TextInput,
Button,
StyleSheet,
} from "react-native";
import { Picker } from "@react-native-picker/picker";

const App = () => {


const [inputValue, setInputValue] = useState(""); // Input value to convert
const [conversionType, setConversionType] = useState("kmToMiles"); // Default conversion
type
const [result, setResult] = useState(""); // Converted value

const conversions = {
kmToMiles: (value) => (value * 0.621371).toFixed(2), // Kilometers to Miles
milesToKm: (value) => (value / 0.621371).toFixed(2), // Miles to Kilometers
kgToPounds: (value) => (value * 2.20462).toFixed(2), // Kilograms to Pounds
poundsToKg: (value) => (value / 2.20462).toFixed(2), // Pounds to Kilograms
cmToInches: (value) => (value * 0.393701).toFixed(2), // Centimeters to Inches
inchesToCm: (value) => (value / 0.393701).toFixed(2), // Inches to Centimeters
};

const handleConversion = () => {


if (!inputValue || isNaN(inputValue)) {
setResult("Please enter a valid number");
return;
}
const convertFunction = conversions[conversionType];
const convertedValue = convertFunction(parseFloat(inputValue));
setResult(`Converted Value: ${convertedValue}`);
};

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

{/* Input Field */}


<TextInput
style={styles.input}
placeholder="Enter value"
keyboardType="numeric"
value={inputValue}
onChangeText={setInputValue}
placeholderTextColor="#999"
/>

{/* Conversion Type Picker */}


<Text style={styles.label}>Select Conversion Type:</Text>
<View style={styles.pickerContainer}>
<Picker
selectedValue={conversionType}
onValueChange={(itemValue) => setConversionType(itemValue)}
style={styles.picker}
dropdownIconColor="#000" // Black arrow icon in app
mode="dialog" // Ensures proper dialog UI on Android
>
<Picker.Item label="Kilometers to Miles" value="kmToMiles" color="#FFF" />
<Picker.Item label="Miles to Kilometers" value="milesToKm" color="#FFF" />
<Picker.Item label="Kilograms to Pounds" value="kgToPounds" color="#FFF" />
<Picker.Item label="Pounds to Kilograms" value="poundsToKg" color="#FFF" />
<Picker.Item label="Centimeters to Inches" value="cmToInches" color="#FFF" />
<Picker.Item label="Inches to Centimeters" value="inchesToCm" color="#FFF" />
</Picker>
</View>

{/* Convert Button */}


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

{/* Display Result */}


{result ? <Text style={styles.result}>{result}</Text> : null}
</View>
);
};

const styles = StyleSheet.create({


container: {
flex: 1,
padding: 20,
backgroundColor: "#f5f5f5",
justifyContent: "center",
},
title: {
fontSize: 24,
fontWeight: "bold",
textAlign: "center",
marginBottom: 20,
},
input: {
borderWidth: 1,
borderColor: "#ccc",
padding: 10,
borderRadius: 5,
marginBottom: 20,
backgroundColor: "#fff",
},
label: {
fontSize: 16,
marginBottom: 10,
},
pickerContainer: {
backgroundColor: "#f5f5f5", // White background in main screen
},
picker: {
color: "#000", // Black text in main app
},
result: {
fontSize: 18,
fontWeight: "bold",
marginTop: 20,
textAlign: "center",
},
});
export default App;
OUTPUT:

RESULT:
EX NO: 4 TO-DO MANAGEMENT
DATE:
AIM:
Design and Develop A Cross Platform Application for Day to Day Task (To-Do)
Management.

ALGORITHM:

Step 1: Initialize state variables for input value, conversion type, and result.
Step 2: Define a dictionary of conversion functions for different unit conversions.
Step 3: Handle user input for entering a numeric value.
Step 4: Allow users to select a conversion type from a dropdown (Picker).
Step 5: Validate the input to ensure it is a valid number.
Step 6: Perform the selected conversion using the corresponding function.
Step 7: Display the converted result on the screen.
Step 8: Provide a button to trigger the conversion process.

PROGRAM:

import React, { useState } from "react";


import {
View,
Text,
TextInput,
Button,
StyleSheet,
} from "react-native";
import { Picker } from "@react-native-picker/picker";

const App = () => {


const [inputValue, setInputValue] = useState(""); // Input value to convert
const [conversionType, setConversionType] = useState("kmToMiles"); // Default conversion
type
const [result, setResult] = useState(""); // Converted value

const conversions = {
kmToMiles: (value) => (value * 0.621371).toFixed(2), // Kilometers to Miles
milesToKm: (value) => (value / 0.621371).toFixed(2), // Miles to Kilometers
kgToPounds: (value) => (value * 2.20462).toFixed(2), // Kilograms to Pounds
poundsToKg: (value) => (value / 2.20462).toFixed(2), // Pounds to Kilograms
cmToInches: (value) => (value * 0.393701).toFixed(2), // Centimeters to Inches
inchesToCm: (value) => (value / 0.393701).toFixed(2), // Inches to Centimeters
};

const handleConversion = () => {


if (!inputValue || isNaN(inputValue)) {
setResult("Please enter a valid number");
return;
}
const convertFunction = conversions[conversionType];
const convertedValue = convertFunction(parseFloat(inputValue));
setResult(`Converted Value: ${convertedValue}`);
};

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

{/* Input Field */}


<TextInput
style={styles.input}
placeholder="Enter value"
keyboardType="numeric"
value={inputValue}
onChangeText={setInputValue}
placeholderTextColor="#999"
/>

{/* Conversion Type Picker */}


<Text style={styles.label}>Select Conversion Type:</Text>
<View style={styles.pickerContainer}>
<Picker
selectedValue={conversionType}
onValueChange={(itemValue) => setConversionType(itemValue)}
style={styles.picker}
dropdownIconColor="#000" // Black arrow icon in app
mode="dialog" // Ensures proper dialog UI on Android
>
<Picker.Item label="Kilometers to Miles" value="kmToMiles" color="#FFF" />
<Picker.Item label="Miles to Kilometers" value="milesToKm" color="#FFF" />
<Picker.Item label="Kilograms to Pounds" value="kgToPounds" color="#FFF" />
<Picker.Item label="Pounds to Kilograms" value="poundsToKg" color="#FFF" />
<Picker.Item label="Centimeters to Inches" value="cmToInches" color="#FFF" />
<Picker.Item label="Inches to Centimeters" value="inchesToCm" color="#FFF" />
</Picker>
</View>

{/* Convert Button */}


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

{/* Display Result */}


{result ? <Text style={styles.result}>{result}</Text> : null}
</View>
);
};

const styles = StyleSheet.create({


container: {
flex: 1,
padding: 20,
backgroundColor: "#f5f5f5",
justifyContent: "center",
},
title: {
fontSize: 24,
fontWeight: "bold",
textAlign: "center",
marginBottom: 20,
},
input: {
borderWidth: 1,
borderColor: "#ccc",
padding: 10,
borderRadius: 5,
marginBottom: 20,
backgroundColor: "#fff",
},
label: {
fontSize: 16,
marginBottom: 10,
},
pickerContainer: {
backgroundColor: "#f5f5f5", // White background in main screen
},
picker: {
color: "#000", // Black text in main app
},
result: {
fontSize: 18,
fontWeight: "bold",
marginTop: 20,
textAlign: "center",
},
});
export default App;
OUTPUT:

RESULT:
EX.NO: 5 LAYOUT MANAGERS
DATE:
AIM:
To Develop the Layout Managers in an ADT bundle is to provide a flexible, dynamic, and
systematic way of arranging components (such as buttons, text fields, images, etc.) in a graphical
user interface.
ALGORITHM :
1. Create the file new and Click Android Project. Initialization Phase: Define Layout Type,
Assign Dimensions, Prepare Components.
2. In layouts, position components based on defined constraints or relationships to other
components.
3. For each component, calculate the x and y coordinates of the component inside the
container, depending on its layout type.
4. Draw Components:
Place each component in its assigned position, and render them based on the container’s
layout manager.
5. Create the button and text box for User name and password, and submit button.
6. Set the AVD
7. Save the project and run the project

PROGRAM
HTML
<!DOCTYPE html>
<html>
<head>
<title>User Login</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div class="container">
<img src="img/header_image.png" alt="Header Image" class="header-image">
<h1 class="login-title">Login</h1>
<form id="login-form" class="login-form">
<label for="username">Username:</label>
<input type="text" id="username" class="input-field" placeholder="Enter your
username">
<label for="password">Password:</label>
<input type="password" id="password" class="input-field" placeholder="Enter your
password">
<div class="button-container">
<button id="resetButton" class="reset-button">Reset</button>
<button id="submitButton" class="submit-button">Submit</button>
</div>
</form>
</div>
<script src="js/app.js"></script>
</body>
</html>
CSS
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f5f5f5;
}
.container {
background-color: #fff;
border-radius: 10px;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
padding: 20px;
width: 300px;
text-align: center;
}
.header-image {
max-width: 100%;
margin-bottom: 20px;
}
.login-title {
font-size: 24px;
margin-bottom: 20px;
}
.login-form {
display: flex;
flex-direction: column;
}
.input-field {
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}
.button-container {
display: flex;
justify-content: space-between;
margin-top: 20px;
}
.reset-button, .submit-button {
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}
.reset-button {
background-color: #e0e0e0;
}
.submit-button {
background-color: #007bff;
color: #fff;
}
JS
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
document.getElementById("resetButton").addEventListener("click", resetFields);
document.getElementById("submitButton").addEventListener("click", submitForm);
}
function resetFields() {
document.getElementById("username").value = "";
document.getElementById("password").value = "";
}
function submitForm() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username === "user" && password === "pass") {
alert("Login successful!");
} else {
alert("Invalid username or password. Please try again.");
}
}

RESULT:
EX.NO: 6. DISPLAY THE CURRENT LOCATION OF THE USER
DATE:
AIM:
To display the current geographical location (latitude and longitude) of the user's device in
real time.
ALGORITHM:
1. Initialize the Program: Set up the environment
2. Request Permission to Access Location: Before accessing the location, request the
necessary permissions from the user.
3. Access Device Location: Use platform-specific APIs to retrieve the user's current
location.
4. Handle the Location Data.
5. Show the obtained latitude and longitude on the user interface.
6. Display the latitude and longitude in a user-friendly format on the screen.

PROGRAM:
Manifestfile
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
GPSTracker.class
package com.example.gpsdemo;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
public class GPSTracker extends Service implements LocationListener
{
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context)
{
this.mContext = context;
getLocation();
}
public Location getLocation() {
try
{
locationManager(LocationManager)
mContext.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled =
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled)
{
// no network provider is enabled
} else
{
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled)
{
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null)
{
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled)
{
if (location == null)
{
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e)
{
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS()
{
if(locationManager != null)
{
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude()
{
if(location != null)
{
latitude = location.getLatitude();
}
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude()
{
if(location != null)
{
longitude = location.getLongitude();
}
return longitude;
}
/**
* Function to check GPS/wifi enabled
* @return boolean
* */
public boolean canGetLocation()
{
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
MainActivity.java
package com.example.gpsdemo;
import android.os.Bundle;
import android.app.Activity;
import android.view.*;
import android.location.*;
import android.content.Context;
import android.widget.*;
public class MainActivity extends Activity
{
Button btnShowLocation;
// GPSTracker class
GPSTracker gps;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnShowLocation = (Button) findViewById(R.id.button1);
btnShowLocation.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View arg0)
{
// create class object
gps = new GPSTracker(MainActivity.this);
// check if GPS enabled
if(gps.canGetLocation())
{
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude +
"\nLong: " + longitude, Toast.LENGTH_LONG).show();
}
else
{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
OUTPUT:
RESULT:

EX.NO: 7. DATABASE APPLICATION


DATE:

Aim:
To develop a Database Application using an Android Application, you can follow a structured
approach that involves designing, building, and deploying your application.
Algorithm:
1. Install Android Developer Tool.
2. Create a new project with an empty or basic activity.
3. Choose your project language (Java).
Database Selection
4. Option 1: SQLite (Local Database)
5. SQLite is built into Android and ideal for offline data storage.
6. Use SQLiteOpenHelper to create, manage, and upgrade your database.
PROGRAM:
Main activity java
package com.example.sqlapp;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.database.Cursor;
import android.view.*;
import android.widget.*;
public class MainActivity extends Activity
{ @Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button b1=(Button) findViewById(R.id.insert);
final Button b2=(Button) findViewById(R.id.selectall);
final Button b3=(Button) findViewById(R.id.select);
final Button b4=(Button) findViewById(R.id.update);
final Button b5=(Button) findViewById(R.id.delete);
final EditText et1=(EditText)findViewById(R.id.id);
final EditText et2=(EditText)findViewById(R.id.name);
final EditText et3=(EditText)findViewById(R.id.email);
final DBAdapter db = new DBAdapter(MainActivity.this);
//---Insert Contact---
b1.setOnClickListener(new View.OnClickListener( )
{ @Override
public void onClick(View v)
{ db.open();
db.insertContact(Integer.parseInt(et1.getText().toString()),et2.getText().toString(
),
et3.getText().toString());
db.close();
Toast.makeText(getBaseContext(), "Inserted",Toast.LENGTH_SHORT).show();
}
});
//---Select All contacts---
b2.setOnClickListener(new View.OnClickListener( )
{ @Override
public void onClick(View v)
{ db.open();
Cursor c = db.getAllContacts();
if (c.moveToFirst())
{ do {
DisplayContact(c);
} while (c.moveToNext());
}
db.close( );
}

private void DisplayContact(Cursor c)


{
Toast.makeText(getBaseContext(),"id: " + c.getString(0) +"Name: " +
c.getString(1) + "\n" + "Email: " +
c.getString(2),Toast.LENGTH_LONG).show();
}
});
//---Select a contact---
b3.setOnClickListener(new View.OnClickListener( )
{
@Override
public void onClick(View v)
{
db.open();
Cursor c = db.getContact(Integer.parseInt (et1.getText().toString()));
if (c.moveToFirst())
DisplayContact(c);
else
Toast.makeText(getBaseContext(),"Nocontact
found",Toast.LENGTH_LONG).show();
db.close();
}
private void DisplayContact(Cursor c)
{
Toast.makeText(getBaseContext(),"id: " + c.getString(0) + "\n" +"Name: " +
c.getString(1) +"\n" + "Email: " +
c.getString(2),Toast.LENGTH_LONG).show();
}
}) ;
//---updates a contact---
b4.setOnClickListener(new View.OnClickListener()
{ public void onClick(View v)
{ db.open();
if(db.updateContact(Integer.parseInt(et1.getText().toString()),et2.getText().toString()
,
et3.getText().toString( )))
Toast.makeText(getBaseContext(),"UpdateSuccessful.",
Toast.LENGTH_LONG).show();
else
Toast.makeText(getBaseContext(),"Update failed.",Toast.LENGTH_LONG).show();
db.close();
}
});
//---delete a contact---
b5.setOnClickListener(new View.OnClickListener( )
{ @Override
public void onClick(View v)
{
db.open();
db.deleteContact(Integer.parseInt(et1.getText().toString()));
Toast.makeText(getBaseContext(), "Deleted",Toast.LENGTH_SHORT).show();
db.close();
}
});
}
}
DBAdapter java class
package com.example.sqlapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter
{
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_EMAIL = "email";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "MyDB";
private static final String DATABASE_TABLE = "contacts";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE =
"create table contacts (_id integer primary key , " + "name text not null, email text not
null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{ this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{
try
{ db.execSQL(DATABASE_CREATE);
}
catch (SQLException e)
{ e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "+
newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{ DBHelper.close();
}
//---insert a contact into the database---
public long insertContact(long id,String name, String email)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_ROWID, id);
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_EMAIL, email);
return db.insert(DATABASE_TABLE, null, initialValues);
}
//---deletes a particular contact---
public boolean deleteContact(long rowId)
{ return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
//---retrieves all the contacts---
public Cursor getAllContacts()
{
return db.query(DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_NAME,KEY_EMAIL},null, null, null, null, null);
}
//---retrieves a particular contact---
public Cursor getContact(long rowId) throws SQLException
{
Cursor mCursor =db.query(true, DATABASE_TABLE, new String[ ]
{KEY_ROWID,KEY_NAME, KEY_EMAIL}, KEY_ROWID + "=" + rowId,
null,null,
null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
//---updates a contact---
public boolean updateContact(long rowId, String name, String email)
{
ContentValues args = new ContentValues();
args.put(KEY_NAME, name);
args.put(KEY_EMAIL, email);
return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}
OUTPUT:
Insert
Display
RESULT:

You might also like