Post on 11-Mar-2020
1
DIRECTORATE OF TECHNICAL EDUCATION, CHENNAI-25
DIPLOMA EXAMINATIONS-APRIL-2019
DEPT : COMPUTER ENGINEERING
SUBJECT : MOBILE COMPUTING
QCODE/SUB CODE : 915/35262
PART -A
1. Define LAN.[ 2 marks]
A local-area network (LAN) is a computer network that spans a relatively small area.
Most often, LAN is confined to a single room, building or group of buildings, however, one
LAN can be connected to other LANs over any distance via telephone lines and radio waves.
2. What is meant by Adhoc? [ 2 marks]
An ad hoc network is a network that is composed of individual devices communicating
with each other directly. The term implies spontaneous or impromptu construction because
these networks often bypass the gatekeeping hardware or central access point such as a router
3. What is GSM network? [ 2 marks]
GSM stands for Global System for Mobile Communication. GSM is the most widely
accepted standard in telecommunications and it is implemented globally. It is a digital
cellular technology used for transmitting mobile voice and data services.
4. Write the limitation of GPRS. [ 2 marks]
Although GPRS will provide better data rates than is currently available, there are
some limitations.
• Speeds of 177.2kbps would require a user to use all eight timeslots without
any error protection - which simply won't happen. Initial terminals are likely
to use only 1-3 timeslots anyway, limiting the available bandwidth to a GPRS
user.
• When GPRS packets are sent to a destination they are sent in all different directions
- allowing for the potential for one or some of those packets to be corrupted
or even lost altogether during the data transmission over the radio link. This is
inherent in wireless packet technologies so data integrity and retransmission
strategies are incorporated - which in turn result in potential transit delays.
2
Although available radio resource can be concurrently shared between several users, an
increase in the numbers of users will slow data services down for each user.
5. Define DVM. [ 2 marks]
The Dalvik Virtual Machine (DVM) is an android virtual machine optimized for mobile
devices. It optimizes the virtual machine for memory, battery life and performance. The
Dalvik VM was written by Dan Bornstein. The Dex compiler converts the class files into the .
dex file that run on the Dalvik VM.
6. Define auto completes text view. [ 2 marks]
Auto complete Text View is an editable text view that shows
completion suggestions automatically while the user is typing. The list of suggestions is
displayed in a drop down menu from which the user can choose an item.
7. What is the uses of grid view? [ 2 marks]
Android GridView. Android GridView layout in one of the most useful layouts
in android. GridView is mainly useful when we want show data in grid layout like displaying
images or icons. This layout can be used to build applications like image viewer, audio or
video players in order to show elements in grid manner.
8. What is meant by SQLite? [ 2 marks]
SQLite is a software library that implements a self-contained, serverless, zero-
configuration, transactional SQL database engine. SQLite is the most widely deployed
SQL database engine in the world. The source code for SQLite is in the public domain.
This tutorial will give you a quick start with SQLite and make you comfortable with
SQLite programming.
PART-B
9. What is meant by mobile computing? [ 3 marks]
Mobile Computing is a technology that allows transmission of data, voice and
video via a computer or any other wireless enabled device without having to be
connected to a fixed physical link. The main concept involves −
Mobile communication
Mobile hardware
Mobile software
3
10. List out the application of tier-2,tier-3. [ 3 marks]
Application (Tier-2)
• This layer plays an important role in wireless LAN applications.
• It aces as interface between the Presentation Layer and the Data Layer.
• It processes the user input, obtains the information and makes the decisions.
• It uses the technologies like .NET, JAVA, ZEND.
Data (Tier-3)
• Data layer includes the database systems in which the processed data can be
stored and retrieved.
11. Describe about CDMA. [ 3 marks]
. Code Division Multiple Access (CDMA) is a digital cellular technology used for
mobile communication. CDMA is the base on which access methods such as cdmaOne,
CDMA- 2000, and WCDMA are built. The CDMA is a digital modulation and radio
access system that acts as a signature codes to arrange simultaneous and continuous
access to a radio network by multiple uses. CDMA cellular systems are deemed superior
to FDMA and TDMA, which is why CDMA plays a critical role in building efficient,
robust, and secure radio communication systems
12. Discuss any three strengths of SMS. [ 3 marks]
The following are the Strength of SMS
Always Connected
As SMS uses the SS7 signaling channel for its data traffic, the bearer media is
always on. Users cannot switch OFF, BAR or DIVERT any SMS message.
SMS message is delivered to the Mobile Station without any interruption to
the ongoing call.
Self Configurable and last mile problem resistant
SMS is self configurable and subscriber is always connected to the SMS
bearer irrespective of the home and visiting network configuration.
Asynchronous
4
SMS is completely an Asynchronous. In case of SMS, even if the recipient is
out of service the transmission will not be abandoned and the particular SMS
will be placed in the message queue.
13. Explain reverse geocoding. [ 3 marks]
Android Geocoding refers to transforming street address or any address into latitude
and longitude. Reverse Geocoding refers to transforming latitude and longitude into its
corresponding street address.
Address class helps in fetching the street address, locality, sub-locality, city, country,
landmark etc. features of the location.
14. Explain about the option menu and context menu. [ 3 marks]
A context menu (also called contextual, shortcut, and pop up or pop-up menu) is a
menu in a graphical user interface (GUI) that appears upon user interaction, such as a
right-click mouse operation. A context menu offers a limited set of choices that are
available in the current state, or context,
Android Option Menus are the primary menus of android. They can be used for settings,
search, delete item etc.
15. Explain about the android SDK and ADT. [ 3 marks]
The Android SDK (software development kit) is a set of development tools used to
develop applications for Android platform. The Android SDK includes the following:
Required libraries
Debugger
An emulator
Relevant documentation for the Android application program interfaces (APIs)
Sample source code
Tutorials for the Android OS
ADT
5
ADT (Android Developer Tools) is a plugin for Eclipse that provides a suite of
tools that are integrated with the Eclipse IDE. It offers you access to many features that
help you develop Android applications quickly. ADT provides GUI access to many of the
command line SDK tools as well as a UI design tool for rapid prototyping, designing, and
building of your application's user interface
16. Write a note on calling build in applications. [ 3 marks]
Android provides Built-in applications for phone calls, in some occasions we may need to
make a phone call through our application. This could easily be done by using implicit
Intent with appropriate actions. Also, we can use PhoneStateListener and
TelephonyManager classes, in order to monitor the changes in some telephony states on
the device.
PART-C
17. (a) Explain the architecture of mobile computing tier 1,2. [Description- 7marks,
diagram -3 marks]
A 3-tier architecture is an application program that is organized into three major parts,
comprising of:
• The data access layer tier at the bottom,
• The application tier (business logic) in the middle and
• The client tier (presentation) at the top.
Each tier is distributed to a different place or places in a network. These tiers do not
necessarily correspond to physical locations on various computers on a network, but
rather to logical layers of the application.
6
1. Presentation Layer (UI):
• This layer presents data to the user and optionally permits data manipulation and data
entry, also this layer requests the data form Business layer.
• This layer accomplished through use of Dynamic HTML and client-side data sources and
data cursors.
2. Business Logic Layer:
• The business logic acts as the server for client requests from workstations. It acts
according Business rules fetch or insert data through the Data Layer.
• In turn, it determines what data is needed (and where it is located) and acts as a client in
relation to a third tier of programming that might be located on a local or mainframe
computer.
7
• Because these middle-tier components are not tied to a specific client, they can be used
by all applications and can be moved to different locations, as response time and other
rules require.
(OR)
(b) Explain about the wireless LAN and its application.write the features of
WI-FI and WI-MAX. [Description- 10marks]
Wireless Network
Wireless LAN stands for Wireless Local Area Network. It is also called LAWN (Local Area
Wireless Network). WLAN is one in which a mobile user can connect to a Local Area Network
(LAN) through a wireless connection.
The IEEE 802.11 group of standards defines the technologies for wireless LANs. For path
sharing, 802.11 standard uses the Ethernet protocol and CSMA/CA (carrier sense multiple access
with collision avoidance). It also uses an encryption method i.e. wired equivalent privacy
algorithm.
Wireless LANs provide high speed data communication in small areas such as
building or an office.
WLANs allow users to move around in a confined area while they are still connected
to the network.
• Computer is connected to one network technology without wires.
• It is used for communication and data transmission with the help of different
types of waves.
• It reduces the installation time and cable costs.
Wi-Fi
• The full form is Wireless Fidelity.
• Accessible Range is upto 50 meters
8
• Data transfer rate is 7 MBPS
• 10 times higher than Bluetooth technology
• User no need to by other access point equipments, when use Wi-Fi It is used in
Colleges, Offices, Conference Hall, etc.,
WiMAX
High Capacity Load Balancing. ...
Scalability. ...
Network Management System. ...
Role Based Access Control. ...
Indoor as well as Outdoor coverage options. ...
Ability to Measure Performance.
Network Access Control. ...
Ability to communicate with both 2.4 GHz devices and 5 GHz devices
providing 30 miles broadband access to mobile users.
WiMAX technology based on IEEE 802.16 standard and it is a telecommunication
protocol offering full access to mobile internet across cities and countries with a
wide range of devices.
WiMAX technology has salient features as described below.
18. (a) Explain in detail about the Linux Kernel based mobile OS. [Description-
10marks]
Linux Kernel based mobile operating system is Android OS. It is developed by
Google Corporation. Android OS give the open choice to the user to modify and add
any new applications without even bring on the notice of Google.
Android is the Linux based technology tat uses Unix as an Operating System. Any
one can upload a new application on the Android Platform as App store to entire free
or payable. These applications uploads by the users can be easily download by the
users and enjoy the additional games, interactive media and business parts.
Thus the flexibility of Android technology makes it more convenient to the operating
system to have this as a base for smart phones.
Operating systems
9
This is a list of many Linux kernel-based operating systems used on mobile devices. They
differ from one another in parts of the middleware or the entire middleware, and in that they
employ individual UIs.
List of Linux kernel based OS.
Android (operating system)
AsteroidOS
Plasma Mobile
postmarketOS
Sailfish OS
SHR (operating system)
Tizen
Ubuntu Touch (discontinued by Canonical, adopted by UBports Community)
webOS
LuneOS (based on HP webOS)
PureOS
Firefox OS (discontinued)
Openmoko Linux (discontinued)
OpenZaurus (discontinued)
Bada (discontinued)
Maemo Leste (fork of discontinued Maemo based on Devuan)
Moblin (discontinued)
MeeGo (discontinued)
Middlewares
BusyBox
Toybox
Smart Common Input Method
Maliit
Intelligent Input Bus
Uim
Fcitx
Halium
UI
Unity
10
KDE Plasma Workspaces
GPE Palmtop Environment
OPIE user interface
Phosh
(OR)
(b) Explain about the architecture of SMS with a neat diagram. [Description- 7marks,
diagram -3 marks]
Short Message Service
Today, SMS is the most popular data bearer / service with in GSM with an
average of one billion SMS messages transacted every day around the world. Short
Message Service is a mechanism of delivery of short messages over the mobile
networks. It is a store and forward way of transmitting messages to and from
mobiles. The message (text only) from the sending mobile is stored in a Central Short
Message Centre, which then forwards it to the destination mobile. This means that in
the case that the recipient is not available the short message is stored and can be sent
later.
Each short message is up to 160 characters. These characters can be text or
binary Non-Text Short messages. SMS used signaling channels as opposed to
dedicated channels, so that these messages can be sent / received simultaneously
with the voice / data / fax service over a GSM network.
SMS supports national and international roaming. This means that you can
send short messages to any other GSM mobile user around the world.
Strength of SMS
The following are the Strength of SMS
11
Always Connected
As SMS uses the SS7 signaling channel for its data traffic, the bearer media is always
on. Users cannot switch OFF, BAR or DIVERT any SMS message. SMS message is
delivered to the Mobile Station without any interruption to the ongoing call.
Self Configurable and last mile problem resistant
SMS is self configurable and subscriber is always connected to the SMS bearer
irrespective of the home and visiting network configuration.
Asynchronous
SMS is completely an Asynchronous. In case of SMS, even if the recipient is out of
service the transmission will not be abandoned and the particular SMS will be placed
in the message queue.
Stateless
SMS is session-less and stateless as every SMS message is unidirectional and
independent of any contest. This makes SMS the best bearer for notifications, alerts
and paging.
Omnibus nature of SMS
SMS uses SS7 signaling channel which is available throughout the world.
Non-repudiable
SMS message carries the Service Center and the source MSISDN as a part of the
message header through which any SMS can prove beyond doubt its origin.
SMS Architecture
At the beginning, if a user sends a SMS, the SMS first deliver from the MS which is
know as Mobile Station A to SM-SC (Short Message Service Center) Via the Base
Station System (BSS), and then it catch up to the Mobile Station center(MSC) and
12
finally combine with Interworking MSC (IW-MSC). The following Figure (Fig. 2.2)
explain the architecture of SMS.
Content aggregator uses the SMPP (Short Message Peer-to-peer Protocol) to
maintain connections with carrier networks.
Content Providers
A mobile content provider is an entity that provides value-added content and
applications for mobile devices.
When a mobile phone user sends an interactive text message to retrieve
information, the content provider returns the information through the aggregator. The
aggregator is responsible for transmitting the message to the end user.
SMS Centers
When the user sends a text message to another user, the phone actually sends the
message to the SMSC, which stores the message and then delivers it, when the
recipient is on the network. This is the store and forward operation.
13
The use of Short Message Service Center (SM-SC) to carry ahead the SMS message
to the GSM network through a definite GSM-MSC called the Short Message Service
gateway MSC (SMS-GMSC). The SM-SC is allowed to link with several GSM
networks and to several SM- GMSCs in a GSM network. The SMS-GMSC come
across the contemporary MSC of the message acceptor and then step ahead the SMS
message to that Mobile Station center, pursue the Global System for Mobile
Communication (GSM) roaming protocol. The MSC then Publish the SMS through
the Base Station System (BSS) to the destination MSB.
Value added services through SMS
Value Added Services (VAS) can be defined as services, which share one or
more of the following characteristics.
• Supplementary service but adds value to total service offering
• Stimulates incremental demand for core services offering
• Stands alone in terms of profitability and revenue generation potential
• Can sometimes stand-alone operationally
• Does not cannibalize basic service unless clearly favorable
• Can be an add-on basic service, and as such, may be sold at a premium price
• May provide operational and / or administrative synergy between or
among other services and not merely for diversification.
Some examples
• News/Stock Quotes Service
• Session-based Chat Application
• Email through SMS
• Health Care Services
Micro-payment Services
14
19.(a) Explain about the architecture of android with a neat diagram. [Description-
7marks, diagram -3 marks]
Android operating system is a stack of software components which is roughly divided into
five sections and four main layers as shown below in the architecture diagram.
Applications
You will find all the Android application at the top layer. You will write your application to be
installed on this layer only. Examples of such applications are Contacts Books, Browser, Games
etc.
Application Framework
The Application Framework layer provides many higher-level services to applications in the
form of Java classes. Application developers are allowed to make use of these services in their
applications.
The Android framework includes the following key services −
• Activity Manager − Controls all aspects of the application lifecycle and activity stack.
• Content Providers − Allows applications to publish and share data with other
applications.
• Resource Manager − Provides access to non-code embedded resources such as strings,
color settings and user interface layouts.
• Notifications Manager − Allows applications to display alerts and notifications to the
user.
• View System − An extensible set of views used to create application user interfaces.
15
Android Runtime
This is the third section of the architecture and available on the second layer from the bottom.
This section provides a key component called Dalvik Virtual Machine which is a kind of Java
Virtual Machine specially designed and optimized for Android.
The Dalvik VM makes use of Linux core features like memory management and multi-
threading, which is intrinsic in the Java language. The Dalvik VM enables every Android
application to run in its own process, with its own instance of the Dalvik virtual machine.
The Android runtime also provides a set of core libraries which enable Android application
developers to write Android applications using standard Java programming language.
Libraries
On top of Linux kernel there is a set of libraries including open-source Web browser engine
WebKit, well known library libc, SQLite database which is a useful repository for storage and
16
sharing of application data, libraries to play and record audio and video, SSL libraries
responsible for Internet security etc.
Linux kernel
At the bottom of the layers is Linux - Linux 3.6 with approximately 115 patches. This provides
a level of abstraction between the device hardware and it contains all the essential hardware
drivers like camera, keypad, display etc. Also, the kernel handles all the things that Linux is
really good at such as networking and a vast array of device drivers, which take the pain out of
interfacing to peripheral hardware.
(OR)
(b) Explain about the android development tool. write about the installing and
configuring android os. [Description- 5marks, diagram -5 marks]
ADT (Android Developer Tools) is a plugin for Eclipse that provides a suite of tools that are
integrated with the Eclipse IDE. It offers you access to many features that help you develop
Android applications quickly. ADT provides GUI access to many of the command line SDK
tools as well as a UI design tool for rapid prototyping, designing, and building of your
application's user interface.
Because ADT is a plugin for Eclipse, you get the functionality of a well-established IDE, along
with Android-specific features that are bundled with ADT. The following describes important
features of Eclipse and ADT
INSTALLING AND CONFIGURING ANDROID
I launched android-studio-ide-181.5056338-windows.exe to start the installation process. The
installer responded by presenting the Android Studio Setup dialog box shown in Figure 1.
17
Figure 1. Set up Android Studio
Clicking Next took me to the following panel, which provides the option to decline installing an
Android Virtual Device (AVD).
Figure 2. Install an Android AVD?
I chose to keep the default settings. After clicking Next, I was taken to the Configuration
Settings panel, where I was asked to choose where to install Android Studio.
Figure 3. The installation location must have at least 500 MB free space
I kept the default installation location and clicked Next, and was greeted with the Choose Start
Menu Folder panel.
18
Figure 4. Select the folder in which to store Android Studio shortcuts
I kept the default setting and clicked Install. The following Installing panel appeared:
Figure 5. This panel shows the progress of the installation
Clicking Show details causes the names of files being installed and other activities to be
displayed. When installation finished, the Installation Complete panel appeared.
Figure 6. The Next button is enabled when installation completes
After clicking Next, the installer presented the Completing Android Studio Setup panel.
19
Figure 7. Leave the Start Android Studio checkbox checked to run this software
To complete the installation, I left the Start Android Studio box checked and clicked Finish.
Running Android Studio
The first time Android Studio runs, it presents a Complete Installation dialog box that offers the
option of importing settings from a previous installation.
Figure 8. A previous installation's settings can be imported
I chose not to import settings (the default selection) and clicked OK, and was rewarded with the
following splash screen:
20
Figure 9. Android Studio's splash screen
I also observed the following Finding Available SDK Components message box.
Figure 10. Android Studio downloads any SDK components that are needed (and available)
At this point, Android Studio presented the following Android Studio Setup Wizard dialog box:
Figure 11. The wizard provides setup and app-porting capabilities (click to enlarge
I clicked Next, and the wizard invited me to select an installation type. I kept the default standard
setting.
21
Figure 12. Choose an installation type (click to enlarge)
I was then given the opportunity to choose a user interface theme.
Figure 13. Put the bite on Android Studio by choosing the Darcula theme (click to enlarge)
I kept the default IntelliJ setting and clicked Next. Android Studio next provided the opportunity
to verify settings.
22
Figure 14. Android Studio identifies additional SDK components that will be downloaded (click
to enlarge)
I clicked Finish and Android Studio began the process of downloading SDK components.
Figure 15. The wizard downloads and unzips SDK components (click to enlarge)
It can take several minutes for this part of the setup to finish. Clicking Show Details might
relieve some boredom by revealing the various files being downloaded and unzipped.
23
Figure 16. The wizard identifies the various archives being downloaded (click to enlarge)
For my AMD-based computer, an unpleasant surprise awaited after the components had
completely downloaded and unzipped:
Figure 17. Intel-based hardware acceleration is unavailable (click to enlarge)
My options are to either put up with the slow emulator or use an Android device to speed up
development. In Part 3 I'll show you how I resolved this issue.
Finally, I clicked Finish to complete the wizard. The Welcome to Android Studio dialog box
appeared.
24
Figure 18. Welcome to Android Studio (click to enlarge)
This dialog box is used to start up a new Android Studio project, work with an existing project,
and more. It can be accessed by selecting Android Studio from the Windows Start menu, or the
equivalent on another platform.
20.(A) Explain about text view,image button, edit text, check box, toggle button, radio
button and radio group views with neat diagrams. [Description- 10marks]
Text view
A TextView displays text to the user and optionally allows them to edit it. A TextView is
a complete text editor, however the basic class is configured to not allow editing.
<TextView
android:id="@+id/text_id"
android:layout_width="300dp"
android:layout_height="200dp"
android:capitalize="characters"
android:text="hello_world"
android:textColor="@android:color/holo_blue_dark"
android:textColorHighlight="@android:color/primary_text_dark"
android:layout_centerVertical="true"
android:layout_alignParentEnd="true"
25
android:textSize="50dp"/>
Image button
An ImageButton is an AbsoluteLayout which enables you to specify the exact location of
its children. This shows a button with an image (instead of text) that can be pressed or
clicked by the user.
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:layout_centerVertical="true"
26
android:layout_centerHorizontal="true"android:src="@drawable/abc"/>
Edit text
A EditText is an overlay over TextView that configures itself to be editable. It is the
predefined subclass of TextView that includes rich editing capabilities.
<EditText
android:id="@+id/edittext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button"
android:layout_below="@+id/textView1"
android:layout_marginTop="61dp"
android:ems="10"
android:text="@string/enter_text" android:inputType="text" />
27
Check box
A CheckBox is an on/off switch that can be toggled by the user. You should use check-
boxes when presenting users with a group of selectable options that are not mutually
exclusive.
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Do you like Tutorials Point"
android:layout_above="@+id/button"
android:layout_centerHorizontal="true" />
28
Toggle button
A ToggleButton displays checked/unchecked states as a button. It is basically an on/off
button with a light indicator.
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Off"
android:id="@+id/toggleButton2"
android:checked="true"
android:layout_alignTop="@+id/toggleButton" />
29
Radio button
A RadioButton has two states: either checked or unchecked.This allows the user to select
one option from a set.
<RadioButton
android:layout_width="142dp"
android:layout_height="wrap_content"
android:text="JAVA"
android:id="@+id/radioButton"
android:textSize="25dp"
android:textColor="@android:color/holo_red_light"
android:checked="false"
android:layout_gravity="center_horizontal" />
Radio group views
A RadioGroup class is used for set of radio buttons.If we check one radio button that
belongs to a radio group, it automatically unchecks any previously checked radio button
within the same group.
<RadioGroup
android:layout_width="fill_parent"
android:layout_height="90dp"
android:layout_below="@+id/imageView"
android:layout_marginTop="58dp"
android:weightSum="1"
30
android:id="@+id/radioGroup"
android:layout_alignLeft="@+id/textView2"
android:layout_alignStart="@+id/textView2"
android:layout_alignRight="@+id/textView3"
android:layout_alignEnd="@+id/textView3">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="55dp"
android:text="Male"
android:id="@+id/radioButton"
android:layout_gravity="center_horizontal"
android:checked="false"
android:textSize="25dp" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:id="@+id/radioButton2"
android:layout_gravity="center_horizontal"
android:checked="false"
android:textSize="25dp"
android:layout_weight="0.13" />
</RadioGroup>
31
(OR)
(b) Explain in detail about the displaying pictures and menus with view. [Description-
7marks, diagram -3 marks]
Displaying Pictures & Menus with views
To displaying images, we use the ImageView, Gallery, ImageSwitcher , and
GridView views.
• Image View:
Gallery View:
The Gallery is a view that shows items (such as images) in a center-locked,
horizontal scrolling list.
1. Using Eclipse, create a new Android project
32
• . Modify the main.xml fi le as shown
<?xml version=”1.0”encoding=”utf-8”?>
<LinearLayoutxmlns:android="
=”http://schemas.android.com/apk/res/android”
android:orientation=”vertical”
android:layout_width=”fill_pare
nt”
android:layout_height=”fill_pare
nt” >
<TextView
android:layout_width=”fill_parent
”
android:layout_height=”wrap_con
tent”
android:text=”Images of San Francisco” />
<Gallery
android:id=”@+id/gallery1”
android:layout_width=”fill_p
arent”
android:layout_height=”wrap_content” />
<ImageView
android:id=”@+id/image
33
1”
android:layout_width=”3
20px”
android:layout_height=”2
50px”
android:scaleType=
”fitXY” />
</LinearLayout>
• . Right-click on the res/values folder and select New ➪ File. Name the file
attrs.xml. 4 . Populate the attrs.xml file as follows:
<?xml version=”1.0” encoding=”utf-8”?>
<resources>
<declare-styleable name=”Gallery1”>
<attr name=”android:galleryItemBackground” />
</declare-styleable>
</resources>
• . Prepare a series of images and name them pic1.png , pic2.png , and so on
for each subsequent image
• . Drag and drop all
the images into the res/drawable-mdpi folder .When a dialog is displayed,
check the copy option and click OK.
• . Add the following statements to the MainActivity.java file:
packagenet.learn2develop.G
allery;
34
importandroid.app.Activity;
importandroid.os.Bundle;
import android.content.Context;
import
android.content.res.TypedArray;
import android.view.View;
import android.view.ViewGroup;
import
android.widget.AdapterView;
import
android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import
android.widget.Gallery;
import
android.widget.ImageView;
import android.widget.Toast;
publicclassMainActivityextendsActivity {
//---the images to
display--- Integer[]
imageIDs = {
R.drawable.pic1,
R.drawable.pic2,
R.drawable.pic3,
R.drawable.pic4,
R.drawable.pic5,
R.drawable.pic6,
R.drawable.pic7
};
/** Calledwhenthe activity isfirstcreated. */
@Override
publicvoidonCreate(BundlesavedInstanceS
tate){ super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Gallery gallery = (Gallery) findViewById(R.id.gallery1 );
gallery.setAdapter(new ImageAdapter(this));
gallery.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v,
35
int position, long id)
{
Toast.makeText
(getBaseContext(), “pic” +
(position + 1) + “ selected”,
Toast.LENGTH_SHORT).sh
ow();
}
});
}
public class ImageAdapter extends BaseAdapter
{
private Context context;
private int
itemBackground;
public ImageAdapter(Context c)
{
context = c;
//---setting the style---
TypedArray a =
obtainStyledAttributes(R.styleable.Gallery1 );
itemBackground = a.getResourceId(
R.styleable.Gallery1_android_galleryItemBackground , 0);
a.recycle();
}
//---returns the number of
images--- public int
getCount() {
return imageIDs .length;
}
//---returns the ID of an item--
- public Object getItem(int
position) { return position;
36
}
//---returns the ID of an item---
public long getItemId(int
position) { return position;
}
//---returns an ImageView view---
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(context);
imageView.setImageResource(imageIDs [position]);
imageView.setScaleType(ImageView.ScaleType. FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(150, 120));
imageView.setBackgroundResource(itemBackground);
return imageView;
}
}
}
• . Press F11 to debug the application on the Android Emulator.
• . You can swipe the images to view the entire series of images. Observe that as
you click on an image, the Toast class will display its name
37
• . To display the selected image in the ImageView, add the following
statements MainActivity.java file:
/** Calledwhenthe activity isfirstcreated. */
@Override
publicvoidonCreate(BundlesavedInstanceS
tate){ super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Gallerygallery=(Gallery)findViewById(R.id. gallery1 );
gallery.setAdapter(new ImageAdapter( this));
gallery.setOnItemClickListener(new
OnItemClickListener()
{
38
publicvoidonItemClick(AdapterView<?>parent,Vi
ewv, int position,longid)
{
Toast.makeText
(getBaseContext(),
“pic”+(position+1)+“selected
”,
Toast.LENGTH_SHORT).sh
ow();
//---display the images selected---
ImageView imageView = (ImageView)
findViewById(R.id.image1);
imageView.setImageResource(imageIDs [position]);
}
});
}
• . Press F11 to debug the application again. This time, you will see the image
selected in the ImageView
21.(a) Explain about the web servicing and accessing web services with http.
[Description- 10marks]
39
A web service is a standard for exchanging information between different types of
applications irrespective of language and platform. For example, an android application
can interact with java or .net application using web services.
Accessing Web Services
• Once the Web service returns a resultin XML, you will extract the relevant
parts and display its content using the Toast class.
• For this example, the web method you will be
using is from http://services.aonaware.com/
• DictService/DictService.asmx?op=Define. This web method is from a
Dictionary Web service that returns the definitions of a given word.
The web method takes a request in the following format:
GET /DictService/DictService.asmx/Define?word=string
HTTP/1.1 Host: services.aonaware.com
HTTP/1.1 200 OK
Content-Type: text/xml;
charset=utf-8 Content-Length:
length
It returns a response in the following format:
<?xml version=”1.0” encoding=”utf-8”?>
<WordDefinition xmlns=”http://services.aonaware.com/webservices/”>
<Word>string</Word>
<Definitions>
<Definition>
<Word>string</Word>
<Dictionary>
<Id>string</Id>
<Name>string</Name>
</Dictionary>
<WordDefinition>string</WordDefinition>
</Definition>
<Definition>
<Word>string</Word>
40
<Dictionary>
<Id>string</Id>
<Name>string</Name>
</Dictionary>
<WordDefinition>string</WordDefinition>
</Definition>
</Definitions>
</WordDefi
nition>
Example:
• Using the same project created earlier, add the following statements in
bold to the MainActivity.java file:
public class MainActivity extends
Activity { ImageView img;
private InputStream OpenHttpConnection(String
urlString) throws IOException
{
//...
}
private Bitmap DownloadImage(String URL)
{
//...
}
private String DownloadText(String URL)
{
//...
}
private void WordDefinition(String
word) { InputStream in = null;
try {
41
in=OpenHttpConnection(“http://services.aonaware.com/DictService/DictService.a
smx/Define?word=” + word); Document doc = null;
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInsta
nce(); DocumentBuilder db;
try {
db =
dbf.newDocumentBuilder(
); doc = db.parse(in);
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch
block e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch
block e.printStackTrace();
}
doc.getDocumentElement().normalize();
//---retrieve all the <Definition>
nodes--- NodeList itemNodes =
doc.getElementsByTagName(“Definit
ion”); String strDefinition = “”;
for (int i = 0; i < definitionElements.getLength(); i++) {
Node itemNode = definitionElements.item(i);
if (itemNode.getNodeType() == Node.ELEMENT_NODE)
{
//---convert the Node into an Element---
Element definitionElement = (Element) itemNode;
//---get all the <WordDefinition> elements under
// the <Definition> element---
NodeList
wordDefinitionElements =
(definitionElement).getElementsByTag
Name( “WordDefinition”);
strDefinition = “”;
42
for (int j = 0; j < wordDefinitionElements.getLength(); j++) {
//---convert a <WordDefinition> Node into an
Element--- Element wordDefinitionElement =
(Element) wordDefinitionElements.item(j);
//---get all the child nodes under the
// <WordDefinition>
element--- NodeList
textNodes =
((Node)
wordDefinitionElement).getChildNodes();
strDefinition +=
((Node) textNodes.item(0)).getNodeValue() + “. “;
}
//---display the title---
Toast.makeText(getBaseContext(),strDefi
nition, Toast.LENGTH_SHORT).show();
}
}
} catch (IOException e1) {
Toast.makeText(this,
e1.getLocalizedMessage(),
Toast.LENGTH_LONG).show();
e1.printStackTrace();
}
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//---download an
image--- Bitmap
bitmap =
DownloadImage(
43
―http://www.streetcar.org/mim/cable/images/cable
-01.jpg‖); img = (ImageView)
findViewById(R.id.img);
img.setImageBitmap(bitmap);
//---download an
RSS feed--- String
str = DownloadText(
Toast.makeText(getBaseCont
ext(), str,
Toast.LENGTH_SHORT).sh
ow();
//---access a Web service using
GET---
WordDefinition(“Apple”);
(OR)
(b) Explain about storing and retrieving data in internal and external storage using
android OS.
[Description- 10marks]
Android provides many kinds of storage for applications to store their data. These
storage places are shared preferences, internal and external storage, SQLite storage, and
storage via network connection.
Internal storage is the storage of the private data on the device memory.
By default these files are private and are accessed by only your application and get
deleted , when user delete your application.
Writing file
In order to use internal storage to write some data in the file, call the openFileOutput() method
with the name of the file and the mode. The mode could be private , public e.t.c. Its syntax is
given below −
FileOutputStream fOut = openFileOutput("file name
here",MODE_WORLD_READABLE);
The method openFileOutput() returns an instance of FileOutputStream. So you receive it
in the object of FileInputStream. After that you can call write method to write data on the
file. Its syntax is given below −
String str = "data";
fOut.write(str.getBytes());
44
fOut.close();
Reading file
In order to read from the file you just created , call the openFileInput() method with the
name of the file. It returns an instance of FileInputStream. Its syntax is given below −
FileInputStream fin = openFileInput(file);
After that, you can call read method to read one character at a time from the file and then
you can print it. Its syntax is given below −
int c;
String temp="";
while( (c = fin.read()) != -1){
temp = temp + Character.toString((char)c);
}
//string temp contains all the data of the file.
fin.close();
Apart from the the methods of write and close, there are other methods provided by the
FileOutputStream class for better writing files.
Saving to External Storage (SD Card)
Sometimes, Information would be useful to save them to external storage
(such as an SD card) because of its larger capacity, as well as the capability
to share the files easily with other users (by removing the SD card and
passing it to somebody else).
Using the project created in the previous section as the example, to save the
text entered by the user in the SD card, modify the onClick() method of the
Save button as shown in bold here:
saveBtn.setOnClickListener(new
View.OnClickListener() { public void
45
onClick(View v) {
String str =
textBox.getText().toString(); try
{
//---SD Card Storage---
File sdCard =
Environment.getExternalStorageDirectory(); File
directory = new File (sdCard.getAbsolutePath() +
“/MyFiles”);
directory.mkdirs();
File file = new File(directory, “textfile.txt”);
FileOutputStream fOut = new
FileOutputStream(file); OutputStreamWriter osw
= new
OutputStreamWriter(fOut);
//---write the string to
the file---
osw.write(str);
osw.flush();
osw.close();
//---display file saved
message---
Toast.makeText(getBaseC
ontext(),
―File saved successfully!‖,Toast.LENGTH_SHORT).show();
//---clears the
EditText---
textBox.setText(
―‖);
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
46
}
});
The preceding code uses the getExternalStorageDirectory() method to
return the full path to the external storage. Typically, it should return the
―/sdcard‖ path for a real device, and ―/mnt/sdcard‖for an Android Emulator.
However, you should never try to hardcode the path to the SD card, as
manufacturers may choose to assign a different path name to the SD card.
Hence, be sure to use thegetExternalStorageDirectory() method to return the
full path to the SD card.
You then create a directory called MyFiles in the SD card. Finally, you
save the file into this directory.To load the file from the external storage,
modify the onClick() method for the Load button:
loadBtn.setOnClickListener(new
View.OnClickListener() { public void
onClick(View v) {
try
{
//---SD Storage---
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File
(sdCard.getAbsolutePath() + “/MyFiles”);
File file = new File(directory, “textfile.txt”);
FileInputStream fIn = new FileInputStream(file);
InputStreamReader isr = new
InputStreamReader(fIn); char[] inputBuffer = new
char[READ_BLOCK_SIZE]; String s = ―‖;
int charRead;
while ((charRead = isr.read(inputBuffer))>0)
{
//---convert the chars to a
String--- String readString
=
String.copyValueOf(inputBuffer, 0,
charRead); s += readString;
inputBuffer = new char[READ_BLOCK_SIZE];
47
}
//---set the EditText to the text that has been
// read---
textBox.se
tText(s);
Toast.makeText(getBaseContext(),
―File loaded
successfully!‖,
Toast.LENGTH_SHORT)
.show();
}
catch
(IOException
ioe) {
ioe.printStackTra
ce();
}
}
});
Note that in order to write to the external storage, you need to add the
WRITE_EXTERNAL_STORAGE permission in your Android
Manifest.xml file:
<?xml version=‖1.0‖ encoding=‖utf-8‖?>
<manifest xmlns:android=‖http://schemas.android.com/apk/res/android‖
package=‖net.learn2develop.Files‖
android:versionCode=‖1‖
android:versionName=‖1.0‖>
<application android:icon=‖@drawable/icon‖
android:label=‖@string/app_name‖>
<activity android:name=‖.MainActivity‖
android:label=‖@string/app_name‖>
<intent-filter>
<action android:name=‖android.intent.action.MAIN‖ />
<category android:name=‖android.intent.category.LAUNCHER‖ />
48
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion=‖9‖ />
<uses-permission
android:name=”android.permission.WRITE_EXTERNAL_STORA
GE”
>
</uses-permission>
KEY PREPARED BY
SIGNATURE :
NAME :S.SIVAKUMAR
DESINATION :P.T -LECTURER
COLLEGE :GOVT.POLY.,
PURASAWALKAM