KEMBAR78
Ccs332 App Development Lab Manual | PDF | Mobile App | Android (Operating System)
0% found this document useful (0 votes)
10 views95 pages

Ccs332 App Development Lab Manual

The document outlines a practical laboratory observation book for a course on App Development at Gojan School of Business and Technology. It includes a list of experiments for students to complete, such as building cross-platform applications using React Native and Flutter, as well as designing applications for various functionalities like BMI calculation and expense management. Each exercise provides detailed steps for setting up the development environment and coding the applications.
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)
10 views95 pages

Ccs332 App Development Lab Manual

The document outlines a practical laboratory observation book for a course on App Development at Gojan School of Business and Technology. It includes a list of experiments for students to complete, such as building cross-platform applications using React Native and Flutter, as well as designing applications for various functionalities like BMI calculation and expense management. Each exercise provides detailed steps for setting up the development environment and coding the applications.
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/ 95

GOJAN SCHOOL OF

BUSINESS AND TECHNOLOGY


AN AUTONOMOUS INSTITUTION YYeeaarrssooffEExxcceelllleennccee

(Conferment of Autonomous Status by UGC)


APPROVED BY AICTE | AFFILIATED TO ANNA UNIVERSITY | ACCREDITED BY NAAC
GOJAN COLLEGE ROAD, EDAPALAYAM, REDHILLS, CHENNAI - 600052

+91-70107 23984/85 +91-44-2631 1001/1002/1045 WWW.GSBT.EDU.IN

DEPARTMENT OF
COMPUTER SCIENCE AND ENGINEERING

Course Code/Name: CCS332 / APP DEVELOPMENT

Department: CSE

APP DEVELOPMENT LABORATORY


PRACTICAL LABORATORY - OBSERVATION BOOK

Name : ………………………………………….

Register No : ………………………………………….

Branch : ………………………………………….

Year & Sem : …………………………………………...

1
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

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 budova and a submit button. Also, include header image and a label

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

7.Design and implement a simple library management system using a switch statement in
Java, where have operated the following operations Add a new book, Check Out a book,
display specific book status, search specific book, and display book details using different
classes

2
NAME OF THE PAGE DATE OF MARK
S.No. DATE SIGNATURE
EXPERIMENT NO SUBMISSION (10)

3
NAME OF THE PAGE DATE OF MARK
S.No. DATE SIGNATURE
EXPERIMENT NO SUBMISSION (10)
EXERCISE:1 Using react native, build a cross platform application for a
BMI calculator.

Setup Development Environment


Step 1: Before start building a new application with react native you have to install
Node.js.
Step 2: Setup your IDE .Visual studio code is recommended.
>> Install Expo CLI
Step 3: Open terminal in your preferred directory and run the following command
>> npm install –g expo -cli
Step 4: Create your project .
>> expo init BMIcalculator >>cd BMIcalculator.
Step 5: Run your application.
>> expo start
Open expo client on your device.After running above command ,the
development server will start and show a QR code in the terminal and web
browser.
BMI is the measure of body index: BMI= weight(kg)/height(m)]^ 2
Download expo mobile application for live previewing your new application with
in your mobile phone.
Android/ios. After installing expo on your device ,you have to scan the QR code
in your terminal or web browser using expo client app.
Step 6: Open BMI calculator/App.js and type code
import React ,{ Component } from ‘react’
import { View,Text,TouchableOpacity,TextInput,StyleSheet
} from ‘react-native’ class Inputs extends Component{
State = {
height: ‘ ‘,
weight: ‘ ‘,
bmi: ‘ ‘,
BmIResult:’ ‘,
}
handleHeight =(text)=> {
this.setState({ height:text } )
}
handleWeight =(text) => {
this.setstate( { weight:text} )
}
Calculate =(height,weight)=> {
//calculation
Var result =(parseFloat(weight)* 10000)/(parseFloat(height) *
parseFloat(height));
result =result.toFixed(2);
//display result
this.setState({ bmi: result } )
if(result<18.5){
this.setState({ BmiResult:’ Underweight ‘ } )
}
else if(result>= 18.5 && result<2.5){
this.setState( {BmiResult:’ Normal weight’} )
}
elseif (result>= 25 && result< 30){
this.setState( {BmiResult:’ Overweight’ })
}
else if(result>=30){
this.setState( { BmiResult: ’Obese’ } )
}
else {
alert(“Incorrect Input ‘);
this.setState( { BmiResult : “ } )
}
}
render(){
return(
<View style = { styles.container }><Text style={ styles.title }>BMI
Calculator</Text>
<Text style = { styles.label }>Height</Text>
<TextInput style ={ styles.input }
underlineColorAndroid =”transparent”
placeholder =”Height(Cm)”
autoCapitalize =”none”
onChangeText ={ this.handleHeight }/><Text style ={ styles.label
}>Weight</Text>
<TextInput style ={ styles.input }
underlineColorAndroid =”transparent”
placeholder =”Weight(Kg)”
autoCapitalize =”none”
onChangeText ={ this.handleWeight}/>
<TouchableOpacity
Style ={styles.submitButton}
onPress = {
() =>this.calculate(this.state.height, this.state.weight)
}>
<Text style ={ styles.submitButtonText}>Calculate </Text>
</TouchableOpacity><Text style ={styles.output}>{this.state.bmi}</Text>
<Text style ={ styles.resultText}> {this.state.BmiResult} </Text> </view>
)
}
}
export default Inputsconst styles =Stylesheet.create({
container: {
paddingTop:23,
},
Input:{
margin:15,
height:40,
borderWidth : 1,
padding: 10,
},
submitButton: {
backgroundColor : ‘#ff6666’,
padding: 10,
margin : 15,
height : 40,

},
submitButtonText: {
textAlign: “center”,
color :’white’,
//font weight:” bold”,
fontSize :18,
},
Output :{
textAlign :”center”,
fontSize :30,
},
title:{
paddingTop: 30,
paddingBottom:10,
textAlign: “center”,
fontSize: 30,
fontWeight: “bold”,
},
resultText: {
paddingTop:20,
paddingBottom:10,
textAlign: “center”,
fontSize :30,
color: ‘blue’
},
label: {
marginLeft: 15,
}})
Exercise : 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.

