Mobile Computing File Format Vivek
Mobile Computing File Format Vivek
(ETIT 452)
Course outcomes
ETIT‐452 Student should be able to understand and recall the basic concept of WML
.1 (L1, L2)
ETIT‐452 Student should be able to apply WML programing to develop basic mobile
.2 applications and services. (L3, L6)
ETIT‐452 Student should be able to analyze typical functionalities of modern
.3 smartphones and should able to evaluate a mobile phone’s quality. (L4, L5).
ETIT‐452
Student should be able to create an android application. (L6)
.4
CO MOBILE COMPUTING
ETIT-452 PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
ETIT452.1 3 3 3 3 3 3 1 1 1 2 1 3
ETIT452.2 3 3 3 3 3 2 1 1 1 2 1 3
ETIT452.3 3 3 3 3 3 2 1 1 1 2 1 3
ETIT452.4 3 3 2 3 3 2 1 1 1 2 1 3
Rubrics Evaluation
1. Index for the Lab File is as follows:
PRACTICAL RECORD
PRACTICAL DETAILS
2.
3.
4.
5.
b) Experiments beyond the list provided by GGSIPU
2.
3.
4.
5.
LIST OF EXPERIMENTS
1. Write a WML program to print a formatted Text on the mobile Screen using varioustags.
2. Write a WML program to connect multiple cards from same desk.
3. Write WML program to display table with three columns Image name, Image and thirdcolumn
contain hyperlink to open another card.
4. Write a WML program to create a form with multiple options.
5. Write a WML program to use the time control and to trigger On pick event
6. Write a WML script to find maximum out of two numbers with help of inbuilt functionLang.Max()
and to find absolute value with help of inbuilt function Lang.abs()
7. Write a Program in NS3 to Simulate OLSR
8. Write a Program in NS3 to Simulate AODV
9. Make an application of your choice using WML or Android.
10. Write a Android Program design an application using Hybrid Approah
List of Experiment
(Beyond Curriculum)
a. Syntax
<p>
..text..
..images..
..links..
</p>
b. WML Tags and Attributes
OUTPUT:
Viva Questions
The <anchor>...</anchor> tag pair is used to create an anchor link. It is used together with other
WML elements called <go/>, <refresh> or <prev/>. These elements are called task elements and
tell WAP browsers what to do when a user selects the anchor link
You can enclose Text or image along with a task tag inside <anchor>...</anchor> tag pair.
Attributes:
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="Anchor Element">
<p>
<anchor>
<go href="nextpage.wml"/>
</anchor>
</p>
<p>
<anchor>
<prev/>
</anchor>
</p>
</card>
</wml>
Output:
Viva Questions
The <table> element along with <tr> and <td> is used to create a table in WML. WML does not
allow the nesting of tables
Attributes:
<wml>
<card title="WML Tables">
<p>
<table columns="3" align="LCR">
<tr>
<td>Col 1</td>
<td>Col 2</td>
<td>Col 3</td>
</tr>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
</tr>
<tr>
<td>D</td>
<td>E</td>
<td>F</td>
</tr>
</table>
</p>
</card>
</wml>
OUTPUT:
12.1: Write WML program to display user personal information like Id, Name, Address,
Phone No and pass same information on another deck.
The <input/> element is used to create input fields and input fields are used to obtain
alphanumeric data from users.
Attributes:
OUTPUT:
12.3 Short Questions:
WML<select>Element:
The <select>...</select> WML elements are used to define a selection list and the
<option>...</option> tags are used to define an item in a selection list. Items are presented as
radiobuttons in some WAP browsers. The <option>...</option> tag pair should be enclosed within
the <select>...</select> tags.
Attributes:
iname text Names the variable that is set with the index result
of the selection
name text Names the variable that is set with the result of the
selection
tabindex number Sets the tabbing position for the select element
title text Sets a title for the list
value text Sets the default value of the variable in the "name"
attribute
xml:lang language_code Sets the language used in the element
class class data Sets a class name for the element.
id element ID A unique ID for the element.
<wml>
<card title="Selectable List">
<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>
For Multiple Options:
<wml>
<card title="Selectable List">
<p> Select a Tutorial :
<select multiple="true">
<option value="htm">WML Tutorial A</option>
<option value="xml">WML Tutorial B</option>
<option value="wap">WML Tutorial C</option>
</select>
</p>
</card>
</wml>
OUTPUT:
Output:
13.4 Short Questions:
Q.No.2 List out the Databases used to store Data of WML pages?
The ontimer event is used to trigger an event after a given time period. Suppose students wants
to display a message after 5 seconds of loading a card then you can use this event to do so.
<timer value="50"/>
OUTPUT:
When you load this program, it shows you the following screen:
If you do not select given Enter option then after 5 seconds you will be directed to welcome page
and following screen will be displayed automatically.
5.1 Write a WML program to trigger On pick event
The onpick attribute is a great shortcut if you are using a select menu. Instead of writing a lot of
code that allows the user to go to another card if an option is selected, you can simply place the
destination into the onpick attribute.
Select a tutorial :
<select title="tutorials" name="selection_list">
<option onpick="#xhtml">XHTML Tutorial</option>
<option onpick="#wap">WAP Tutorial</option>
</select>
Output:
14.3 Short Questions:
Q.No.1 Does WAP run over GPRS?
The Lang.max function compares two given numbers and then returns the larger value. If the
two numbers prove to be equal, the first number is selected. The value and type (floating-point
or integer) of the selected number is not changed.
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("MaxExample.wml#card2");
};
OUTPUT:
Syntax: Lang.abs(value)
Value: The mandatory value parameter can be any positive or negative single-precision floating-
point number or any positive or negative integer number (including zero). The floating-point
number must reside on or between the largest number and the smallest nonzero number supported
by the browser. These boundary values can be determined using the Float.maxFloat and
Float.minFloat functions.
Output:
Short Questions:
4. What is the process where WML cards request the device to access WAP? - WMLScript
6. What is the process of adding the client side logic to WAP using WMLScript?
1. Create a wireless mobile ad-hoc network with three nodes Node1, Node2 and Node3. Install the
OLSR routing protocol on these nodes.
2. Place them such that Node1 and Node3 are just out of reach of each other.
3. Create a UDP client on Node1 and the corresponding server on Node3.
4. Schedule Node1 to begin sending packets to Node3 at time 1s.
5. Verify whether Node1 is able to send packets to Node3.
6. Make Node2 move between Node1 and Node3 such that Node2 is visible to both A and C. This
should happen at time 20s. Ensure that Node2 stays in that position for another 15s.
7. Verify whether Node1 is able to send packets to Node3.
8. At time 35s, move Node2 out of the region between Node1 and Node3 such that it is out of
each other's transmission ranges again.
9. Verify whether Node1 is able to send packets to Node3.
10. To verify whether data transmissions occur in the above scenarios, use either the tracing
mechanism or a RecvCallback() for Node3's socket.
11. Plot the number of bytes received versus time at Node3.
12. Show the pcap traces at Node 2's Wifi interface, and indicate the correlation between Node2's
packet reception timeline and Node2's mobility.
Network topology
// n0
\ 5 Mb/s, 2ms
\ 1.5Mb/s, 10ms
n2 n3 n4
/
/ 5 Mb/s, 2ms
n1
// - all links are point-to-point links with indicated one-way BW/delay
// - CBR/UDP flows from n0 to n4, and from n3 to n1
// - UDP packet size of 210 bytes, with per-packet interval 0.00375 sec.
// (i.e., DataRate of 448,000 bps)
// - DropTail queues
// - Tracing of queues and packet receptions to file "simple-point-to-point-olsr.tr"
16.2 Program:
#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");
int
main (int argc, char *argv[])
{
// Users may find it convenient to turn on explicit debugging
// for selected modules; the below lines suggest how to do this
#if 0
LogComponentEnable ("SimpleGlobalRoutingExample", LOG_LEVEL_INFO);
#endif
// 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);
// Enable OLSR
NS_LOG_INFO ("Enabling OLSR Routing.");
OlsrHelperolsr;
Ipv4StaticRoutingHelper staticRouting;
Ipv4ListRoutingHelperlist;
list.Add (staticRouting, 0);
list.Add (olsr, 10);
InternetStackHelper internet;
internet.SetRoutingHelper (list); // has effect on the next Install ()
internet.Install (c);
AsciiTraceHelper ascii;
p2p.EnableAsciiAll (ascii.CreateFileStream ("simple-point-to-point-olsr.tr"));
p2p.EnablePcapAll ("simple-point-to-point-olsr");
return 0;
}
AIM: Write a program to show the introduction of multi point relay set as a subset of the
neighbor set does not destroy the connectivity properties of the network
Output:
Short Questions:
Introduction
Ad hoc On-Demand Distance Vector (AODV) [1] is a routing protocol for mobile ad-hoc net-
works. AODV is a reactive routing protocol which means that routes are discovered
when necessary, routes are also maintained as long as necessary. Every node maintains its
monoton- ically increasing sequence number which increases every time the node notices
change in the neighborhood topology. Routing tables are used to store routing information
where data is stored as follows:
<destination addr, next-hop addr, destination sequence number,
life_time>
life_time gets updated every time the route is used (If not used within its life_time,
route expires).
AODV Routing Protocol works as follows: Assuming in the network in the figure
below we need to discover route between S and D.
Figure 1: AODV protocol working on five nodes.
It works as follows:
(b) It has a route to D, and the seq # for route to D is >= D 0 s seq # in
RREQ (c) C creates a Route Reply (RREP)
Program
Source 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>
private:
// parameters
uint32_t size;
doublestep;
doubletotalTime;
boolpcap;
boolprintRoutes;
// network
NodeContainernodes;
NetDeviceContainerdevices;
Ipv4InterfaceContainerinterfaces;
private:
void CreateNodes ();
void CreateDevices ();
void InstallInternetStack ();
void InstallApplications ();
};
test.Run ();
test.Report (std::cout);
return 0;
}
//
AodvExample::AodvExample () :
size (10),
step (100),
totalTime (10),
pcap (true),
printRoutes (true)
{
}
bool
AodvExample::Configure (int argc, char **argv)
{
// Enable AODV logs by default. Comment this if too noisy
// LogComponentEnable("AodvRoutingProtocol", LOG_LEVEL_ALL);
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::Report (std::ostream &)
{
}
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"));
}
}
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));
Output:
Short Questions
Steps:
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:
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.
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
> 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"))
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.
Name your project and then click Finish.
Now we need to add a Java Class, which is as easy as adding a Java Package.
After giving it a name, make sure that the following options are checked:
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.
18.3 Short Questions:
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.
android:id="@+id/simpleGridView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numColumns="3"/>
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.
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>
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.
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:
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.
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:
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:
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:
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
// Call a Number
Output:
Experiment 12 (Beyond Curricula)
a. 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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_email);
et1 = (EditText)
findViewById(R.id.editText1); et2 =
(EditText)
findViewById(R.id.editText2); et3 =
(EditText)
findViewById(R.id.editText3);
ib1.setOnClickListener(this);
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.email, menu);
return true;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Program
MainActivity.java
package com.gpslocationtracker;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import
android.view.MenuItem;
import
android.widget.TextView;
{ TextView textview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (gpsTracker.canGetLocation())
{
String stringLatitude = String.valueOf(gpsTracker.latitude);
textview = (TextView)findViewById(R.id.fieldLatitude);
textview.setText(stringLatitude);
String stringLongitude =
String.valueOf(gpsTracker.longitude); textview =
(TextView)findViewById(R.id.fieldLongitude);
textview.setText(stringLongitude);
}
else
{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gpsTracker.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;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in
AndroidManifest.xml. int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
a. GPSTracker.java
package com.gpslocationtracker;
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;
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
Location location;
double latitude;
double longitude;
Log.d("Network", "Network"); if
(locationManager != null)
{
location =
locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateGPSCoordinates();
}
}
if (locationManager != null)
{
location =
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateGPSCoordinates();
}
}
}
}
}
catch (Exception e)
{
//e.printStackTrace();
Log.e("Error : Location", "Impossible to connect to LocationManager", e);
}
return location;
}
return latitude;
}
return longitude;
}
}
);
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
//On pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
alertDialog.show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
return null;
OUTPUT
Experiment 14 (Beyond Curricula)
package com.example.multipleactivities;
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.Toast;
bt1.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.first, menu);
return true;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}else {
Intent next = new Intent(this, SecondActivity.class);
next.putExtra("NAME", name);
next.putExtra("NUMBER", number);
startActivity(next);
finish();
}
}
}
a. SecondActivity.java
package com.example.multipleactivities;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
bt1.setOnClickListener(this);
bt2.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.button_main:
Intent main = new Intent(this, FirstActivity.class); startActivity(main);
finish(); break;
case R.id.button_exit:
Toast.makeText(this, "Bye !", Toast.LENGTH_SHORT).show(); finish();
break;
}
}
}
Experiment 15 (Beyond Curricula)
Aim: Write a program to design a contacts application.
a. Source Code:
DatabaseActivity.java
package com.example.contactsapp;
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.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_database);
bt1.setOnClickListener(this);
bt2.setOnClickListener(this);
bt3.setOnClickListener(this);
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.database, menu);
return true;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.button_save:
break;
case R.id.button_view:
case R.id.button_exit:
finish();
break;
}
b. DBHelper.java
package com.example.contactsapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
94 Mobile Computing ETIT 452
public static final String createQuery = "CREATE TABLE " + DB_TABLE + "(" + DB_CNAME + "
TEXT, " + DB_CNUMBER + " TEXT);" ;
context;
private SQLiteDatabase db;
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(createQuery);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Department of Information Technology, MAIT
94 Mobile Computing ETIT 452
}
return result;
}
}
c. ViewActivity.java
package com.example.contactsapp;
import android.app.Activity; import
android.content.Intent; import
android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener; import
android.widget.Button;
import android.widget.TextView;
TextView tv;
Button bt1, bt2;
super.onCreate(savedInstanceState); setContentView(R.layout.view_activity);
bt1.setOnClickListener(this);
bt2.setOnClickListener(this);
tv.setText(result);
}
@Override
public void onClick(View v) {
// TODO Auto-generated
method stub
switch(v.getId()){
case R.id.button_home:
case R.id.button_exit1:
finish(); break;
}
}
}