Harsh - MobileComputing
Harsh - MobileComputing
ETIT-452
VISION
To nurture young minds in a learning environment of high academic value and imbibe spiritual
and ethical values with technological and management competence.
MISSION
The Institute shall endeavour to incorporate the following basic missions in the
teaching methodology:
Diversification
The Engineering, Technology and Management disciplines have diverse fields of studies with
different attributes. The aim is to create a synergy of the above attributes by encouraging
analytical thinking.
2
MAHARAJA AGRASEN INSTITUTE OF
TECHNOLOGY
VISION
To Produce “Critical thinkers of Innovative Technology”
MISSION
To provide an excellent learning environment across the computer science
discipline to inculcate professional behaviour, strong ethical values,
innovative research capabilities and leadership abilities which enable
them to become successful entrepreneurs in this globalized world.
3
MOBILE COMPUTING LAB
ETIT – 452
LAB ASSESSMENT SHEET
4
Index
Name: Harsh
Roll No.: 05614802720
Semester: 8th
Group: 8C4
Date of
Date of
Ex.no Experiment Name performanc Marks Signature
checking
e
Write a WML program to
print a formatted Text onthe
01.
mobile Screen using
various tags.
Write a WML program to
02. connect multiple cards from
same deck.
08.
Write a Program in NS3 to
Simulate AODV
5
09.
Make an application of your
choice using WML or
Android.
10.
Write a Android Program
design an application using
Hybrid Approach.
11.
Program to develop calling
application.(Android)
Program to develop a
12.
mailing application. (Android)
6
Experiment 1
AIM: Write a WML program to print a formatted Text on the mobileScreen using various
tags.
Theory:
Attribute Value Description
Align left Aligns the paragraph. Default is "left"
right
cen
ter
Mode wrap Sets whether a paragraph should wrap lines
nowrap or not.
xml:lang language_code Sets the language used in the element
Class Cdata Sets a class name for the element. The
class name is case sensitive. An element
can be connected to multiple classes.
Multiple class names within the class
attribute
are separated by white space
Id Id Sets a unique name for the element
WML Elements
<b> Defines bold text
<big> Defines big text
<em> Defines emphasized text
<i> Defines italic text
<small> Defines small text
<strong> Defines strong text
<u> Defines underlined text
Purpose
<!--> Defines a WML comment
<wml> Defines a WML deck (WML root)
<head> Defines head information
<meta> Defines meta information
<card> Defines a card in a deck
<access> Defines information about the access control of a deck
<template> Defines a code template for all the cards in a deck
7
Code:
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.3//EN"
"http://www.wapforum.org/DTD/wml13.dtd">
<wml>
<card id="ABC" title="Practical 1">
<p>
Hello World
</p>
<onevent type="ontimer">
<go href="#ABC1"/>
</onevent>
<timer value="50"/>
</card>
</wml>
Output:
8
VIVA QUESTIONS
A1: WML decks are used in WAP (Wireless Application Protocol) to structure and present content in
a mobile application or website.
A2: WSDL (Web Services Description Language) is an XML-based language used to describe web
services and their operations, data types, and communication protocols.
A3: WML variables are used to store and manipulate data in WML (Wireless Markup Language).
They can be declared using the <variable> tag and accessed using expressions within WML decks.
A4: Card variables in WML can be refreshed by assigning new values to them using appropriate
WML tags or elements, such as <setvar> or <go> tags, within the WML deck.
9
Experiment 2
AIM: Write a WML program to connect multiple cards from same desk.
Code:
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.3//EN"
"http://www.wapforum.org/DTD/wml13.dtd">
<wml>
<card id="CardNo.1" title="Program2Card1">
<p>You Are Visiting Card 1</p>
<do type="accept" name="CardNo.2" label="Continue">
<go href="#CardNo.2"/>
</do>
</card>
10
Output:
11
VIVA QUESTIONS
A1: XML (Extensible Markup Language) is used for storing and transporting data. It provides a
platform-independent and self-describing format that is widely used in web services, data exchange,
configuration files, and more.
A2: Metadata refers to data that provides information about other data. It describes characteristics
such as the structure, format, context, and properties of data, allowing for better organization,
searchability, and interpretation of the actual data.
A3: HTML (Hypertext Markup Language) is used for creating web pages and is primarily designed
for desktop browsers. WML (Wireless Markup Language) is a markup language for creating content
on mobile devices, particularly for wireless application protocols. The main difference lies in their
target platforms and device compatibility.
A4: XML DOM (Document Object Model) Document represents the XML structure as a
hierarchical tree-like structure. It provides a programming interface for accessing and manipulating
XML documents, allowing developers to navigate, modify, and update XML content
programmatically.
12
Experiment 3
AIM: Write WML program to display table with three columns Image name, Image and
third column contain hyperlink to open another card.
Code:
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.3//EN"
"http://www.wapforum.org/DTD/wml13.dtd">
<wml>
<card id="CardNo.1" title="Program3Card1">
<p>
<table columns="3" align="LCR">
<tr>
<td>Image Name</td>
<td>Image</td>
<td>Link</td>
</tr>
<tr>
<td>Thumb Image</td>
<td><img src="thumb.wbmp" alt="Thumb Image"/></td>
<td><anchor><a href="#CardNo.2">CardNo2</a></anchor></td>
</tr>
<tr>
<td>Heart Image</td>
<td><img src="heart.wbmp" alt="Heart Image"/></td>
<td><anchor><a href="#CardNo.3">CardNo3</a></anchor></td>
</tr>
</table>
</p>
</card>
<card id="CardNo.2" title="Program3Card2">
<p>You Are Visiting Card 2</p>
<do type="accept" name="CardNo.3" label="Continue">
<go href="#CardNo.3"/>
</do>
</card>
<card id="CardNo.3" title="Program3Card3">
<p>You Are Visiting Card 3</p>
13
<do type="accept" name="CardNo.1" label="Go Back">
<go href="#CardNo.1"/>
</do>
</card>
</wml>
Output:
14
VIVA QUESTIONS
A1: The function of a WAP (Wireless Application Protocol) Gateway is to translate and route
data between the wireless network and the Internet, enabling communication between mobile
devices and web-based applications.
A2: The distillation technique in WAP refers to the process of optimizing web content to fit the
limited screen size and bandwidth of mobile devices, ensuring efficient delivery and improved
user experience.
A3: UAProf (User Agent Profile) is used to provide device-specific information, such as
capabilities and features, to web servers. It helps in adapting the content and services to the
capabilities of the accessing device.
15
Experiment 4
AIM: Write a WML program to create a form with multiple options.
Code:
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="Practical4">
<p> Select a Tutorial :
<select>
<option value="htm">HTML Tutorial</option>
<option value="xml">XML Tutorial</option>
<option value="wap">WAP Tutorial</option>
</select>
</p>
</card>
</wml>
Output:
16
VIVA QUESTIONS
A1: In WAP (Wireless Application Protocol), the push technique involves the server initiating
communication and pushing content to the mobile device, while the pull technique involves the
mobile device initiating communication and pulling content from the server.
Q2: List out the databases used to store data of WML pages.
A2: The databases commonly used to store data of WML pages are SQLite, MySQL, and Oracle
Database.
A3: The advantages of using XML DOM (Document Object Model) include easy navigation and
manipulation of XML data, platform independence, and support for standardized APIs across
different programming languages.
A4: DTD (Document Type Definition) is a set of rules that define the structure, elements, and data
types of an XML document. It is used to validate and enforce the structure and integrity of XML
documents.
17
Experiment 5
AIM: Write a WML program to use the time control and to trigger On pickevent.
Code:
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.3//EN"
"http://www.wapforum.org/DTD/wml13.dtd">
<wml>
<card id="ABC" title="Practical 5">
<p>
Hello World
</p>
<onevent type="ontimer">
<go href="#ABC1"/>
</onevent>
<timer value="100"/>
</card>
<card id="ABC1" title="Practical 5">
<p>Select a Tutorial :
<select title="tutorials" name="selection_list">
<option onpick="#xhtml">XHTML Tutorial</option>
<option onpick="#wap">WAP Tutorial</option>
</select>
</p>
</card>
<card id="xhtml" title="Practical 5">
<p>
XHTML stands for EXtensible HyperText Markup Language.
</p>
</card>
<card id="wap" title="Practical 5">
<p>
Wireless Application Protocol (WAP) is a technical standard for
accessing information over a mobile wireless network.
</p>
</card>
</wml>
18
Output:
19
VIVA QUESTIONS
A1: Yes, WAP (Wireless Application Protocol) can run over GPRS (General Packet Radio
Service), which is a mobile data network technology.
A2: WAP uses WTLS (Wireless Transport Layer Security) as the security protocol to provide
secure communication between mobile devices and servers.
A3: No, WML (Wireless Markup Language) is not case sensitive. The tags, attributes, and
values can be written in any case (uppercase or lowercase).
A4: The `<postfield>` tag in WML is used to send user input data, such as form field values, to
the server using the HTTP POST method. It allows data to be submitted in the body of an
HTTP request.
20
Experiment 6
AIM : Write a WML script to find maximum out of two numbers with helpof inbuilt
function Lang.Max() and to find absolute value with help of inbuilt function Lang.abs().
Code:
lang.max():
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.3//EN"
"http://www.wapforum.org/DTD/wml13.dtd">
<wml>
<card id="card1" title="WMLScript Tutorial">
<p>
<a href="findmax.wmls#findmax()">Find Maximum Out Of
Two.</a><br/>
<br>
First Number: $(number1)<br>
Second Number: $(number2)<br>
Maximum One: $(maxnumber)
</p>
</card>
</wml>
lang.abs():
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.3//EN"
"http://www.wapforum.org/DTD/wml13.dtd">
<wml>
<card id="card1" title="WMLScript Tutorial">
<p>
<fieldset title="Enter The Number: ">
n : <input name="N" size="12" format="*N"/>
</fieldset><br/>
<do type="accept" name="CardNo.2" label="Enter">
<go href="findmax.wmls#findabs(-8)"/>
</do>
<br>
</p>
21
<p>
First Number: $(number)<br>
ABS Number: $(absnumber)
</p>
</card>
</wml>
Custom function[findmax()]:
extern function findmax()
{
var result1 = Dialogs.prompt("Enter 1st number", "");
var result2 = Dialogs.prompt("Enter 2cd number", "");
var maxnum = Lang.max(result1, result2);
WMLBrowser.setVar("number1", result1);
WMLBrowser.setVar("number2", result2);
WMLBrowser.setVar("maxnumber", maxnum);
WMLBrowser.go("p6.wml#card2");
}
extern function findabs(n)
{
var absnum = Lang.abs(n);
WMLBrowser.setVar("number", n);
WMLBrowser.setVar("absnumber", absnum);
WMLBrowser.go("p6.2.wml#card3");
};
Output:
22
23
VIVA QUESTIONS
WML decks in WAP applications are utilized to structure and present content,
while WMLScript can be incorporated within WML decks to introduce scripting
capabilities and enhance interactivity.
4. What is the process where WML cards request the device to access WAP? -
WMLScript
24
Experiment 7
AIM: Write a Program in NS3 to Simulate OLSR.
Code:
#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/applications-module.h"
#include "ns3/olsr-helper.h"
#include "ns3/ipv4-static-routing-helper.h"
#include "ns3/ipv4-list-routing-helper.h"
NS_LOG_COMPONENT_DEFINE ("SimplePointToPointOlsrExample");
// Allow the user to override any of the defaults and the above
// DefaultValue::Bind ()s at run-time, via command-line arguments
CommandLinecmd;
cmd.Parse (argc, argv);
25
// topologies, we could configure a node factory.
NS_LOG_INFO ("Create nodes.");
NodeContainer c;
c. Create (5);
NodeContainer n02 = NodeContainer (c.Get (0), c.Get (2));
NodeContainer n12 = NodeContainer (c.Get (1), c.Get (2));
NodeContainer n32 = NodeContainer (c.Get (3), c.Get (2));
NodeContainer n34 = NodeContainer (c.Get (3), c.Get (4));
// Enable OLSR
Ipv4StaticRoutingHelper staticRouting;
InternetStackHelper internet;
internet.SetRoutingHelper (list); // has effect on the next Install ()
internet.Install (c);
26
ipv4.SetBase ("10.1.3.0", "255.255.255.0");
Ipv4InterfaceContainer i32 = ipv4.Assign (nd32);
// Create a packet sink to receive these packets apps = sink.Install (c.Get (1));
apps.Start (Seconds (1.1));
apps.Stop (Seconds (10.0));
AsciiTraceHelper ascii;
p2p.EnableAsciiAll (ascii.CreateFileStream ("simple-point-to-point-olsr.tr"));
p2p.EnablePcapAll ("simple-point-to-point-olsr");
return 0;
}
Output:
28
VIVA QUESTIONS
A1: Some security issues in ad hoc networks include node authentication, secure routing, data
confidentiality, denial-of-service attacks, and secure key management.
A2: Multicasting is a communication method in which data is sent from one sender to multiple
recipients simultaneously, allowing efficient data distribution in networks.
A3: MANET stands for Mobile Ad hoc Network, which is a self-configuring network of mobile
devices that communicate without a centralized infrastructure, making it suitable for dynamic and
mobile environments.
29
Experiment 8
AIM: Write a Program in NS3 to Simulate AODV.
Code:
#include "ns3/aodv-module.h"
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/mobility-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/wifi-module.h"
#include "ns3/v4ping-helper.h"
#include <iostream>
#include <cmath>
using namespace ns3;
class AodvExample{
public:
AodvExample ();
bool Configure (int argc, char **argv);
void Run ();
void Report (std::ostream & os);
private:
// network NodeContainernodes;
NetDeviceContainerdevices;
Ipv4InterfaceContainerinterfaces;
private:
void CreateNodes ();
void CreateDevices ();
void InstallInternetStack ();
void InstallApplications ();
};
30
int main (int argc, char **argv)
{
AodvExampletest;
if (!test.Configure (argc, argv))
NS_FATAL_ERROR ("Configuration failed. Aborted.");
test.Run ();
test.Report (std::cout);
return 0;
}
AodvExample::AodvExample () : size (10), step (100), totalTime (10), pcap (true),
printRoutes (true){}
SeedManager::SetSeed (12345);
CommandLinecmd;
void AodvExample::Run ()
{
// Config::SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold",
UintegerValue (1));
// enable rts cts all the time.
CreateNodes ();
CreateDevices ();
InstallInternetStack ();
InstallApplications ();
void AodvExample::CreateNodes ()
{
std::cout <<"Creating "<< (unsigned)size<<" nodes "<<step<<" m apart.\n";
nodes.Create (size);
// Name nodes
for (uint32_t i = 0; i <size; ++i)
{
std::ostringstream os;
os <<"node-"<< i;
Names::Add (os.str (), nodes.Get (i));
}
// Create static grid
MobilityHelpermobility;
mobility.SetPositionAllocator ("ns3::GridPositionAllocator", "MinX", DoubleValue
(0.0),
"MinY", DoubleValue (0.0), "DeltaX", DoubleValue (step), "DeltaY", DoubleValue
(0), "GridWidth", UintegerValue (size),
"LayoutType", StringValue ("RowFirst"));
mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
mobility.Install (nodes);
}
void AodvExample::CreateDevices ()
{
WifiMacHelper wifiMac;
wifiMac.SetType ("ns3::AdhocWifiMac");
YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();
YansWifiChannelHelper wifiChannel = YansWifiChannelHelper::Default ();
wifiPhy.SetChannel (wifiChannel.Create ());
WifiHelperwifi;
wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager", "DataMode",
StringValue ("OfdmRate6Mbps"), "RtsCtsThreshold", UintegerValue (0));
devices = wifi.Install (wifiPhy, wifiMac, nodes);
if (pcap)
{
wifiPhy.EnablePcapAll (std::string ("aodv"));
32
}
}
void AodvExample::InstallInternetStack ()
{
AodvHelper aodv;
// you can configure AODV attributes here using aodv.Set(name, value)
InternetStackHelperstack;
stack.SetRoutingHelper (aodv); // has effect on the next Install ()
stack.Install (nodes);
Ipv4AddressHelperaddress;
address.SetBase ("10.0.0.0", "255.0.0.0");
interfaces = address.Assign (devices);
if (printRoutes)
{
Ptr<OutputStreamWrapper> routingStream = Create<OutputStreamWrapper>
("aodv.routes", std::ios::out);
aodv.PrintRoutingTableAllAt (Seconds (8), routingStream);
}
}
void AodvExample::InstallApplications ()
{
V4PingHelper ping (interfaces.GetAddress (size - 1));
ping.SetAttribute ("Verbose", BooleanValue (true));
33
Output:
34
VIVA QUESTIONS
A1: Routing in ad hoc networks differs from fixed networks as ad hoc networks are decentralized,
self-organizing networks without a centralized infrastructure, where nodes dynamically establish
routes among themselves.
Q2: What is the hidden and exposed terminal problem in ad hoc networks?
A2: The hidden terminal problem in ad hoc networks occurs when two nodes cannot detect each
other's presence due to interference, while the exposed terminal problem arises when a node refrains
from transmitting data due to interference, even though it could transmit without causing actual
interference.
A3: Hiper Access (High-Performance Radio LAN Access) is a wireless LAN access technology that
offers high-speed wireless connectivity, enhanced quality of service (QoS), and improved efficiency
compared to traditional Wi-Fi standards.
A4: Hybrid routing protocols in ad hoc networks combine the features of proactive (table-driven) and
reactive (on-demand) routing protocols. They maintain routing information for changing network
topologies while minimizing control overhead and route discovery latency associated with on-
demand protocols.
35
Experiment 9
THEORY:
After you have successfully installed the Android SDK, it is time to configure it. After installing
the Android SDK, you will get a window like this:
36
Just de-select the Documentation for Android SDK and Samples for SDKpackages if you want
to reduce the installation size and time. Click on Install 7packages to continue with the installation.
You will get a dialogue box like this:
It will take some time to install, Once it is done, you can close the SDK manager.
37
4. Setup Eclipse IDE
Install the latest version of Eclipse. After successful installation, it should display a window like
this:
38
Just click on the Add button as shown in the picture and add https://dl-
ssl.google.com/android/eclipse/ as the location. When you press OK, Eclipse will start to search
for the required plug-in and finally it will list the found plug-ins.
The last step is to create Android Virtual Device, which students will use to test your Android
applications. To do this, open Eclipse and Launch Android AVD Manager from options Window
39
> AVD Manager and click on New which will create a successful Android Virtual Device. Use
the screenshot below to enter the correct values.
Before we write the code, you need to know how to take input from the user. The most efficient
way of taking input from the user is to use the Scanner class, which is found in the java.io package
as it is just a two-step process.
import java.util.Scanner;
import java.util.Random;
String response;
System.out.println();
computerInt = generator.nextInt(3)+1;
computerPlay = "R";
else if (computerInt == 2)
computerPlay = "P";
else if (computerInt == 3)
computerPlay = "S";
// stored as a string
personPlay = scan.next();
personPlay = personPlay.toUpperCase();
if (personPlay.equals(computerPlay))
System.out.println("It's a tie!");
else if (personPlay.equals("R"))
if (computerPlay.equals("S"))
else if (computerPlay.equals("P"))
else if (personPlay.equals("P"))
if (computerPlay.equals("S"))
else if (computerPlay.equals("R"))
42
else if (personPlay.equals("S"))
if (computerPlay.equals("P"))
else if (computerPlay.equals("R"))
else
Now calling the Java code in Eclipse is a tricky process and it helps to pay attention while you're
doing this. Launch Eclipse and click File > New > Java Project
When the Create a Java Project box appears, it's time to give your project a name. Click on Finish
to save it and it should appear in the Package Explorer window. Then we are supposed to add a
package which will contain all our package files. Click on New Java Package icon to do this, as
shown in the screenshot below.
43
Name your project and then click Finish.
Now we need to add a Java Class, which is as easy as adding a Java Package.
44
After giving it a name, make sure that the following options are checked:
45
After you create a new class, it will show up in the Work Space where you can write or copy the
code.
Now you need to build the application and to do this, Right Click on your Android Project and
select Android Tools->Export Signed Application Package. After selecting the export button,
select Create new keystore and it will take you to the location where you want to save it, so give
it a name and save it. Fill in all the required fields that are self-explanatory and save it. You have
successfully exported the apk file to your computer and you can test the app it on your android
device.
8. Testing
Testing is as important as developing the app because your app will be of no use if it doesn't run
properly or shows errors. Luckily, there is an integrated testing framework in Android Framework,
which you can use to test all the aspects of your application. SDK tools can also help set up and
test applications. SDK will help you test different aspects of your app no matterif you are planning
on running your tests within an emulator or any Android device.
It is recommended using ADT for the testing process, as it is comparatively easier than the other
tools. Using ADT, you can easily create a test project and link it to the application under test.
The great thing about the ADT is that it automatically adds thenecessary
<instrumentation> element in the test package's manifest file.
Launch Eclipse from the Start Menu and click on File > New > Other and from the drop-down
menu, click on Android Test Project, then at the bottom of the dialog click Next. Enter any name
you want and in the Test Target panel, set An Existing Android Project and browse to the Rock
Paper Scissors app you made. Now you should be able to see the wizard completing the Test
Target Package, Application Name, and Package Name fields for you.
Choose the Android SDK platform from the Build Target Panel that the application to be tested
is using. Click the Finish button to complete the Wizard and if it is disabled, look for error
messages at the top to fix any problems.
46
VIVA QUESTIONS
A1: An Activity in Android is a component that represents a single screen with a user interface,
where users can interact with the app.
A2: APK (Android Package Kit) is the file format used for distributing and installing Android
applications. It contains the compiled code, resources, and other necessary files required for running
an Android app.
A3: Intent is a messaging object in Android that enables communication between components, such
as activities, services, and broadcast receivers. It can be used to start activities, pass data between
components, and trigger actions.
A4: The Android Manifest file is an XML file in an Android application that provides essential
information about the app to the Android system. It includes details like the app's package name,
permissions, components (activities, services, receivers), and more.
47
Experiment No. 10
AIM: Write a Android Program to create list view, grid view and databaseconnectivity
In android GridView is a view group that display items in two dimensional scrolling grid (rows
and columns), the grid items are not necessarily predetermined but they are automaticallyinserted
to the layout using a ListAdapter. Users can then select any grid item by clicking on it. GridView
is default scrollable so we don’t need to use ScrollView or anything else with GridView.
Adapter Is Used To Fill Data In Gridview: To fill the data in a GridView we simply use adapter
and grid items are automatically inserted to a GridView using an Adapter which pulls the content
from a source such as an arraylist, array or database. You can read full Adapter tutorial here.
GridView in Android Studio: Gridview is present inside Containers. From there you can drag and
drop on virtual mobile screen to create it. Alternatively you can also XML code to create it.
<GridView
android:id="@+id/simpleGridView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numColumns="3"/>
48
Introduction: LIST VIEW
List of scrollable items can be displayed in Android using ListView. It helps you to displaying the
data in the form of a scrollable list. Users can then select any list item by clicking on it. ListView
is default scrollable so we do not need to use scroll View or anything else with ListView.
ListView is widely used in android applications. A very common example of ListView is your
phone contact book, where you have a list of your contacts displayed in a ListView and if you
click on it then user information is displayed.
Adapter: To fill the data in a ListView we simply use adapters. List items are automatically
inserted to a list using an Adapter that pulls the content from a source such as
an arraylist, array or database.
ListView in Android Studio: Listview is present inside Containers. From there you can drag and
drop on virtual mobile screen to create it. Alternatively you can also XML code to create it.
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/simpleListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context="abhiandroid.com.listexample.MainActivity">
</ListView>
49
Introduction: Database Connectivity SQLite
SQLite is a relational database management system (RDBMS). If most RDBMSs such asMySQL,
Oracle, etc. are standalone server processes, then SQLite is embedded because it is provided in the
form of a library that is linked in applications.
Like other RDBMSs, data is accessed in a SQLite database by using Structured Query Language
(SQL).
Cursor: a class provides access to the results of a database query. Its methods include:
getCount(): returns the number of rows contained within the result set.
move(): moves by a specified offset from the current position in the result set.
get<type>() (such as getInt(), getDouble(), so on): returns the value of the specified <type>
contained at the specified column index of the row at the current cursor position.
SQLiteDatabase: provides the primary interface between the application code and underlying
SQLite database. Its methods include:
query(): performs a specified database query and returns matching results via a Cursor object.
execSQL(): executes a single SQL Statement that does not return result data.
rawQuery(): executes an SQL query statement and returns matching results in the form of a
Cursor object.
SQLiteOpenHelper : is designed to make it easier to create and update databases. Its methods
include:
onCreate(): called when the database is created for the first time.
onUpgrade(): called in the event that the application code contains a more recent database
version number reference.
50
getWritableDatabase(): opens or creates a database for reading and writing.
ContentValues : allows key/value pairs to be declared consisting of table column identifiers and
the values to be stored in each column. Its methods include:
For Example: Creating a Data Application, we have to follow certain steps as follows.
My application will interact with a database named StudentDB.db, which contains a single table
named Student. The Student table schema will look like this:
The application will consist of an activity and a database handler class (MyDBHandler class). The
database handler will be a subclass of SQLiteOpenHelper and will provide an abstract layer
between the underlying SQLite database and the activity class. A third class (Student class) will
need to be implemented to hold the database entry data as it is passed between the activity and the
handler. My application model can be shown in the following figure:
51
Data Model Class
The Student class contains fields, constructors, and properties as follows:
We create the Student class in the Android Studio by selecting app > java.
52
Right-click the myfirstdatabase package and selecting New > Java Class.
Type Student in the Name item, maintain the default options, and click the OK button:
54
Steps for creating the MyDBHandler class like the Student class and its code can look like this:
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.Context;
import android.content.ContentValues;
import android.database.Cursor;
Initialize the Database
The database can be initialized in the constructor of the MyDBHandler class. The code of this
constructor looks like this:
Load Data
The result of above SQL statement is a table. We use the rawQuery() method of a SQLiteDatabase
object to implement SQL statement and display result via a Cursor object. The following code will
demonstrate the loadHandler method:
56
Add a New Record
To add a new record to the database, we must use the ContentValues object with the put()
method that is used to assign data to ContentsValues object and then use insert() method of
SQLiteDatabase object to insert data to the database. The addHandler method can look like this:
57
VIVA QUESTIONS
A1: View group in Android is a class that acts as a container for other view elements, allowing them
to be organized and positioned within the user interface hierarchy.
A2: Content Provider in Android is a component that manages access to a structured set of data,
enabling other applications to query, insert, update, and delete data through a standard interface.
A3: Container in Android refers to a type of view group that provides a way to organize and group
multiple views together, allowing them to be treated as a single entity for layout and interaction
purposes.
A4: ADB (Android Debug Bridge) is a command-line tool used for communication with an Android
device or emulator, enabling various debugging and development tasks. ANR (Application Not
Responding) refers to a condition in which the user interface of an Android application becomes
unresponsive, usually due to long-running operations on the main thread, leading to a potential
system dialog or termination of the application.
58
Experiment 11
AIM: Write a program to design a calling application.
Source Code:
package com.example.callingapp;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import
android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import
android.widget.ImageButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_call);
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.call, menu);
return true;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
59
// Call a Number
Output:
60
Experiment 12
AIM: Write a program to design a Mailing application.
Source Code:
package
com.example.emailapp;
import android.os.Bundle;
import android.app.Activity;
import
android.content.Intent;
import android.view.Menu;
import android.view.View;
import
android.view.View.OnClickListener;
import android.widget.EditText;
import
android.widget.ImageButton;
import android.widget.Toast;
et1 = (EditText)
findViewById(R.id.editText1); et2 =
(EditText)
findViewById(R.id.editText2); et3 =
(EditText)
findViewById(R.id.editText3);
ib1 = (ImageButton) findViewById(R.id.imageButton1);
ib1.setOnClickListener(this);
@Override
String emailid =
et1.getText().toString();String[]
emails = { emailid };
String subject =
et2.getText().toString(); String
message = et3.getText().toString();
62
63