Step1:
Create APP: Android Studio, and create a new Flutter Give the project name
"expense today”. And click. Next and follow the same to use the default
settings.
Step 2: Now delete all the code from the main.dart file.
Step3: Create the Main App Widget
main.dart
import 'package:flutter/material.dart';
final String appTitle = "Expense App";
void main() {
runApp(ExpenseApp());
}
class ExpenseApp extends Stateless Widget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: appTitle,
theme: ThemeData(
primarySwatch: Colors.green,
visualDensity: VisualDensity.adaptivePlatformDensity, ),
home: Text(appTitle),
debugShowCheckedModeBanner: false);
}}
Step 4: Run the app:
Step 5: Create a HomeScreen Stateful widget
main.dart file at the bottom after Expense App class, write the Following code.
class HomeScreen extends StatefulWidget {
constHomeScreen( ({Key key}): super(key: key);
@override
_HomeScreenStatecreateState() =>_HomeScreenState();
class_HomeScreenState extends State<HomeScreen> {
String title appTitle;
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: ListView(
children: [
Text("ABC"),
Text("DEF"),
],
),
),
appBar: AppBar(
title: Text(title),
),
floating ActionButton: Pressed: () {}, Floating ActionButton.extended(
onPressed : ( ) { },
label: Text('Add'),
icon: Icon(Icons.add),
backgroundColor: Colors.pink,
),
);
}}
Step 6: Update ExpenseApp Widget
class ExpenseApp extends Stateless Widget {
//
This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(

home: HomeScreen(),

}
}
Step 7: Fix Test Code red line is showing under the widget_test.dart. To
remove it just change MyApp() to Expense App()
Step 8: Create a Row Widget
Step:9 Creating the Widget UI. write the following code in the
category_widget.dart file
import package flutter/material.dart';
class CategoryWidget extends StatefulWidget {
Category Widget({Key key, this rowNumber, this.callback)) super(key: key);
int rowNumber;
Function callback;
@override
_Category WidgetStatecreateState() => _CategoryWidgetState();
}
class_CategoryWidgetState extends State<CategoryWidget> {
@override
Widget build(BuildContext context) {
return Card(
child: Padding(
padding: constEdgeInsets.all(15.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.space Between, children: [
Padding(
padding: constEdgeInsets.only(right: 20),
child: Text(
"$(widget.rowNumber + 1}",
style: TextStyle(
fontSize: 20,
font Weight: Font Weight.bold,
),
),
),
Expanded(
child: TextField(
onChanged: (text) {
print(text);
},
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Category',
),
),
),
Icon(Icons.attach_money),
Expanded(
child: TextField(
onChanged: (text) {
print(text);
},
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Cost',
),
),
],
),
),
),
}
}
Step 10: Update the ListView within the class. _HomeScreenstate
class_HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: ListView(
children: [
Category Widget(
rowNumber: 0,
callback: () {},
),
Category Widget(
rowNumber: 1,
callback: () {},
),
],
),
),

);
}
}

Step 11: Create the "+ Add" Functionality


click the pink +Add button new row will be added.
add int totalRow = 0; within the_HomeScreenState
class_HomeScreenState extends State<HomeScreen>
String title appTitle;
int totalRow = 0;
….
Step 12: addRow function within the HomeScreen State
Class_HomeScreenState extends State<Home Screen>{

void addRow() {
setState(() {
totalRow+1:
});}...)
Step 13: Listview within the _ HomeScreen Widget again:
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: ListView(
children: [
for (int i = 0; i<totalRow; ++i)
Category Widget(
rowNumber: i,
callback: () {}, ), ], ),
),
],
),
),

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

floatingActionButton: Floating ActionButton.extended(
onPressed: addRow,
label: Text('Add'),
icon: Icon(Icons.add),
backgroundColor: Colors.pink,
),

Step 15: save the file to hot reload the app. You see, the app screen is blank,
and if
you click + Add continuously a new Category Widget will be added within the
ListView.
Step 16: Update main.dart file
Now update the main.dart file by importing the new widget here.
import package:expense_today/category_widget.dart';
Step 17: update the ListView within the _HomeScreenstate class.
class_HomeScreenState extends State<HomeScreen> {

@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: ListView(
children: [
Category Widget(
rowNumber: 0,
callback: () {},
),
Category Widget(
rowNumber: 1,
callback: () {},
),
],
),
),

);
}}
Within the ListView you remove the old Text widgets and adds 2
CategoryWidget. You also pass rowNumber:0 for the first one and rowNumber: 1
for the second one. Currently the callback function is empty.
Step 11: Create the "+ Add" Functionality
A user will click the pink +Add button new row will be added. To do that,
let's add int
totalRow = 0; within the HomeScreenState
class_HomeScreenState extends State<HomeScreen> {
String title appTitle;
int totalRow = 0;

addRow function within the _HomeScreenState
class_HomeScreenState extends State< HomeScreen> {

void_addRow() {
setState(() {
totalRow += 1;
});
}

List View within the_HomeScreenWidget again: {

Widget build(BuildContext context)


return Scaffold(
body: SafeArea(
child: ListView(
children: [
for (int i = 0; i<totalRow; ++i)
Category Widget(
rowNumber: i,
callback: () {},
),
],
),
),
onPressed function of the floatingActionButton widget and add a reference of
the_addRow function.
...
floating ActionButton: FloatingActionButton.extended(
onPressed: _addRow,
label: Text('Add'),
icon.Icon(Icons.add),
background Color:Colors.pink,
),

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

Ex:3.1: pounds to kg:


Import React, { useState } from “react “;
export default function App(){
const [weightInLb, setWeightInLb] = useState(0);
const[weightInKg, setWeightInKg] =useState(0);
const calculate = (e) => {
e.preventDefault();
constformValid =+weightInLb>= 0;
if(!formValid){
return;
}
setWeightInKg(+weightInLb *0.453592);
};
return(
<div className=”App”>
<form onSubmit ={calculate}>
<div>
<label>weight in pounds</label>
<input
Value={weightInLb}
onChange={(e) =>setWeightInLb(e.target.value)}
/>
</div>
<button type=”submit”>calculate </button>
</form>
<p>{weightInkg} kg</p>
</div>
);
}

Ex3.2 Convert km to mi
Import React, { useState } from “react”;
export default function App( ) {
const [weightInLb, setWeightInLb] = useState(0);
const [weightInKg, setWeightInKg] = useState(0);
const calculate = (e) => {
e.preventDefault( );
constform Valid =+ weightInLb > =0;
if(!formValid){
return;
setWeightInKg(+weightInLb * 0.62137);
};
return(
<div className =”App”>
<form onSubmit ={ calculate }>
<div>
<label>Enter Km </label>
<input
Value={weightImLb}
Onchange ={ ( e) =>setWeightInLb(e.target.value)}
/>
</div>
<button type =”submit”>convert </button>
</form>
<p>{weightInKg} mi </p>
</div>
Exercise:4 Design and develop a cross platform application for day to day
task (to-do) management.

Day to day activities


1. The Customer Experience
2. Attendance calculation
3. Pay roll
4. Billing

Ex:4.1 Customer Experience

Step 1: Emoji Feedback component-src/App.js


/ React
import { useState } from "react",
// External
import styled from "styled-components";
//Components
import EmojiFeedback from "/components/EmojiFeedback";
const AppStyles = styled.div
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
background-color: #f8ebe2;
‘;
const App = () => {
const [activeReaction, setActiveReaction] = useState("");
return (
<AppStyles>
<EmojiFeedback

activeReaction (active Reaction)


set Active Reaction={setActiveReaction}
/>
</AppStyles>
);
};
export default App:

Step2: Constants-src/components/EmojiFeedback/data.js

const reactions["Aweful", "Bad", "Ok Ok", "Good","Amazing"],


export { reactions };

Step:3 call the Emoji component for every reaction.src/


components/EmojiFeedback/index.jsx

// External
import styled from "styled-components";
// Components
import Emoji from "./Emoji";
import { Flex } from "../../styles/globalStyles";

// Reactions array
import { reactions } from "./data";
const Card styled.div'
width: 800px;
height: 500px;
background-color: #fff;
border-radius: 33px;
padding: 44px 48px;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);

@media only screen and (max-width: 900px) {


width: 80%;
}
‘;
const Heading = styled.h2’
font-size: 42px;
font-weight: bold;
margin: 0;
color: #000;
font-family: Plus Jakarta Sans Bold,
‘;
const Content = styled(Flex)’
height: 452px;
position: relative;
‘;
const Emojis = styled(Flex)'
top: 30%;
‘;
const Button = styled.button'
background-color: ${props => (props.isSelected ? "#000" : "#ccc")};
cursor: ${props => (props.isSelected ? "pointer" : "not- allowed")};
border: none;
color: #fff;
padding: 19.5px 107.3px,
border-radius: 19px;
font-family: Plus Jakarta Sans Medium;
font-size: 24px;
user-select: none;
position: absolute;
bottom: 0;

const EmojiFeedback= ({ activeReaction, setActiveReaction })


=> {
return (
<Card>
<Heading>How was your experience?</Heading>
<Content column>
<Emojis>
{reactions.map(reaction => (
<Emoji
reaction={reaction}
key={reaction}

isSelected={activeReaction === reaction}


setActiveReaction={setActiveReaction}
/>
))}
</Emojis>
<Button isSelected={!!activeReaction}>Submit</Button>
</Content>
</Card>
);
};
export default EmojiFeedback;

Step 5: render a single emoji.src/components/Emojitok App Development


Emoji.jsx

//External

import Lottie from "react-lottie";


import { motion } from "framer-motion";
import styled from " styled-components":
//Helper for handling lottie animation data import select AnimationData from
"../../lotties";
const EmojiWrapper = styled(motion.div)
cursor: pointer;
margin: 0 12px;
position: relative;
‘;
constEmojiLabel = styled.p
text-align: center;
position: absolute;
bottom: -32px;
left: 50%;
transform: translate(-50%, -50%);
font-family: Plus Jakarta Sans Bold;
font-size: 16px;
user-select: none;
‘;
// Constants for emoji's scale during different states
const NORMAL_SCALE = 1;
const HOVERED_SCALE = 1.3;
Const SELECTED_SCALE = 1.5;
const Emoji { i = ({ reaction, isSelected, setActiveReaction }) =>
{
// Initialize the animation options as per the reaction

constanimationOptions = {

loop: true,
autoplay: false,
animationData: select AnimationData(reaction),
rendererSettings: {
preserveAspectRatio: "xMidYMid slice",
},
};

// Update state on the click of reaction


consthandleClick = () => {
if (isSelected) {
setActiveReaction("");
} else {
setActiveReaction(reaction);
}
};
return (
<EmojiWrapper
whileHover={{
scale: isSelected ? SELECTED_SCALE:
HOWEVERED_SCALE,
}}
animate={{
scale: isSelected ? SELECTED_SCALE
NORMAL_SCALE,
}}
onClick={handleClick}
>

<Lottie
Options={animationOptions}
height ={100}
Width =”80%”
isStopped={! is Selected}
isClickToPauseDisabled
/>
{isSelected&&<EmojiLabel>{reaction}</EmojiLabel>}
</EmojiWrapper>
);
};
Exercise No 5: Design an android application using Cordova for a user login
screen with username, password, reset budova and a submit button. Also,
include header image and a label. Use layout managers.

Creating a New project:

Open Android Studio and then click on File -> New -> New project.

1-10thenla ang AndroidStatio Projectsex.no - Android Studio 14

Le View

evigate de

Analyse

Blacto Build Nei Preject

Fools VCS

Window Help

Import Project

Open Eerpen Project

Project from Venion Contrel

Close Prejest

New Module

CARS

Import Module

Project Structur

CAS

Import Sample Jeva Class


We by name with Chit SNN

Recent Files with CE

Other Settings

Navigation cos Bar with At Home

Supert Settings

Export Setting

Save Al Synchronize

Module

Andreid resource fåe

Culas

Androd resource directory

CMARY Fide

Balate Caches/t

Package

Reges

Show only selected

C-Class

Line Separators

Mate File Read only

Power Save Mode

C/CSource Fide

CC Header File

Image Asist
Vector Asset

Singleton

300

fventing

Gradle Console

Then type the Application name as "ex.no.23 and click Next.

AF

New Project

Configure your new project

Then select the Minimum SDK as shown below and click Next.

Target Android Devices

ON

110

Then select the Empty Activity and click Next.

Add an activity to Mobile

Finally click Finish.

Customize the Activity

It will take some time to build and load the project.

After completion it will look as given below.

Creating Second Activity for the Android Application:

Click on File -> New -> Activity -> Empty Activity.


Type the Activity Name as SecondActivity and click Finish button.

Customize the Actrity

Thus Second Activity For the application is created.

Designing layout for the Android Application:

Designing Layout for Main Activity:

Click on app -> res -> layout -> activity_main.xml

Now click on Text as shown below.

Then delete the code which is there and type the code as given below.

Code for Activity_main.xml:

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

<RelativeLayout xmlns:android="http://schemas.android.com/ apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

Practical Exercises

android layout height="match_parent" tools context=" MainActivity">

<LinearLayout

android:layout_width="match_parent"

android:layout_height="100dp">

<TextView

android:id="@+id/textView"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_margin="30dp"
android:text="Details Form"

android:textSize="25sp"

android:gravity="center"/>

</LinearLayout>

<GridLayout

android:id="@+id/gridLayout"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:layout_marginTop="100dp"

android:layout_marginBottom="200dp"

android:columnCount="2"

android:rowCount="3">

<TextView

android:id="@+id/textView1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_margin="10dp"

App Development

android:layout_row="0"

android:layout_column="0"

android:text="Name"

android:textSize="20sp"
android:gravity="center"/>

<EditText

android:id="@+id/editText"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_margin="10dp"

android:layout_row="0"

android:layout_column="1"

android:ems="10"/>

<TextView

android:id="@+id/textView2"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_margin="10dp"

android:layout_row="1"

android:layout_column="0"

android:text="Reg.No"

android:textSize="20sp"

android:gravity="center"/>

<EditText

android:id="@+id/editText2"

android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:layout_margin="10dp"

android:layout_row="1"

android:layout_column="1"

android:inputType="number"

android:ems="10"/>

<TextView>

android:id="@+id/textView3"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_margin="10dp"

android:layout_row="2"

android:layout_column="0"

android:text="Dept"

android:textSize="20sp"

android:gravity="center"/>

<Spinner>

android:id="@+id/spinner"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_margin="10dp"

android:layout_row="2

android:layout_column="1"
android:spinnerMode="dropdown"/>

</GridLayout>

Batton

App Development

android:id="@+id/button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentBottom="true"

android:layout_centerInParent="true"

android:layout_marginBottom="150dp"

android:text="Submit"/>

RelativeLayout>

Now click on Design and your activity will look as given below.

So now the designing part of Main Activity is completed.

signing Layout for Second Activity:

Click on app -> res -> layout -> activity_second.xml.

Now click on Text as shown below.

Then delete the code which is there and type the code as given below.

Code for Activity_second.xml:

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

<LinearLayout xmlns:android="http://schemas.android.com apk/res/android"


xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context="com.example.devang.exno2.SecondActivity"

android:orientation="vertical"

android:gravity="center">

<TextView

android:id="@+id/textView1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_margin="20dp"
android:text="New Text"
android:textSize="30sp"/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="New Text"
android:textSize="30sp"/>
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="New Text"
android:textSize="30sp"/>
LinearLayout>
Now click on Design andyour activity will look as given below.
So now the designing part of Second Activity is also completed.
Java Coding for the Android Application:
Java Coidng for Main Activity:
MainActivity.
Click on app -> java -> com.example.exno2 →
Then delete the code which is there and type the code as given below.
Code for MainActivity.java:
1
package com.example.exno2;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button
import android.widget.EditText;
import android.widget.Spinner;
public class MainActivity extends AppCompatActivity {
//Defining the Views
EditText el,e2;
Button bt;
Spinner s;
//Data for populating in Spinner
String [] dept_array={"CSE", "ECE", "IT", "Mech", "Civil"};
String name, reg, dept;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
*
Practical Exercises
setContentView(R.layout.activity_main);
//Referring the Views
el= (EditText) findViewById(R.id.editText); e2= (EditText)
findViewById(R.id.editText2);
bt= (Button) findViewById(R.id.button);
}
1
S
1
s= (Spinner) findViewById(R.id.spinner);
//Creating Adapter for Spinner for adapting the data from array to Spinner
ArrayAdapter adapter= new ArrayAdapter(MainActivity.
this,android.R.layout.simple_spinner_item,dept_array); s.setAdapter(adapter);
//Creating Listener for Button
bt.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) {
//Getting the Values from Views(Edittext & Spinner)
name=el.getText().toString();
reg=e2.getText().toString();
dept=s.getSelectedItem().toString();
//Intent For Navigating to Second Activity
Intent i = new Intent(MainActivity.this, SecondActivity.class);
/For Passing the Values to Second Activity
i.putExtra("name_key", name);
i.putExtra("reg_key",reg); i.putExtra("dept_key", dept);
startActivity(i);
}
});
}
}
So now the Coding part of Main Activity is completed.
Java Coding for Second Activity:
Click on app -> java -> com.example.exno2 -> SecondActivity.
Then delete the code which is there and type the code as given below.
Practical Exercises
Code for SecondActivity.java:
package com.example.exno2;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class SecondActivity extends AppCompatActivity {
TextView t1, t2,t3;
String name, reg, dept;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
t1= (TextView) findViewById(R.id.textView1);
t2= (TextView) findViewById(R.id.textView2);
t3= (TextView) findViewById(R.id.textView3);
//Getting the Intent
Intent i = getIntent();
//Getting the Values from First Activity using the Intent eceived
name-i.getStringExtra("name_key");
reg-i.getStringExtra("reg_key");
dept-i.getStringExtra("dept_key");
//Setting the Values to Intent
11.setText(name);
12.setText(reg);
13.setText(dept);
}
}
So now the Coding part of Second Activity is also completed.
Now run the application to see the output.
Output:
VAAB 11:48
44 11:50
44 11:50
800.2
Details Form
Details Form
Name
Name
devang
devang
Reg No
Reg. No 111512104049
Dept
Dept
CSE
SUBMIT
111512104049
SUBMIT
4
D
4
6
CSE
CSE
Result:
Thus a Simple Android Application that uses Layout Managers and Event
Listeners is developed and executed successfully.
Exercise NO:6 Design and develop an android application using Apache
Cordova to find and display the current location of the user

Step 1:Set up your Development |Environment

1. Install Node.js: Make sure you have Node.js installed on your system.
2. Install Cordova: Open your terminal and run the following command to install
Cordova globally:
Copy code
npm install –g cordova
3.Create a New Cordova Project: Navigate to the directory where you want to
create your Project and run:
luaCopy code
cordova create LocationApp com.example.locationapp LocationApp
4. Navigate to your project folder:
bashCopy code
cdLocationApp
Step 2:Add Android Platform
Run the following command to add Android platform to your project:
CsharpCopy code
Cordova platform add android
Step 3:Install the Geolocation Plugin
To access the device’s geolocation ,you ‘ll need to install the Cordova
Geolocation plugin. Run the following command :
csharpCopy code
cordova plugin add cordova-plugin –geolocation
Step 4: Edit the HTML and JavaScript
Open the www folder in your project directory and
modify the index.html file to include a button to fetch the location and a
<div> to display it.
<! DOCTYPE html>
<html>
<head>
<title> Location App </title>
<script type = “ text/javascript” src=”cordova.js” > </script>
<script type = “text/javascript” src=”js/index.js”> </script>
</head>
<body>
<h1> Location App</h1>
<button id=”getLocation “ >Get Location </button>
<div id =” locationDisplay”> </div>
</body>
</html>

In the js /index.js file ,add the following code to handle the button
click and fetch the user’s location.
Step 5: Build and Run your App

Document.getElementById(“getLocation”).addEventListener(“Click”,
getLocation);
}
function getLocation( ){
navigator.geolocation.getCurrentPosition(
function(position){
var latitude =position.coords.latitude;
var longitude =position.coords.longitude;
var locationDisplay =document.getElementByid(“locationDisplay”);
locationDisplay.innerHTML =”Latitude:” +latitude + “<br>Longitude
:” + longitude;
},
function(error){
console.log(“Error getting location:” + error.message);
}
);
}

Run the following command to build and run your app on an Android emulator or
device:
arduinoCopy code
Cordova run android
Exercise 7: Design and implement a simple library management system using
a switch statement in Java, where have operated the following operations Add
a new book, Check Out a book, display specific book status, search specific
book, and display book details using different classes.

Menu for Library Management

Here is the list set of options that we will be creating that are as follows:

Exit Application

Add a New Book

Upgrade Quantity of a Book

Search a Book

Show All Books

Register Student

Show All Registered Students

Check Out Book


Check-In Book

Implementation: Creating 5 files including our application (main) class responsible


for the execution of our mini-project listed as follows:

Library

Students

Student

books

book

A. File: book.java

Java

// Java Program to Illustrate book Class that

// takes Input from the books and related information


package College;

// Importing required classes import java.util.Scanner;

// Class public class book {

// Class data members public int sNo; public String bookName;

public String authorName; public int bookQty;

public int bookQtyCopy;

// Creating object of Scanner class to

// read input from users Scanner input = new Scanner(System.in);

// Method

// To add book details

public book()

{
// Display message for taking input later

// taking input via

// nextInt() and nextLine() standard methods

System.out.println("Enter Serial No of Book:");

this.sNo input.nextInt();

input.nextLine();

System.out.println("Enter Book Name:");

this.bookName input.nextLine();

System.out.println("Enter Author Name:");

this.authorName = input.nextLine();

System.out.println("Enter Quantity of Books:");

this.bookQty input.nextInt();

bookQtyCopy = this.bookQty;

}
B. File: books.java

Java

// Java Program to Illustrate books class

// To Do all the Operations related to Books such as

// add, check-in, check-out, Valid books, Update books

// Importing required classes import java.util.Scanner;

// CLass

public class books {

// Class data members book theBooks[] = new book[50];

public static int count;

Practical Exercises

Scanner input = new Scanner(System.in);


// Method 1

// To compare books

public int compareBookObjects(book b1, book b2)

// If book name matches if (bl.bookName.equalsIgnoreCase(b2.bookName))

// Printing book exists

System.out.println( "Book of this Name AlreadyExists.");

return 0;

// if book serial matches if (bl.sNob2.sNo) {

// Print book exists

System.out.println( "Book of this Serial No Already Exists.");


return 0;

return 1;

// Method 2

// To add book

public void addBook(book b)

for (int i=0; i < count; i++) {

if (this.compareBookObjects(b, this.theBooks[i]) = 0)

return;

if (count < 50) {

theBooks[count] = b;
count++;

else {

System.out.println("No Space to Add More Books.");

// Method 3

// To search book by serial number

public void searchBySno()

// Display message
System.out.println(

"\t\t\t\tSEARCH BY SERIAL NUMBER\n");

// Class data members

Practical Exercises

int sNo;

System.out.println("Enter Serial No of Book:"); sNo= input.nextInt();

int flag = 0;

System.out.println("S.No\t\tName\t\tAuthor\t\tAvailable Qty\t\tTotal Qty");

for (int i = 0; i < count; i++) {

if (sNo theBooks[i].sNo) {

System.out.println(theBooks[i].sNo + "\t\t"+ theBooks[i].bookName "\t\t"+


theBooks[i].authorName + "\t\t"+ theBooks[i].bookQtyCopy + "\t\t"+
theBooks[i].bookQty);flag++;
return;

if (flag == 0) System.out.println("No Book for Serial No " +sNo + "Found.");

// Method 4

// To search author by name public void searchByAuthorName()

// Display message

System.out.println("\t\t\t\tSEARCH BY AUTHOR'S NAME");

input.nextLine();

System.out.println("Enter Author Name:");


String authorName = input.nextLine();

int flag = 0;

System.out.println( "S.No\t\tName\t\tAuthor\t\tAvailable Qty\t\tTotal Qty");

for (int i = 0; i < count; i++) {

// if author matches any of its book if (authorName.equalsIgnoreCase(


theBooks[i].authorName)) {

// Print below corresponding credentials System.out.println( theBooks[i].sNo +


"\t\t" + theBooks[i].bookName + "\t\t" + theBooks[i].authorName + "\t\t" +
theBooks[i].bookQtyCopy + "\t\t" + theBooks[i].bookQty);

flag++;

// Else no book matches for author

}
if (flag = 0)

System.out.println("No Books of " + authorName + "Found.");

// Method 5

// To display all books public void show AllBooks()

System.out.println("\t\t\t\tSHOWING ALL BOOKS\n"); System.out.println(


"S.No\t\tName\t\tAuthor\t\tAvailable Qty\t\tTotal Qty");

for (int i = 0; i < count; i++) {

System.out.println(theBooks[i].sNo + "\t\t"+ theBooks[i].bookName

+ "\t\t"+ theBooks[i].authorName + "\t\t" + theBooks[i].bookQtyCopy

+ "\t\t"+ theBooks[i].bookQty);

}
// Method 6

// To edit the book

public void upgradeBookQty()

System.out.println(UPGRADE QUANTITY OF A BOOK\n");

System.out.println("Enter Serial No of Book"),

int sNo input.nextInt(),

for (int i=0;i<count, i++) {

if (sNo theBooks[1] sNo) {

Display message

System.out.println( "Enter No of Books to be Added: "),


int addingQty input.nextInt();

theBooks[i] bookQty addingQty:

theBooks[i] bookQtyCopy + addingQty,

return,

Method 7

To create menu public void dispMenu()

Displaying menu System.out.println(");

Practical Exercises

System.out.println("Press 1 to Add new Book.");

System.out.println("Press 0 to Exit Application.");


System.out.println( "Press 2 to Upgrade Quantity of a Book.");

System.out.println("Press 3 to Search a Book.");

System.out.println("Press 4 to Show All Books.");

System.out.println("Press 5 to Register Student.");

System.out.println("Press 6 to Show All Registered Students.");

System.out.println("Press 7 to Check Out Book. ");

System.out.println("Press 8 to Check In Book");

System.out.println(-");

// Method 8

// To search the library

public int is Available(int sNo)


{

for (int i = 0; i < count; i++) {

if (sNo == theBooks[i].sNo) {

if (theBooks[i].bookQtyCopy > 0) {

System.out.println("Book is Available.");

return i;

System.out.println("Book is Unavailable");

return -1;

on

}
System.out.println("No Book of Serial Number " + "Available in Library.");

dent

return -1;

// Method 9

// To remove the book from the library

Book

public book checkOutBook()

System.out.println( "Enter Serial No of Book to be Checked Out.");

int sNo input.nextInt();


int bookIndex = isAvailable(sNo);

if (bookIndex != -1) { theBooks[bookIndex].bookQtyCopy-;

return theBooks[bookIndex];

001

return null;

// Method 10

// To add the Book to the Library

public void checkInBook(book b)

Unavailable
for (int i = 0; i < count; i++) {

Practical Exercises

// Method 1

// To add books public void addStudent(student s)

for (int i = 0; i < count; i++) {

if (s.regNum.equalsIgnoreCase( the Students[i].regNum)) {

// Print statement

System.out.println( "Student of Reg Num" + s.regNum +" is Already Registered.");

return;

if (count=50) { the Students[count] = s; count++;

// Method 2
// Displaying all students public void show AllStudents() {

// Printing student name and // corresponding registered number

System.out.println("Student Name\t\tReg Number");

for (int i = 0; i < count; i++) {

System.out.println(theStudents[i].studentName + "\t\t" + theStudents[i].regNum);

// Method 3

// To check the Student public int isStudent()

{
// Display message only System.out.println("Enter Reg Number:");

String regNum = input.nextLine();

for (int i = 0; i < count; i++) {

if (theStudents[i].regNum.equalsIgnoreCase( regNum)) {

return i;

// Print statements

System.out.println("Student is not Registered."); System.out.println("Get


Registered First.");

return -1;

// Method 4
// To remove the book

public void checkOutBook(books book)

int studentIndex = this is Student();

if (studentIndex != -1) {

System.out.println("checking out");

book.showAllBooks();

book bbook.checkOutBook();

System.out.println("checking out"); if (b != null) {

if (theStudents[studentIndex].booksCount <= 3) {

System.out.println("adding book");
theStudents[studentIndex] borrowedBooks [theStudents[studentIndex]
booksCount] = b; theStudents[studentIndex].booksCount++;

return;

else {

System.out.println(

App Development "Student Can not Borrow more than 3 Books.");

return;

System.out.println("Book is not Available.");

Method 5

To add the book public void checkInBook(books book)

1
int studentIndex = this.isStudent(); if (student Index != -1) {

// Printing credentials corresponding to student System.out.println(

"S.No\t\t\tBook Name\t\t\tAuthor Name");

students theStudents[studentIndex];

edBooks

for (int i = 0; i < s.booksCount; i++) {

bunt++;

System.out.println( s.borrowedBooks[i].sNo + "\t\t\t" +


s.borrowedBooks[i].bookName + "\t\t\t" + s.borrowedBooks[i].authorName); }

// Display message only

System.out.println(Count);

"Enter Serial Number of Book to be Checked In:");


int sNo = input.nextInt();

for (int i = 0; i < s.booksCount; i++) {

if (sNos.borrowedBooks[i].sNo) {

book.checkInBook(s.borrowedBooks[i]); s.borrowedBooks[i] = null;

return;

System.out.println("Book of Serial No " + sNo + "not Found");

}
E. File: Library.java

Java

// Java Program to Illustrate Application CLass

// To Create The Menu For the Program

// Importing required classes

import java.util.Scanner;

// Class

public class Library {

// Main driver method

d In:");

public static void main(String[] args)


{

// Creating object of Scanner class

// to take input from user Scanner input = new Scanner(System.in);

// Displaying menu System.out.println( "********************Welcome to the


GFG Library!********************");

System.out.println("Select From The Following Options: ");

System.out.println(

// Creating object of book class

books ob = new books();

// Creating object of students class

students obStudent = new students();

int choice;
int searchChoice;

// Creating menu

// using do-while loop

do {

ob.dispMenu();

choice = input.nextInt();

// Switch case

switch (choice) {

// Case

case 1: book b = new book();

ob.addBook(b);

break;

// Case case 2:
ob.upgradeBookQty();

break;

// Case case 3:

System.out.println(

"press 1 to Search with Book Serial No.");

System.out.println( "Press 2 to Search with Book's Author Name.");

searchChoice = input.nextInt();

// Nested switch switch (searchChoice) {

// Case

case 1: ob.searchBySno();

break;

// Case
case 2:

ob.searchByAuthorName();

break;

// Case

case 4:

ob.showAllBooks();

break;

// Case

case 5:

student s = new student();

obStudent.addStudent(s);

break;

Book Ser
// Case

case 6:

Book's A nt();

obStudent.showAllStudents();

break;

// Case

case 7:

obStudent.checkOutBook(ob);

break;

// Case

case 8:

obStudent.checkInBook(ob);

break;
// Default case that will execute for sure

// if above cases does not match

default:

// statement

Print State print("ENTER BETWEEN TO 8.");

// Checking condition at last where we are

// checking case entered value is not zero while (choice != 0);

}
Output:

Add Book

****Welcome to the GFG Library!

Select From The Following Options

Press to Exit Application

Press 1 to Add new Book.

Press 2 to Upgrade Quantity of a Book.

Press 3 to Search a Book.

Press 4 to Show All Books.

Press 5 to Register Student

Press 6 to Show All Registered Students.

Press 7 to Check Out Book


Press 8 to Check In Book

Enter Serial No of Book:

Enter Book Name:

geekforgeek

Enter Author Name:

geek

Enter Quantity of Books:

10

EEN STOL

90
Register Student

Press & to Exit Application Press 1 to Add new Book

Press 2 to Upgrade Quantity of a Book

Press 3 to Search a Book Press 4 to Show All Books

Press 5 to Register Student

Press 6 to Show All Registered Students.

Press 7 to Check out Book Press & to Check In Book

Enter Student Name Dragonsaicage

Enter Regstration Number

Rent Book/Check Out Book

Press to Exit Application.

Press 1 to Add new Book


Press 2 to Upgrade Quantity of a Book

Press 3 to Search a look

Press 4 te Show All Books

Press 5 to Register Student

Press 6 to Show All Registered Students

Press 7 to Check Out Book

Press to Check In Book

Enter Registration Number:

0001

checking out

S.No
Name

geekforgeek

App Development

SHONING ALL BOOKS

Author

geek Enter Serial Nu of Book to be Checked Out.

Available Qty

10

Book is Available.

checking out adding book

Show All Book

Press to Exit Application


Press 1 to Add new Book

Press 2 to Upgrade Quantity of a Book

Press 3 to Search a Book Press 4 to Show All Books

Press 5 to Register Student.

Press 6 to Show All Registered Students.

Press 7 to Check Out Book

Press to Check In Book

SHOWING ALL BOOKS

Name

geek forgeek

Author
Available Qty

geek

Practical Exercises

Return The Book/Check-In Book

Press 0 to Exit Application.

Press 1 to Add new Book.

Press 2 to Upgrade Quantity of a Book.

Press 3 to Search a Book. Press 4 to Show All Books.

Press 5 to Register Student.

Press 6 to Show All Registered Students.

Press 7 to Check Out Book. Press 8 to Check In Book


8 Enter Registration Number:

0001

S.No

Book Name

Author Name geek

1 Enter Serial Number of Book to be Checked In:

geekforgeek

Update The Quantity Of the Book

Press & to Exit Application.

Press 1 to Add new Book.

Press 2 to Upgrade Quantity of a Book.

Press 3 to Search a Book.


Press 4 to Show All Books.

Press 5 to Register Student.

Press 6 to Show All Registered Students.

Press 7 to Check Out Book.

Press 8 to Check In Book

91

Enter Serial No of Book

UPGRADE QUANTITY OF A BOOK

Enter No of Books to be Added:

92
App Development

geek

Search The Book

Press to Exit Application.

Press 1 to Add new Book.

Press 2 to Upgrade Quantity of a Book.

Press 3 to Search a Book.

Press 4 to Show All Books.

Press 5 to Register Student.

Press 6 to Show All Registered Students.

Press 7 to Check Out Book.


Press B to Check In Book

press 1 to Search with Book Serial No.

Press 2 to Search with Book's Author Name.

Enter Author Name:

SEARCH BY AUTHOR'S NAME

neek 5.No

Name geekforgeek

Author

Available Qty 11

Total Qty 11
Show All The Registered Student

Press 0 to Exit Application.

Press 1 to Add new Book.

Press 2 to Upgrade Quantity of a Book.

Press 3 to Search a Book.

Press 4 to Show All Books.

Press 5 to Register Student.

Press 6 to Show All Registered Students.

Press 7 to Check Out Book.

Press 8 to Check In Book

6
Student Name DragonUncaged

Registration Number 0001

You might also like