0% found this document useful (0 votes)
56 views130 pages

Mad Epa

Uploaded by

Kiran janjal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
56 views130 pages

Mad Epa

Uploaded by

Kiran janjal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 130

Examination Paper Analysis and Solution

Mobile Application Development (22617) T.Y. Diploma: Sem 6

Winter-23 Summer-23 Winter-22 Summer-22


Topi
Name of Topic Questio Mark Mark
c No. Question Marks Question Marks Question
n s s
1.(b) 2 1.(a) 2
1.(a) 2 1.(a) 2
Android and its 1.(a) 2 2.(a) 4
1 2.(c) 4 2.(a) 4
tools 2.(a) 4 4.(c) 4
6 8 10 6
1.(b) 2 1.(b) 2 1.(b) 2
2.(b) 4
2.(b) 4 1.(c) 2 1.(c) 2
Installation and 3.(a) 4
2 configuration 4.(a) 4 2.(b) 4 2.(b) 4
4.(a) 4
of Android 4.(b) 4 3.(a) 4 3.(a) 4
Total 14 Total 12 Total 12 Total 12
1(c) 2 4(a) 4 4(a) 4
1(c)
2(a) 4 2 5(c) 6 6(c) 6
3(b)
3(c) 4 4 6(c) 6
4(a)
UI components 4(b) 4 4
3 6(c)
and Layouts 6

Total 14 Total 16 Total 16 Total 10


1(f) 2 1(d) 2 3(b) 4
3(d) 4 1(d) 3(a) 4 4(b) 4
2
Designing User 4(c) 4 4(b) 4(b) 4 5(a) 6
4
4 Interface with 5(a) 6 5(a)
6
View

Total 16 Total 12 Total 10 Total 14


1.(e) 2 1.(e) 2 1.(e) 2 1.(e) 2
1.(g) 2 1.(g) 2 1.(g) 2 1.(g) 2
3.(a) 4 2.(d) 4 3.(c) 4 2.(d) 4
4.(e) 4 3.(c) 4 5.(b) 6 3.(c) 4
Activity and 5.(c) 6 4.(c) 4 6.(a) 6 4.(c) 4
5 Multimedia 6.(a) 6 5.(b) 6 5.(b) 6
with databases
6.(a) 6 6.(a) 6

Total 24 Total 28 Total 20 Total 28


Examination Paper Analysis and Solution

1.(d) 2 2(c) 4 1.(f) 2


1.(f) 2
2.(d) 4 3.(d) 4 2.(d) 4
2.(c) 4
3.(b) 4 4.(d) 4 3.(d) 4
Security and 3.(d) 4
4.(d) 4 4.(e) 4 4.(d) 4
6 Application 4.(d) 4
5.(b) 6 5.(c) 6 5(a) 6
Deployment 4(e) 4
6.(b) 6 6(b) 6 6(b) 6
5(c) 6

Total Total Total Total

Exam Unit No and Question no as per MSBTE paper Marks


Year Name

Summer- Unit-1: Q1 a. Features of Android Operating System. 2


2022 Android and Q 2 a Describe Android architecture with diagram. 4
its tools
Winter- Unit-1: Q 1 a Define OHA and state goal of OHA. 2
2022 Android and Q 2 a Describe the different features of Android. 4
its tools Q 4 c Explain Android system architecture in detail. 4
Summer- Unit-1: Q1. B List various tools for android application 2
2023 Android and development 2
its tools Q 1 a State Android ECO System. 4
Q 2 a Describe android and importance of OHA.
Winter- Unit-1: Q 1 a List all tools and software’s required for 2
2023 Android and developing an android application.
its tools Q 2 c Explain the need of Android Operating System. 4
Also describe any four features of android.
Summer- Unit-2: Q.1 b Define Dalvik Virtual Machine (DVM). 2
2022 Installation Q. 1 c List any four folders from directory structure of 2
and Android project and elaborate in one line.
Configuration Q 2 b Differentiate between DVM and JVM 4
of android Q 3 a Write down the steps to install and configure 4
Android studio.
Winter- Unit-2: Q 1 b Define Android Virtual Devices (AVD) 2
2022 Installation Q 1 c State how the APK files are built? 2
and Q. 2 b Explain features of Android SDK. 4
Configuration Q 3 b Explain the steps to install and configure Android 4
of android studio and SDK
Summer- Unit-2: Q 2b Explain Dalvik Virtual Machine and state its 4
2023 Installation importance
and Q 3 a Describe various installation steps of android 4
Configuration studio and its environment
of android Q 4a Describe directory structure and its components 4

Winter- Unit-2: Q 1 b Define emulator 2


2023 Installation 4
Examination Paper Analysis and Solution

and Q 2 b Explore all steps to install Android studio and 4


Configuration SDK 4
of android Q 4 a Differentiate between JVM and DVM. (Any four
points)
Q 4 b Explain components of android directory
structure
Summer- Unit 3: UI Q.4 a Explain with example, code to create GUI using 4
2022 absolute layout (Assume suitable data).
Components
Q.6 c. Design UI using table layout to display buttons
and Layouts with 0 9 numbers on it. Even display submit and clear 6
button. When user clicks on particular buttons and later
when clicks on submit button, it should display the
numbers clicked.
(Note: Consider the appropriate XML file. All
attributes are not required.
In java file all imports are not expected. Different
relevant logic/code can be considered.)

Winter- Unit 3: UI 4(a)Explain the fundamentals of Ul design in detail. 4


2022 5(c)Develop a program to implement
Components
i) List view of 5 items 6
and Layouts ii) Grid view of 4 x 4 items
iii) Image view.
6(c)Develop a simple calculator using relative layout.

6
Summer- Unit 3: UI 1(c)List various layouts used in android UI design. 2
2023 3(b) Explain Gridview with its attributes with suitable 4
Components
example.
and Layouts 4(a)Describe directory structure and its components. 4
6(c)Explain how linear and frame layout is used to
design an android application with suitable example. 6

Winter- Unit 3: UI Q 1 c List any four attributes of layout. 2


2023 Q 2 a Explain relative layout with all its attributes. 4
Components
Q3 c Explain relative layout with all its attributes. 4
and Layouts Q 4 b Explain components of android directory 4
structure.

Summer- Unit 4: 3 b State syntax to create Text View and Image 4


2022 button with any two attributes of each.
Designing
4 b. Write a program to demonstrate Date and 4
User Time picker.
(Note: Consider the appropriate XML file. All
Interface with
attributes are not required.
View In java file all imports are not expected. Different
relevant logic/code can be considered.) 6
Examination Paper Analysis and Solution

5 a Write a program to convert temperature from


celcius to farenhite and vice versa using Toggle
button. (Design UI as per your choice. Write XML
and java file)
(Note: Consider the appropriate XML file. All
attributes are not required.
In java file all imports are not expected. Different
relevant logic/code can be considered.)

Winter- Unit 4: 1 d Enlist the elements of UI. 2


2022 3 a Explain data and time picker with its method. 4
Designing
4 b Write a program to display a rectangular progress 4
User bar.
Interface with
View

Summer- Unit 4: 1 d Name any four attributes of Edit Text control. 2


2023 4 b Develop an android application for Date and Time 4
Designing
Picker.
User 5 a Design a employee registration form using UI 6
component.
Interface with
View

Winter- Unit 4: 1 f Write difference between toggle button and 2


2023 radio button.
Designing
3 d Develop an application to display analog Time 4
User Picker. Also display the selected time. (Write only
. java file)
Interface with
4 c Develop an android application using radio 4
View button.
5 a Develop a program to perform addition,
subtraction, division, multiplication of two 6
numbers and display the result. (Use appropriate
UI controls).

Summer- Unit-5: Q1 e Draw diagram of activity life cycle. 2


2022 Activity and Q1 g Name two classes used to play audio and video in 2
Multimedia Android. 4
with Q2 d Describe with example, how to create a simple
databases database in SQLite (Assume suitable data). 4
Q3 c Describe Android service life cycle along with 4
diagram. 6
Q4 c Describe multimedia framework of Android with
diagram. 6
Examination Paper Analysis and Solution

Q5 b Write a program to capture an image using


camera and display it.
Q6 a Write a program to implement Android Activity
Life Cycle. Use toast messages to display message
through life cycle.
Winter- Unit-5: Q1 e State the uses of Intent in Android. 2
2022 Activity and Q1 g Explain significance of content provider. 2
Multimedia Q3 c Explain the activity life cycle. 4
with Q5 b Develop a program for providing Bluetooth 6
databases connectivity. 6
Q6 a Develop an application to store customer's details
like, customer-id, customer-name, mobile number,
address, pin-code and retrieve customer information
using customer-id in SQLite databases.

Summer- Unit-5: Q1 e State the use of fragments in android App 2


2023 Activity and development. 2
Multimedia Q1 g List different types of sensors used in android. 4
with Q2 d Explain multimedia framework in android. 4
databases Q3 c Explain text to speech conversion technique in 4
android
Q4 c Explain property animation method to animate 6
the properties of view object with example.
Q5 b Develop an android application for taking student 6
feedback with database connectivity.
Q6 a Design an android application to show the list of
paired devices by Bluetooth.

Winter- Unit-5: Q1 e State intent. List types of intent. 2


2023 Activity and Q1 g Define: i) Fragment ii) Broadcast receiver 2
Multimedia Q3 a Describe service life cycle with its diagram. 4
with Q4 e Draw and explain activity life cycle. 4
databases Q5 c Develop an application to convert thanks" text to 6
speech as given in the following GUI.
Q6 a Develop an application to update a record of an 6
employee whose emp.id is ‘E101’ in SQlite database.
Change employee name from “POR" to “XYZ". Also
display the updated record (Write .java and .xml files).
Winter- Unit 1(f) Name any four methods to get location data in 2
2022 6:Security android. 4
and 2(d) Elaborate the need of permissions in Android.
Application Explain the permissions to set system functionalities
Deployment like SEND-SMS, bluetooth.
3(d) Explain the steps to deploy app on Google Play 4
Store. 4
4(d) Explain the procedure of Geo-coding and reverse
Geo-coding.
5(a) Develop a program to send and receive an Email.
6
Examination Paper Analysis and Solution

Q6(b) Write a program to find the direction from user's


current location to MSBTE, Bandra. (Write only Java
and manitest file).

Summer- Unit Q2(c) List and elaborate steps to deploy an Android 4


2022 6:Security application on Google play store.
and 3(d) State and elaborate the syntax of required class 4
Application and methods for Geocoding.
Deployment 4(d) Discuss developer console with at least four 4
features
4(e) Write a program to demonstrate declaring and 4
using permissions with any relevant example.
5(c) Develop and application to send and receive SMS
(Design minimal UI as per your choice. Write XML, 6
java and manifest file)
6(b) Develop an application to display Google map 6
with user's current location.

S-2023 Unit Q1(f) Define SMS service in android application 2


6:Security development. 4
and Q2(c) Describe the process of getting the map API key. 4
Application Q3(d)Describe steps for deploying android application
Deployment on Google Play Store. 4
4(d)Describe permissions required for android
application development.
4(e)Develop an android application to show current 4
location of an user's car
5(c) Explain Geocoding and Reverse Geocoding with 6
suitable example.

W 2023 Unit Q1(d) Define Geocoding and Reverse Geocoding. 2


6:Security Q2(d)Develop a program to add "Hello World"
and marker at (10 ,10) co-ordinates. Write only . java file. 4
Application Q3(b) Elaborate Android Security Model.
Deployment Q4(d)Develop an application to send and receive SMS. 4
(Write only Java and permission tag in manifest file)
Q5(b) Develop an application to display a Google 4
Map. (Write JAVA & Manifest file)
Q6(b)i) Describe all steps in application deployment 6
on google play store.
ii) Write steps for customized permissions.
6
Examination Paper Analysis and Solution

Unit 1: Android and its Tools

Summer 22

Q1 a. Features of Android Operating System [2M]


Ans.
Features of Android Operating System:
1)Storage
2)Multitasking
3)Web Browser
4)Open Source
5)Accessibility
6)Media Support
7)Streaming Media Support
8)Voice Based Features
9)Multitouch
10)External Storage
11)Video Calling
12)Handset Layout
13)Google cloud Messaging
14)WiFi Direct

Q 2 a Describe Android architecture with diagram.[4 M]


Ans:
Examination Paper Analysis and Solution

1. Applications:
• The top layer of android architecture is Applications. The native and third party
applications like Contacts, Email, Music, Gallery, Clock, Games, etc. whatever we will
build those will be installed on this layer only.
• The application layer runs within the Android run time using the classes and services
made available from the application framework.

2. Application Framework:
• The Application Framework provides the classes used to create an Android application.
It also provides a generic abstraction for hardware access and manages the user
interface and application resources.
• It basically provides the services through which we can create the particular class and
make that class helpful for the Applications creation.
Examination Paper Analysis and Solution

• The application framework includes services like telephony service, location services,
notification. manager, NFC service, view system, etc. which we can use for application
development as per our requirements.

3. Android Runtime:
• Android Runtime environment is an important part of Android rather than an internal
part and it contains a components like core libraries and the Dalvik virtual machine.
• The Android run time is the engine that powers our applications along with the libraries
and it forms the basis for the application framework.
• Dalvik Virtual Machine (DVM) is a register-based virtual machine like Java Virtual
Machine (JVM).
• It is specially designed and optimized for android to ensure that a device can run
multiple instances efficiently. It relies on the Linux kernel for threading and low-level
memory
• management.
• The core libraries in android runtime will enable us to implement an android
applications using standard JAVA programming language.

4. Platform Libraries:
• The Platform Libraries includes various C/C++ core libraries and Java based libraries
such as SSL,libc, Graphics, SQLite, Webkit, Media, Surface Manger, OpenGL etc. to
provide a support for android development.

Following are the summary details of some core android libraries available for android
development.
Media library for playing and recording an audio and video formats
• (i) The Surface manager library to provide a display management
• (ii) SGL and OpenGL Graphics libraries for 2D and 3D graphics
• (iii) SQLite is for database support and FreeType for font support
• (iv) Web-Kit for web browser support and SSL for Internet security.

5. Linux Kernel:
• Linux Kernel is a bottom layer and heart of the android architecture. It is heart of
Android architecture that exists at the root of android architecture and contains all the
low-level device drivers for the various hardware components of an Android device.
Examination Paper Analysis and Solution

• Linux Kernel is responsible fro device drivers, power management, memory


management, device management and resource access. It manage all the drivers such
as display drivers, camera drivers, Bluetooth drivers, audio drivers, memory drivers,
etc. which are mainly required for the android device during the runtime.
• The Linux Kernel will provide an abstraction layer between the device hardware and
the remainder of the stack. It is responsible for memory management, power
management, device management, resource access, etc.

Winter 22
Q 1 a Define OHA and state goal of OHA. [2 M]
Ans:
The OHA is the group that is in charge of the Android smartphones operating system. It was
created by Google. The Open Handset Alliance (OHA) is consortium of multiple companies
like Samsung, Sony, Intel and many more to provide services and deploy handsets using
android platform.
The Open Handset Alliance (OHA) is an association whose goal is to develop open standards
for mobile devices, promote innovation in mobile phones and provide a better experience for
consumers at a lower cost.

Q 2 a Describe the different features of Android. [4M]


Ans:
• User Interface: The user interface of the Android operating system is straight forward,
and these features make it very user friendly.
• Multiple Language Support: Android supports multiple languages in its operating
syste and one can change the language very easily based on one’s requirement, the
International languages supported are English, Germany, Chinese, Dutch, French,
German, Japanese, Korean, Russian, and many more also some native language of India
is also Supported Like Hindi, Marathi, Gujarati, Punjabi and many more.
• Multi-tasking: Android provides support to run apps and services in the background
with ease which allows the users to use multiple apps at the same time.
• Connectivity: Android has extensive support to the connectivity and it supports
connectivity such as WiFi, Bluetooth, Hotspot, CDMA, GSM, NFC, VOLTE, UBB,
VPN, 3G network band, and 4G Network Band.
Examination Paper Analysis and Solution

Extensive Application Support: Android have Play store which is used as the major tool to
download and update applications on the operating system, however, one can download the
installer(often called as APK file) and install it manually, but it is not much recommended as
third party applications could be prone to some security breach in the smartphones.

Q 4 c Explain Android system architecture in detail. [4M]


Ans: refer Q 2 a[4 M S-22]

Summer 2023

Q 1 a State Android ECO System. [2 M]


Ans:

• Ecosystem in Market terminology refers to the inter-dependence between demand and


supply.
• In the Android ecosystem this translates to inter-dependence between users,
developers, and equipment makers. One cannot exist without the other:
• Google develops android
• Users buy devices and applications
• Original Equipment makers sell devices, sometimes bundled with applications
• Developers buy devices, then make and sell applications
Examination Paper Analysis and Solution

• Freelance Android Developer developers have the skills to contribute to the


ecosystem for android development, they are who creates their own applications and
published them on googles play store.

Q1. B List various tools for android application development [2M]


Ans:

• Android Studio
• ADB (Android Debug Bridge)
• AVD Manager
• Eclipse
• Fabric
• FlowUp
• GameMaker: Studio
• Genymotion
• Gradle IntelliJ IDEA

Q 2 a Describe android and importance of OHA. [4 M

Android is an open source and Linux-based Operating System .It is designed primarily for
touch screens mobile devices such as smartphones and tablet computers. Android offers a
unified approach to application development for mobile devices which means developers need
only develop for Android, and their applications should be able to run on different devices
powered by Android. Android was developed by the Open Handset Alliance, led by Google,
and other companies.
OHA
• The Open Handset Alliance (OHA) is a business alliance that was created for the
purpose of developing open mobile device standards.
• The OHA has approximately 80 member companies, including HTC, Dell, Intel,
Motorola, Qualcomm and Google.

Importance of OHA
• Lower overall handset costs: Opens up resources, which facilitates the focus on
creating innovative applications, solutions and services.
Examination Paper Analysis and Solution

• Developer-friendly environment: In the open-source community, developers share


notes to expedite application development.
• Post-development: Provides an ideal channel for application marketing and
distribution.

Winter 23
Q 1 a List all tools and software’s required for developing an android application. [ 2 M]
Ans : Refer Q1. B [2M S-23]

Q 2 c Explain the need of Android Operating System. Also describe any four features of
android. [ 4 M ]
Ans:
Need of Android Operating System
• Zero/negligible development cost: The development tools like Android SDK, JDK, and
Eclipse IDE etc. are free to download for the android mobile application development.
• Open Source: The Android OS is an open-source platform based on the Linux kernel
and multiple open-source libraries. In this way developers are free to contribute or
extend the platform as necessary for building mobile apps which run onAndroid
devices.
• Multi-Platform Support: In market, there are a wide range of hardware devices powered
by the Android OS, including many different phones and tablet. Even development of
android mobile apps can occur on Windows, Mac OS or Linux.
• Multi-Carrier Support: World wide a large number of telecom carriers like Airtel,
Vodafone, Idea Cellular, AT&T Mobility, BSNL etc. are supporting Android powered
phones.
• Open Distribution Model: Android Market place (Google Play store) has very few
restrictions on the content or functionality of an android app. So the developer can
distribute theirs app through Google Play store and as well other distribution channels
like Amazon’s app store.

Four features of android


• Near Field Communication (NFC)
Examination Paper Analysis and Solution

Most Android devices support NFC, which allows electronic devices to easily interact
across short distances.
• Alternate Keyboards
Android supports multiple keyboards and makes them easy to install; the SwiftKey,
Skype, and 8pen apps all offer ways to quickly change up your keyboard style.
• Infrared Transmission
The Android operating system supports a built-in infrared transmitter, allowing you to
use your phone or tablet as a remote control.
• No-Touch Control
Using Android apps such as Wave Control, users can control their phones touch-free,
using only gestures.
• Automation
The Tasker app controls the app permissions but also automate them
• Wireless App Downloads
Using the Android Market or third-party options like AppBrain, we can download apps
on PC and then automatically sync them with Android, no plugging required.
• Storage and Battery Swap
Android phones also have unique hardware capabilities. Google’s OS makes it possible
to remove and upgrade your battery or to replace one that no longer holds a charge
• Custom Home Screens
While it’s possible to hack certain phones to customize the home screen, Android
comes with this capability from the get-go
• Widgets
Apps are versatile, but sometimes you want information at a glance instead of having
to open an app and wait for it to load. Android widgets let you display just about any
feature you choose, right on the home screen—including weather apps, music widgets,
or productivity tools that helpfully remind you of upcoming meetings or approaching
deadlines.

Unit 2: Installation and Configuration of Android


Examination Paper Analysis and Solution

Summer 22
Q.1 b Define Dalvik Virtual Machine (DVM). [2M]
Dalvik Virtual Machine is a register-based machine that compiles byte code to get dex code
and that ensures that a device can run multiple instances efficiently.

Q. 1 c List any four folders from directory structure of Android project and elaborate in
one line. [2M]
Folders from directory structure:
1)app: The App folder contains three subfolders (manifests, java and res) that make up our
application.
They are divided so that it should be fairly easy to determine which resources go in which
folder.
2)Manifest: This is where we would put our manifest files. Most Android apps have single
manifest file. But an app may have several manifest files due to application versioning, or for
supporting specific hardware.
3)Java: This is the folder in our project where we will be storing all of the source code files
written in Java programming language.
4)res: It contains folders that help us to separate and sort the resources of our application.
Resources
basically mean all the needed files except the source code.
5)drawable: The drawable folder contains graphics that can be drawn to the screen.
6)layout: The layout folder contains XML files used for your layouts. These file are used to
set up the layout for your Activity and is used for basic alignment of your layouts, components,
widgets, and similarresources that are used for the UI of your application.
7)mipmap : The mipmap folder contains the launcher icon files for the app. A launcher icon
is a graphic that represents your app to users.
8)values: The values folder contains XML files that contain simple values, such as strings,
integers, and colors. The values folder is used to keep track of the values we will be using in
our application.
Q 2 b Differentiate between DVM and JVM. [4 M]
Ans:
Examination Paper Analysis and Solution

Q 3 a Write down the steps to install and configure Android studio. [4 M]

Step 1: Go to https://developer.android.com/android-studio/download to get the Android


Studio executable or zip file.
Step 2:
● Click on the Download Android Studio Button.
● Click on the “I have read and agree with the above terms and conditions” checkbox followed
by the download button
● Click on the Save file button in the appeared prompt box and the file will start downloading.
Step 3: After the downloading has finished, open the file from downloads and will prompt the
following dialog box. Click on next. In the next prompt, it’ll ask for a path for installation.
Choose a path and hit next.
Step 4: It will start the installation, and once it is completed, it will be like the image shown
below.
Step 5: Once “Finish” is clicked, it will ask whether the previous settings need to be imported
[if the android studio had been installed earlier], or not. It is better to choose the ‘Don’t import
Settings option’. Click the OK button.
Step 6: This will start the Android Studio. Meanwhile, it will be finding the available SDK
components.
Step 7: After it has found the SDK components, it will redirect to the Welcome dialog box.
Choose Standard and click on Next. Now choose the theme, whether the Light theme or the
Examination Paper Analysis and Solution

Dark one. The light one is called the IntelliJ theme whereas the dark theme is called Darcula.
Choose as required. Click on the Next button.
Step 8: Now it is time to download the SDK components. Click on Finish. Components begin
to download let it complete. The Android Studio has been successfully configured. Now it’s
time to launch and build apps. Click on the Finish button to launch it.
Step 9: Click on Start a new Android Studio project to build a new app.

Winter 22

Q 1 b Define Android Virtual Devices (AVD). [2M]


An Android Virtual Device (AVD) is a configuration that defines the characteristics of an
Android phone, tablet, Wear OS, Android TV, or Automotive OS device that you want to
simulate in the Android Emulator. The AVD Manager is an interface you can launch from
Android Studio that helps you create and manage AVDs.

Q 1 c State how the APK files are built? [2M]

The javac compiler compiles the java source file into the class file.
● The dx tool takes all the class files of your application and generates a single .dex file which
is a platform specific tool.
● Then Android Assets Packaging Tool (aapt) handles the packaging process and finally
creates an executable file with extension .apk.
● An APK file contains all of a program's code (such as .dex files), resources, assets,
certificates, and manifest file

Q. 2 b Explain features of Android SDK. [4 M W-22]

Android SDK is a collection of libraries and Software Development tools that are essential for
Developing Android Applications. Whenever Google releases a new version or update of
Android Software, a corresponding SDK also releases with it. In the updated or new version of
SDK, some more features are included which are not present in the previous version. Android
SDK consists of some tools which are very essential for the development of Android
Examination Paper Analysis and Solution

Application. These tools provide a smooth flow of the development process from developing
and debugging. Android SDK is compatible with all operating systems such as Windows,
Linux, macOS, etc.
1. Android Tool: This tool helps in managing the Android Virtual Device projects as well as
the installed components of the software development kit.
2. Emulator Tool: It helps us in testing the applications without the need of using the
application on an actual device.
3. Dalvik Debug Monitor Server(DDMS): DDMS is very useful for debugging the Android
Application.
4. Android Debug Bridge (ADB): It is a very versatile command-line tool and is helpful for
the communication between the developer and the Emulator or the Android device that is
connected.

Q 3 b Explain the steps to install and configure Android studio and SDK. [4 M W-22]
Download the latest version of Android Studio from above URL and launch Android
Studio.exe file by double clicking on it.
● The initial android studio setup screen will open in that click Next to continue for further
steps of environment setup
● Now we need to select a required components to setup an android environment. Here we
selectedall three components (Android Studio, Android SDK and Android Virtual Device) and
click Next.
● Now we need to agree the License agreements to proceed further, click on I Agree button
● Now we need to specify the local machine drive location to install Android Studio and
Android SDK.
● After selecting the location path to install required components, click Next.
● Now select the start menu folder to create a shortcut for android studio and click Install
● Once we click Install button the installation process will start and click Next after completion
of Installation.
● After that it will show installation completion wizard in that click Finish to launch android
studio While launching Android Studio it will give you an option to import settings from
previous version of studio. Incase if you don’t have any previous version, select second option
and click OK
● Now android studio will open a welcome wizard window in that click Next to validate our
current Android SDK and development environment setup
Examination Paper Analysis and Solution

● Now select a Standard installation type and click Next to install a common settings and
options
● Now verify settings and click Finish to complete android studio setup process
● After completion of required components installation click on Finish
● After completion of all required components installation, we will be able to see Android
Studio welcome window

Summer 2023
Q 2b Explain Dalvik Virtual Machine and state its importance. [4 M]
The Dalvik Virtual Machine (DVM) is an android virtual machine optimized for mobile
devices. Dalvik VM is also a virtual machine that is highly optimized for mobile devices. Thus,
it provides all thethree things, that are memory management, high performance as well as
battery life. It is strictly developed for Android mobile phones.

The Dex compiler converts the class files into the .dex file that run on the Dalvik VM. Multiple
class files are converted into one dex file. The javac tool compiles the java source file into the
class file. The dx tool takes all the class files of your application and generates a single .dex
Examination Paper Analysis and Solution

file. It is a platform-specific tool. The Android Assets Packaging Tool (aapt) handles the
packaging process.
Q 3 a Describe various installation steps of android studio and its environment.4M S-23]
Ans: refer 3 a (S- 22)

Winter 2023

Q 1 b Define emulator.[2 M W-23]


An Android emulator is a tool that creates virtual Android devices on your computer. The
emulator lets you prototype, develop and test Android applications without using a physical
device

Q 2 b Explore all steps to install Android studio and SDK [ 4 M W-23]


Ans: Refer Q 3 b [4 M W-22]

Q 4 a Differentiate between JVM and DVM. (Any four points) [4 M W-23]

Ans: refer Q 2 b 4 M S-22]

Q 4 b Explain components of android directory structure. [4 M W-23]


Ans: Refer Q 4a [4 M S-23]

Unit 3: UI Components and Layouts

Summer 22
Examination Paper Analysis and Solution

Q. 4 e Explain with example, code to create GUI using absolute layout (Assume suitable data).
[4 M S-22]

Ans:

AbsoluteLayout is based on the simple idea of placing each control at an absolute position. We
specify the exact x and y coordinates on the screen for each control. This is not recommended for
most UI development (in fact AbsoluteLayout is currently deprecated) since absolutely positioning
every element on the screen makes an inflexible UI that is much more difficult to maintain.

Absolute Layout
● An Absolute Layout lets you specify exact locations (x/y coordinates) of its children. Absolute
layouts are less flexible and harder to maintain than other types of layouts without absolute
positioning. AbsoluteLayout is based on the simple idea of placing each control at an absolute
position.
● We specify for the exact x and y corodinates on the screen for every control. So this recommended
for most UI development (in fact Absolute Layout is currentaly deprecated)since absolute
positioning of every element on the screen makes an inflexible UI that is much more difficult to
maintain.
● Consider what happens if a control needs to be added to the user interface UI, we would have to
change the position of every single element that is shifted by the new control. This allows child
views to be positioned at specified X and Y coordinates within the containing layout view.
Example
(Note :Any other relevant example using absoluteLayout can be considered, No
java code is expected)

activity_main.xml :

<AbsoluteLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<TextView
android:layout_x="110px"
android:layout_y="110px"
android:text="User Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

<EditText
android:layout_x="250px"
Examination Paper Analysis and Solution

android:layout_y="80px"
android:width="100px"
android:layout_width="200dp"
android:layout_height="wrap_content" />

<TextView
android:layout_x="110px"
android:layout_y="200px"
android:text="Password"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

<EditText
android:layout_x="250px"
android:layout_y="150px"
android:width="100px"
android:layout_width="200dp"
android:layout_height="wrap_content" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Log In"
android:layout_x="300px"
android:layout_y="300px"/>

</AbsoluteLayout>

Q. 6 C Design UI using table layout to display buttons with 0 9 numbers on it. Even display
submit and clear button. When user clicks on particular buttons and later when clicks on
submit button, it should display the numbers clicked.
(Note: Consider the appropriate XML file. All attributes are not required.
In java file all imports are not expected. Different relevant logic/code can be
considered.) [6 M S-22]

Ans:

activity_main.xml

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


<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="*"
tools:context=".MainActivity">
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content">
Examination Paper Analysis and Solution

<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/button0"
android:text="0"/>
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/button1"
android:text="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button2"
android:text="2" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/button3"
android:text="3"/>
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/button4"
android:text="4"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="5"
android:id="@+id/button5"/>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="6"
android:id="@+id/button6"/>
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="7"
android:id="@+id/button7"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
Examination Paper Analysis and Solution

android:text="8"
android:id="@+id/button8"/>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="9"
android:id="@+id/button9"/>
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Submit"
android:id="@+id/submit"/>
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Clear"
android:id="@+id/clear"/>
</TableRow>
</TableLayout>

Java File:

package com.example.p1;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button button0, button1, button2, button3, button4, button5, button6,button7, button8,
button9,submit,clear;
String a=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button0 = (Button) findViewById(R.id.button0);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
button4 = (Button) findViewById(R.id.button4);
button5 = (Button) findViewById(R.id.button5);
button6 = (Button) findViewById(R.id.button6);
button7 = (Button) findViewById(R.id.button7);
button8 = (Button) findViewById(R.id.button8);
button9 = (Button) findViewById(R.id.button9);
submit=(Button) findViewById(R.id.submit);
Examination Paper Analysis and Solution

clear=(Button) findViewById(R.id.clear);
button0.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
a=button0.getText().toString();
}
});
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
a=button1.getText().toString();
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
a=button2.getText().toString();
}
});
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
a=button3.getText().toString();
}
});
button4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
a=button4.getText().toString();
}
});
button5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
a=button5.getText().toString();
}
});
button6.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
a=button6.getText().toString();
}
});
button7.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
a=button7.getText().toString();
}
});
button8.setOnClickListener(new View.OnClickListener() {
@Override
Examination Paper Analysis and Solution

public void onClick(View view) {


a=button8.getText().toString();
}
});
button9.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
a=button9.getText().toString();
}
});
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(),a,Toast.LENGTH_LONG).show(); }
});
}
}

Winter 2022

Q.4 a Explain the fundamentals of Ul design in detail. [4 M W-22]

Ans:
1. Views:
• The basic building block for user interface in Android is a View, which is created from the View
class and occupies a rectangular area on the screen and is responsible for drawing and event
handling.
• Views are the base class for all visual interface elements (commonly known as controls or
widgets). All user interface UI controls, including the layout classes, are derived from View.
• A View is an object/widget that draws something on the sreen by the help of user interact.
Examples of widgets are buttons, text boxes, labels etc.
2. View Groups:
• The ViewGroup is a subclass of View and provides invisible container that hold other Views or
other ViewGroups and define their layout properties.
• View groups are extensions of the View class that can contain multiple child Views. In order to
Extend the ViewGroup class to create compound controls made up of interconnected child views.
• A ViewGroup provides the layout in which we can order the appearance and sequence of views.
Examples of ViewGroup are FrmaeLayout, LineourLayout etc.
3. Fragments:
• Fragments represents a portion of user interface in an Activity. Fragments, introduced in Android
3.0 which uses API level 11, are used to encapsulate portions of your UI. This encapsulation makes
fragments particularly useful when optimizing our UI layouts for different screen sizes and creating
reusable user interface (UI) elements.
• Each Fragment includes its own user interface (UI) layout and receives the related input events
but is tightly bound to the activity into which each must be embedded. Fragments are similar to UI
view controller in iPhone development.
4. Activities:
• Activities dictate the UI and handle the user interaction to the smart phone screen. Activities
represent a single screen that user interact.
• Activities are the Android equivalent of Forms in traditional windows desktop development. To
display a UI we assign a View (Usually a layout or Fragment) to an Activity
Examination Paper Analysis and Solution

Q 5 c. Develop a program to implement [6M W-22]


i) List view of 5 items
ii) Grid view of 4 x 4 items
iii) Image view.

Ans:

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<ListView
android:id="@+id/sample_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<GridView
android:id="@+id/gridview1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:columnWidth="50dp"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="columnWidth" >
</GridView>
<ImageView
android:id="@+id/full_logo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:srcCompat="@drawable/android_logo" />
</LinearLayout>

Placed image that has to be displayed in drawable folder

package in.msbte.controls_exam_ques;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ListView;
Examination Paper Analysis and Solution

public class MainActivity extends AppCompatActivity {


String[] sampleArray = {"Item 1","Item 2","Item 3","Item 4", "Item 5"};
GridView gridView;
static final String[] alphabets = new String[]{
"A", "B", "C", "D", "E",
"F", "G", "H", "I", "J",
"K", "L", "M", "N", "O",
"P", "Q", "R", "S", "T",
"U", "V", "W", "X", "Y", "Z"
};
ArrayAdapter adapter, adapter1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//List View
adapter = new ArrayAdapter<String>(this, R.layout.simple_item, sampleArray);
ListView listView = (ListView) findViewById(R.id.sample_list);
listView.setAdapter(adapter);
//Grid View
gridView = (GridView) findViewById(R.id.gridview1);
adapter1 = new ArrayAdapter<String>(this, R.layout.simple_item, alphabets);
gridView.setAdapter(adapter1);
}
}

Q.6 c Develop a simple calculator using relative layout. [6M W-22]

Ans:
activity_main.xml

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


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/heading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Calculator"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
<EditText
android:id="@+id/num1"
android:layout_below="@+id/heading"
android:layout_width="match_parent"
Examination Paper Analysis and Solution

android:layout_height="wrap_content"
android:hint="Enter Number 1"
android:inputType="number" />
<EditText
android:id="@+id/num2"
android:layout_below="@+id/num1"
android:hint="Enter Number 2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number" />
<TextView
android:id="@+id/result"
android:layout_below="@+id/num2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
android:text="Result" />
<Button
android:id="@+id/sum"
android:layout_below="@id/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="+" />
<Button
android:id="@+id/sub"
android:layout_below="@id/result"
android:layout_toRightOf="@id/sum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="-" />
<Button
android:id="@+id/div"
android:layout_below="@id/result"
android:layout_toRightOf="@id/sub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="/" />
<Button
android:id="@+id/mul"
android:layout_below="@id/result"
android:layout_toRightOf="@id/div"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="x"/>
</RelativeLayout>
Examination Paper Analysis and Solution

MainActivity.java
package in.msbte.calculator;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public EditText e1, e2;
Button add, sub , mul, div;
TextView t1;
int num1, num2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1 = (EditText) findViewById(R.id.num1);
e2 = (EditText) findViewById(R.id.num2);
t1 = (TextView) findViewById(R.id.result);
add = (Button) findViewById(R.id.sum);
mul = (Button) findViewById(R.id.mul);
div = (Button) findViewById(R.id.div);
sub = (Button) findViewById(R.id.sub);
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
num1 = Integer.parseInt(e1.getText().toString());
num2 = Integer.parseInt(e2.getText().toString());
int sum = num1 + num2;
t1.setText(Integer.toString(sum));
}
});
sub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
num1 = Integer.parseInt(e1.getText().toString());
num2 = Integer.parseInt(e2.getText().toString());
int sum = num1 - num2;
t1.setText(Integer.toString(sum));
}
});
mul.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
num1 = Integer.parseInt(e1.getText().toString());
num2 = Integer.parseInt(e2.getText().toString());
int sum = num1 * num2;
t1.setText(Integer.toString(sum));
}
});
div.setOnClickListener(new View.OnClickListener() {
Examination Paper Analysis and Solution

@Override
public void onClick(View view) {
num1 = Integer.parseInt(e1.getText().toString());
num2 = Integer.parseInt(e2.getText().toString());
int sum = num1 / num2;
t1.setText(Integer.toString(sum));
}
});
}
}

Summer 2023

Q.1 C List various layouts used in android UI design. [2M]


Ans:

• Linear Layout
• Absolute Layout
• Frame Layout
• Table Layout
• Relative Layout

Q.3 b Explain Gridview with its attributes with suitable example. [4 M]


Ans:
GridView :
Android GridView shows items in two-dimensional scrolling grid (rows & columns) and the grid
items are not necessarily predetermined but they automatically inserted to the layout using a
ListAdapter.

activity_main.xml Code :

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


<GridView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="90dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp"
tools:context=".MainActivity">
</GridView>
activity_listview.xml code :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
Examination Paper Analysis and Solution

android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btn"
android:layout_width="fill_parent"
layout_height="wrap_content"
android:layout_gravity="center" />
</LinearLayout>

MainActivity.java
package com.example.myapplication.gridviewbuttons;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
GridView gridview;
String arr[] = new String[15];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridview = findViewById(R.id.gridview);
for (int i = 0; i < 15; i++) {
arr[i] = Integer.toString(i + 1);
}
ArrayAdapter<String> ad = new ArrayAdapter<String>(this, R.layout.activity_listview,
R.id.btn, arr);
gridview.setAdapter(ad);
}
}

Q 4 a Describe directory structure and its components. [4 M]


Ans:
The android project contains different types of app modules, source code files, and resource files.
1. Manifests Folder
2. Java Folder
3. res (Resources) Folder

• Drawable Folder
• Layout Folder
• Mipmap Folder
• Values Folder
4. Gradle Scripts
Examination Paper Analysis and Solution

Manifests Folder
Manifests folder contains AndroidManifest.xml for creating our android application. This file
contains information about our application such as the Android version, metadata, states package
for Kotlin file, and other application components. It acts as an intermediator between android OS
and our application.
Java folder
The Java folder contains all the java source code (.java) files that we create during the app
development, including other Test files. If we create any new project using Java, by default the
class file MainActivity.java will be created.
Resource (res) folder
The resource folder is the most important folder because it contains all the non-code sources like
images, XML layouts, and UI strings for our android application.
res/drawable folder
It contains the different types of images used for the development of the application. We
need to add all the images in a drawable folder for the application development.
res/layout folder
The layout folder contains all XML layout files which we used to define the user interface of our
application. It contains the activity_main.xml file
res/mipmap folder
This folder contains launcher.xml files to define icons that are used to show on the home screen. It
contains different density types of icons depending upon the size of the device such as hdpi, mdpi,
xhdpi.
res/values folder
Values folder contains a number of XML files like strings, dimensions, colors, and style definitions.
One of the most important files is the strings.xml file which contains the resources.
Examination Paper Analysis and Solution

Gradle Scripts folder


Gradle means automated build system and it contains a number of files that are used to
define a build configuration that can be applied to all modules in our application. In
build.gradle (Project) there are buildscripts and in build.gradle (Module) plugins and
implementations are used to build configurations that can be applied to all our application
modules.

Summer 2023

Q 6 C Explain how linear and frame layout is used to design an android application with
suitable example. [6 M S-23]

Ans:
Linear Layout:
• Android LinearLayout is a view group that aligns all children in either vertically or horizontally.
• Vertically or horizontally direction depends on attribute android: orientation.
• Linear layout is simple and easy to use, it creates a scroll bar if the length of the window exceeds
the length of the screen.
• Linear Layout are one of the simplest and common type of layouts used by Android developers
to keep controls within their interfaces. The linear layout works as much as its name implies, it
organizes the controls either a vertical or horizontal pattern.
• When the layout’s orientation is set to vertical, all child controls within organized in a single
column, and when the layout’s orientation is set to horizontal, all child controls within in
single row.

Example

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


<LinearLayoutandroid:layout_width="368dp"
android:layout_height="495dp"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp"
xmlns:android="http://schemas.android.com/apk/res/android">
<Button
android:id="@+id/button5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button1" />
<Button
android:id="@+id/button6"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button2" />
<Button
android:id="@+id/button7"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button3" />
<Button
Examination Paper Analysis and Solution

android:id="@+id/button8"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button4" />
</LinearLayout>

Frame Layout:

• Frame Layout is designed to block out an area on the screen to display a single item. Generally,
FrameLayout should be used to hold a single child view, because it can be difficult to organize
child views in a way that's scalable to different screen sizes without the children overlapping each
other.
• Frame layouts are one of the simplest layout types used to organize controls within the user
interface of an Android application. The purpose of FrameLayout is to allocate an area of screen.
• Frame layouts are one of the most efficient types of layouts used by Android developers to
organize view controls. They are used less often than some other layouts, simply because they are
generally used to display only one view, or views which overlap.
• The frame layout is often used as a container layout, as it generally only has a single child view
(often another layout, used to organize more than one view).

Example

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


<FrameLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/framelayout"
android:layout_width="200dp"
android:layout_height="300dp"
tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="90dp"
android:layout_marginLeft="20dp"
android:text="Button"/>
<TextView
android:layout_width="100dp"
android:layout_height="50dp"
android:textSize="20sp"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:background="@color/colorPrimary"
android:textColor="#fff"
android:text="I am TextView" />
</FrameLayout >

Q. 1.C List any four attributes of layout. [4 M]

Ans:
• android:id
Examination Paper Analysis and Solution

• android:layout_width
• android:layout_height
• android:layout_margin
• android:layout_marginTop
• android:layout_marginBottom
• android:layout_marginLeft
• android:layout_marginRight
• android:background

Q 2 a Explain relative layout with all its attributes. [4 M]

Ans:

In Relative Layout we need to specify the position of child views relative to each other or relative
to the parent. In case if we didn’t specify the position of child views, by default all child views are
positioned to top-left of the layout.
Attributed of Relative Layout:

1. android:layout_centerHorizontal="true"

This places the view horizontally in the center of the parent. As our parent view covers
the whole screen of mobile therefore the view gets placed in the middle of the mobile
screen horizontally. (See the yellow view in the above figure)

2. android:layout_centerVertical="true"

This places the view vertically in the center of the parent. Since the parent view covers
the whole screen of mobile hence the view gets placed in the middle of the mobile screen
vertically. (See the blue view in the above figure)

3. android:layout_centerInParent="true"

This attribute will place the view in the center of the parent. Since the parent in our
example covers the whole screen of mobile, so the view gets placed in the middle of the
mobile screen, both horizontally and vertically.

1. android:layout_alignParentTop="true"

If you write this attribute for a View, then that view will stick to the top of its parent.
Since the parent covers the whole screen of mobile therefore, the view will appear
sticking to the top-left of the mobile screen.

2. android:layout_alignParentBottom="true"

If you write this attribute for a View, then that view will stick to the bottom of its parent.
Since the our parent covers the whole screen of mobile therefore, the view will appear
sticking to the bottom of the mobile screen.

3. android:layout_alignParentLeft="true"
Examination Paper Analysis and Solution

If you write this attribute for a View, then that view will stick to the left of its parent.
Since the parent in our example covers the whole screen of mobile therefore, the view
will appear sticking to the left of the mobile screen.

4. android:layout_alignParentRight="true"

If you write this attribute for a View, then that view will stick to the right of its parent.

Q. 3 C Write an xml file to create login page using Table Layout.


Ans:

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000"
android:orientation="vertical"
android:stretchColumns="1">
<TableRow android:padding="5dip">
<TextView
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:layout_span="2"
android:gravity="center_horizontal"
text="@string/loginForm"
android:textColor="#0ff"
android:textSize="25sp"
android:textStyle="bold" />
</TableRow>
<TableRow>
<TextView
android:layout_height="wrap_content"
android:layout_column="0"
android:layout_marginLeft="10dp"
android:text="@string/userName"
android:textColor="#fff"
android:textSize="16sp" />
<EditText
android:id="@+id/userName"
android:layout_height="wrap_content"
android:layout_column="1"
android:layout_marginLeft="10dp"
android:background="#fff"
android:hint="@string/userName"
android:padding="5dp"
android:textColor="#000" />
</TableRow>
<TableRow>
<TextView
android:layout_height="wrap_content"
android:layout_column="0"
Examination Paper Analysis and Solution

android:layout_marginLeft="10dp"
android:layout_marginTop="20dp"
android:text="@string/password"
android:textColor="#fff"
android:textSize="16sp" />
<EditText
android:id="@+id/password"
android:layout_height="wrap_content"
android:layout_column="1"
android:layout_marginLeft="10dp"
android:layout_marginTop="20dp"
android:background="#fff"
android:hint="@string/password"
android:padding="5dp"
android:textColor="#000" />
</TableRow>
<TableRow android:layout_marginTop="20dp">
<Button
android:id="@+id/loginBtn"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_span="2"
android:background="#0ff"
android:text="@string/login"
android:textColor="#000"
android:textSize="20sp"
android:textStyle="bold" />
</TableRow>
</TableLayout>

Q.4 B Explain components of android directory structure. [4 M]

Ans:
The android project contains different types of app modules, source code files, and resource files.
Following are the components/ modules of android directory:
1) Manifests Folder
Manifests folder contains AndroidManifest.xml for creating our android application. This file
contains information about our application such as the Android version, metadata, states package
for Kotlin file, and other application components. It acts as an intermediator between android OS
and our application.
2) Java folder
The Java folder contains all the java source code (.java) files that we create during the app
development, including other Test files.
3) Resource (res) folder
The resource folder is the most important folder because it contains all the non-code sources like
images, XML layouts, and UI strings for our android application.
res/drawable folder

It contains the different types of images used for the development of the application. We need to
add all the images in a drawable folder for the application development.
res/layout folder
Examination Paper Analysis and Solution

The layout folder contains all XML layout files which we used to define the user interface of our
application. It contains the activity_main.xml file.
res/mipmap folder

This folder contains launcher.xml files to define icons that are used to show on the home screen. It
contains different density types of icons depending upon the size of the device such as hdpi, mdpi,
xhdpi.
res/values folder

Values folder contains a number of XML files like strings, dimensions, colors, and style definitions.
One of the most important files is the strings.xml file which contains the resources.
4) Gradle Scripts folder
Gradle means automated build system and it contains a number of files that are used to define a
build configuration that can be applied to all modules in our application. In build.gradle (Project)
there are buildscripts and in build.gradle (Module) plugins and implementations are used to build
configurations that can be applied to all our application modules.

Unit 4 : Designing User Interface with View

Summer 2022

Q 3 b State syntax to create Text View and Image button with any two attributes of each. [4
M]
Ans:

Text View:
Syntax :
<TextView
android:id="@+id/textView1"
android:layout_width="<width value>”
android:layout_height="<height_value>"
android:text="<text to be displayed>"/>

Attributes/Properties of TextView:
● id: Supply an identifier name of this view, to later retrieve it with View.findViewByID() or
Activity.findViewById()
● alpha: alpha property of the view as a value between 0 (entirely transparent) and
1(Completely Opaque). [flag]
● auto link: Controls whether links such as urls and email addresses are automatically found
and converted to clickable links.[flag]
● gravity: The gravity attribute is an optional attribute which is used to control the alignment
of the text like left, right, center, top, bottom, center_vertical, center_horizontal etc
● text: text attribute is used to set the text in a text view. We can set the text in xml as
well as in the java class.
● textColor: textColor attribute is used to set the text color of a text view. Color value is in the
form of “#argb”, “#rgb”, “#rrggbb”, or “#aarrggbb”.
● textSize: textSize attribute is used to set the size of text of a text view. We can set the text
size in sp(scale independent pixel) or dp(density pixel).
Examination Paper Analysis and Solution

● textStyle: textStyle attribute is used to set the text style of a text view. The possible text
styles are bold, italic and normal. If we need to use two or more styles for a text view then “|”
operator is used for that.
● background: background attribute is used to set the background of a text view. We can set
a color or a drawable in the background of a text view.
● padding: padding attribute is used to set the padding from left, right, top or bottom. In above
example code of background we also set the 10dp padding from all the sides of text view.

ImageButton:

Syntax :

<ImageButton
android:id="@+id/imageButton"
android:layout_width="<width value>"
android:layout_height="<height value>"
app:srcCompat="<image source from drawable folder "/>

Attributes/Properties of ImageButton:
● id: id is an attribute used to uniquely identify a image button. Below is the example code in
which we set the id of a image button.
● src: src is an attribute used to set a source file of image or you can say image in your image
button to make your layout look attractive.
● background: background attribute is used to set the background of an image button. We can
set a color or a drawable in the background of a Button.
● padding: padding attribute is used to set the padding from left, right, top or bottom of the
ImageButton.

Q 4 b Write a program to demonstrate Date and Time picker.


(Note: Consider the appropriate XML file. All attributes are not required. In java file all imports
are not expected. Different relevant logic/code can be considered.) [4 M]
Ans:

activity_main.xml

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


<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/tvDate"
android:layout_width="149dp"
android:layout_height="46dp"
android:layout_marginEnd="224dp"
android:layout_marginBottom="312dp"
Examination Paper Analysis and Solution

android:textSize="20dp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<Button
android:id="@+id/btnDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="96dp"
android:layout_marginBottom="312dp"
android:text="Set Date"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
tools:ignore="DuplicateClickableBoundsCheck" />
<DatePicker
android:id="@+id/dtpcker"
android:layout_width="314dp"
android:layout_height="293dp"
android:layout_marginBottom="368dp"
android:datePickerMode="spinner"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.36"
app:layout_constraintStart_toStartOf="parent" />
<TimePicker
android:id="@+id/timepcker"
android:layout_width="184dp"
android:layout_height="195dp"
android:layout_marginEnd="132dp"
android:layout_marginBottom="108dp"
android:timePickerMode="spinner"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<TextView
android:id="@+id/tvTime"
android:layout_width="130dp"
android:layout_height="56dp"
android:layout_marginEnd="232dp"
android:layout_marginBottom="40dp"
android:textSize="20dp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<Button
android:id="@+id/btnTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="104dp"
android:layout_marginBottom="48dp"
android:text="Set Time"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
Examination Paper Analysis and Solution

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java

package com.example.datepickereg;
import androidx.appcompat.app.AppCompatActivity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
TextView tvDate,tvTime;
DatePicker dtpcker;
TimePicker timepcker;
Button b1,b2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvDate=findViewById(R.id.tvDate);
tvTime=findViewById(R.id.tvTime);
b1=findViewById(R.id.btnDate);
b2=findViewById(R.id.btnTime);
dtpcker=findViewById(R.id.dtpcker);
timepcker=findViewById(R.id.timepcker);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
tvDate.setText("Date : "+dtpcker.getDayOfMonth()+"-"+dtpcker.getMonth()+"-
"+dtpcker.getYear());
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
tvTime.setText(timepcker.getCurrentHour()+":"+timepcker.getCurrentMinute());
}
});
}
}

Q. 5 a Write a program to convert temperature from celcius to farenhite and vice versa using
Toggle button. (Design UI as per your choice. Write XML and java file)
(Note: Consider the appropriate XML file. All attributes are not required. In java file all imports
are not expected. Different relevant logic/code can be considered.) [6 M]
Examination Paper Analysis and Solution

Ans:

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edittext"
android:hint="Enter the temp"/>
<ToggleButton
android:id="@+id/togglebutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/edittext"
android:layout_marginTop="35dp"
android:textOff="F to C"
android:textOn="C to F" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/togglebutton"
android:layout_marginTop="56dp" />
</RelativeLayout>

MainActivity.java

package com.example.p1;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends AppCompatActivity {
Button b1;
EditText et;
ToggleButton tb;
Double a;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et=findViewById(R.id.edittext);
Examination Paper Analysis and Solution

b1=findViewById(R.id.button);
tb=findViewById(R.id.togglebutton);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(tb.isChecked())
{
a=Double.parseDouble(String.valueOf(et.getText()));
Double b=a*9/5+32;
String r=String.valueOf(b);
Toast.makeText(MainActivity.this,r+"°F",Toast.LENGTH_SHORT).show();
}
else
{
a=Double.parseDouble(String.valueOf(et.getText()));
Double b=a-32;
Double c=b*5/9;
String r=String.valueOf(c);
Toast.makeText(MainActivity.this,r+"°C",Toast.LENGTH_SHORT).show();
}
}
});
}
}

Winter 2022

Q 1 d Enlist the elements of UI. [2M]


Ans:
Elements of UI:
● Menu Bar
● Toolbar
● Navigation Bar
● Editor Tabs
● Editor
● Project Explorer
● Status Bar
● Tool Buttons

Q 3 a Explain data and time picker with its method.[4 M]

Ans: Refer question 4 b Summer 22


Examination Paper Analysis and Solution

Winter 2022

Q 4 b Write a program to display a rectangular progress bar. [4 M]

Ans:
Xml File:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ProgressBar
android:id="@+id/progressBar"
style="@android:style/Widget.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:indeterminate="false"
android:max="100"
android:minHeight="50dp"
android:minWidth="200dp"
android:progress="1" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/progressBar"
android:layout_below="@+id/progressBar"/>
</RelativeLayout>

Java file:

package in.edu.vpt.progressbar;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private ProgressBar progressBar;
private int progressStatus = 0;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
Examination Paper Analysis and Solution

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
textView = (TextView) findViewById(R.id.textView);
// Start long running operation in a background thread
new Thread(new Runnable() {
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
progressBar.setProgress(progressStatus);
textView.setText(progressStatus+"/"+progressBar.getMax());
}
});
try {
// Sleep for 200 milliseconds.
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}

Summer 2023

Q 1 d Name any four attributes of Edit Text control.[ 2 M]


Ans:
android:id
android: gravity
android: text
android: hint
android: textColor
android: textSize
android: textStyle
android: background

Q 4 b Develop an android application for Date and Time Picker. [4 M]


Ans:

Refer question 4 b Summer 22

Q 5 a Design a employee registration form using UI component. [6 M]


Ans:

activity_main.xml
Examination Paper Analysis and Solution

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:text="Employee Registration Form"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:id="@+id/textView"
android:gravity="center"
android:textSize="20dp"
android:textColor="#000000"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="ID"
android:id="@+id/editid"
android:layout_below="@+id/textView"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Name"
android:id="@+id/editname"
android:layout_below="@+id/editid"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Mobile No."
android:id="@+id/editmobile"
android:layout_below="@+id/editname"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Address"
android:lines="3"
android:id="@+id/editaddress"
android:layout_below="@+id/editmobile"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Pin Code"
android:id="@+id/editpincode"
android:layout_below="@+id/editaddress"/>
<Button
android:text="Submit Details"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
Examination Paper Analysis and Solution

android:layout_below="@+id/editpincode"
android:layout_centerHorizontal="true"
android:id="@+id/button" />
</RelativeLayout>

Winter 2023

Q 1 f Write difference between toggle button and radio button. [2 M]


Ans:

Toggle Button Radio button


ToggleButton can be used to display checked Radio Button is used to select one option from
or unchecked list
For ON/OFF two labels can be design There is only one lable for radio button

Q. 3 d Develop an application to display analog Time Picker. Also display the selected time.
(Write only . java file) [4M]
Ans:

MainActivity.java

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
public class MainActivity extends AppCompatActivity {
TextView textview1;
TimePicker timepicker;
Button changetime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview1=(TextView)findViewById(R.id.textView1);
timepicker=(TimePicker)findViewById(R.id.timePicker);
//Uncomment the below line of code for 24 hour view
timepicker.setIs24HourView(true);
changetime=(Button)findViewById(R.id.button1);
textview1.setText(getCurrentTime());
changetime.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
textview1.setText(getCurrentTime());
}
});
}
public String getCurrentTime(){
String currentTime="Current Time:
"+timepicker.getCurrentHour()+":"+timepicker.getCurrentMinute();
return currentTime;
Examination Paper Analysis and Solution

}
}

Q. 4 c Develop an android application using radio button. [4M]

Ans:
Consider any relevant example of Radio Button and in XML file, consider minimum
attributes]
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools=http://schemas.android.com/tools
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="30dp"
tools:context=".frame">
<TextView android:id="@+id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Radio Button"
android:textSize="20dp"
android:gravity="center"
android:textColor="#f00"/>
<RadioGroup android:id="@+id/group"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/text1">
<RadioButton android:id="@+id/male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male"/>
<RadioButton
android:id="@+id/female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/male"
android:text="Female"/>
</RadioGroup>
<Button android:id="@+id/submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/group"
android:layout_marginTop="99dp"
android:layout_centerHorizontal="true"
android:text="Submit" />
</RelativeLayout>

Java File:

package com.example.ifcdiv;
import androidx.appcompat.app.AppCompatActivity;
Examination Paper Analysis and Solution

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.Toast;
public class frame extends AppCompatActivity
{
RadioButton male,female;
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frame);
male=findViewById(R.id.male);
female=findViewById(R.id.female);
b1=findViewById(R.id.submit);
b1.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
String selected; if(male.isChecked())
{
selected="You selected"+male.getText();
}
else
{
selected="You Selected"+female.getText();
}
Toast.makeText(getApplicationContext(),selected,Toast.LENGTH_LONG).show();
} });
}
}

Q 5 a Develop a program to perform addition, subtraction, division, multiplication of two


numbers and display the result. (Use appropriate UI controls). [6 M]
Ans:

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required
details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="4dp">
<TextView
android:id="@+id/textResult"
android:layout_width="wrap_content"
Examination Paper Analysis and Solution

android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:background="#008080"
android:padding="5dp"
android:text="Code4Example"
android:textColor="#fff"
android:textSize="24sp"
android:textStyle="bold" />
<EditText
android:id="@+id/editNum1"
android:inputType="number"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<EditText
android:id="@+id/editNum2"
android:inputType="number"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/editNum1"
android:layout_centerInParent="true" />
<GridLayout
android:layout_centerHorizontal="true"
android:layout_centerInParent="true"
android:layout_below="@+id/editNum2"
android:columnCount="2"
android:rowCount="2"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_margin="1dp"
android:onClick="btnAdd"
android:text="+" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_margin="1dp"
android:onClick="btnSub"
android:text="-" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_margin="1dp"
android:onClick="btnMul"
android:text="*" />
<Button
Examination Paper Analysis and Solution

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_margin="1dp"
android:onClick="btnDiv"
android:text="/" />
</GridLayout>
</RelativeLayout>

Step 3 − Add the following code to src/MainActivity.java

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText editNum1,editNum2;
TextView textResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editNum1= findViewById(R.id.editNum1);
editNum2= findViewById(R.id.editNum2);
textResult= findViewById(R.id.textResult);
}
public void btnAdd(View view){
double num1 = Double.parseDouble(editNum1.getText().toString());
double num2 = Double.parseDouble(editNum2.getText().toString());
double result = num1 + num2;
textResult.setText(Double.toString(result));
}
public void btnSub(View view){
double num1 = Double.parseDouble(editNum1.getText().toString());
double num2 = Double.parseDouble(editNum2.getText().toString());
double result = num1 - num2;
textResult.setText(Double.toString(result));
}
public void btnMul(View view){
double num1 = Double.parseDouble(editNum1.getText().toString());
double num2 = Double.parseDouble(editNum2.getText().toString());
double result = num1 * num2;
textResult.setText(Double.toString(result));
}
public void btnDiv(View view){
double num1 = Double.parseDouble(editNum1.getText().toString());
double num2 = Double.parseDouble(editNum2.getText().toString());
double result = num1 / num2;
textResult.setText(Double.toString(result));
}
Examination Paper Analysis and Solution

Unit 5: Activity and Multimedia with databases

Summer 2022

Q1 e Draw diagram of activity life cycle.[2 M]

.
Ans:
Examination Paper Analysis and Solution

Q1 g Name two classes used to play audio and video in Android.[2 M]

Ans:

1) MediaPlayer
Examination Paper Analysis and Solution

2) MediaController

3) AudioManager

Q2 d Describe with example, how to create a simple database in SQLite (Assume suitable
data). [4M]
Ans:
This procedure is by openOrCreateDatabase()
1. The package imported into the application is android.database.sqlite.SQLiteDatabase.
2. Here the class used is SQLiteDatabase.
3. The method used to create the database or connect to the database is
openOrCreateDatabase() method.

Program:

activity_main.xml

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context=".MainActivity">
<Button
android:text="Create SQLite Database"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="46dp"
android:id="@+id/button" />
</RelativeLayout>

MainActivity.java
package in.edu.vpt.insertusingasync;
import android.app.ProgressDialog;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
SQLiteDatabase sqLiteDatabaseObj;
Button EnterData;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createData = (Button)findViewById(R.id.button);
createData.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
Examination Paper Analysis and Solution

sqLiteDatabaseObj = openOrCreateDatabase("AndroidJSonDataBase",
Context.MODE_PRIVATE, null);
}
}); }
}
Q3 c Describe Android service life cycle along with diagram. (S-22) 4Marks

Ans:

● A service is an application component which runs without direst interaction with the user in
the background.
● Services are used for repetitive and potentially long running operations, i.e., Internet
downloads, checking for new data, data processing, updating content providers and the like.
● Service can either be started or bound we just need to call either startService() or
bindService() from any of our android components. Based on how our service was started it
will either be “started” or “bound”

Service Lifecycle
1. Started
a. A service is started when an application component, such as an activity, starts it by calling
startService().
b. Now the service can run in the background indefinitely, even if the component that started
it is destroyed.
2. Bound
a. A service is bound when an application component binds to it by calling bindService().
Examination Paper Analysis and Solution

b. A bound service offers a client-server interface that allows components to interact with the
service, send requests, get results, and even do so across processes with InterProcess
Communication (IPC).
c. Like any other components service also has callback methods. These will be invoked while
the service is running to inform the application of its state. Implementing these in our custom
service would help you in performing the right operation in the right state. •
d. There is always only a single instance of service running in the app. If you are calling
startService() for a single service multiple times in our
application it just invokes the onStartCommand() on that service. Neither is the service
restarted multiple times nor are its multiple instances created
1. onCreate():
This is the first callback which will be invoked when any component starts the service. If the
same service is called again while it is still running this method wont be invoked. Ideally one
time setup and intializing should be done in this callback.
2. onStartCommand() /startSetvice()
This callback is invoked when service is started by any component by calling startService(). It
basically indicates that the service has started and can now run indefinetly.
3. onBind()
To provide binding for a service, you must implement the onBind() callback method. This
method returns an IBinder object that defines the programming interface that clients can use to
interact with the service.
4. onUnbind()
This is invoked when all the clients are disconnected from the service.
5. onRebind()
This is invoked when new clients are connected to the service. It is called after onRebind
6. onDestroy()
This is a final clean up call from the system. This is invoked just before the service is being
destroyed.

Q4 c Describe multimedia framework of Android with diagram. (S-23, S-22) 4Marks


Ans:

● The android multimedia system includes multimedia applications, multimedia frameworks,


OpenCore engine and hardware abstract for audio/video input/output devices. And the goal of
the android multimedia framework is to provide a reliable interface for java services. The
multimedia framework consists of several core dynamic libraries such as libmediajni, libmedia,
libmediaplayservice and so on.
● Java classes call the Native C library Libmedia through Java JNI(Java Native Interface).
Libmedia library communications with Media Server guard process through Android’s Binder
IPc (inter process communication) mechanism.
● Media Server process creates the corresponding multimedia service according to the Java
multimedia applications.
● The whole communication between Libmedia and Media Server forms a Client/Server model
Examination Paper Analysis and Solution

Android Multimedia Framework Architecture

● Typical video/audio data stream works in Android as follows. Particularly, Java applications
first set the URI of the media (from file or network) to PVPlayer through Java framework, JNI
and Native C. In this process, there are no data stream flows.
● Then PVPlayer processes the media data stream with the steps: demux the media data to
separate video/audio data stream, decode video/audio data, sync video.audio time, send the
decoded data out.
● The below is the description of media codec/format, container and network protocol
supported by the Android platform.
1. Container: The audio file format is a file for storing digital audio data on a system. This data
can be manipulated to reduce the size or change the quality of the audio. It is a kind of container
to store audio information.
2. Audio Format: Any format or codec can be used including the ones provided by Android or
those which are specific devices. However it is recommended to use the specified file formats
as per devices.
3. Network Protocol: Protocols such as RTSP, HTTP,HTTPS are supported in audio and video
playback.

Q5 b Write a program to capture an image using camera and display it. (S-22) 6Marks
(Note: Consider the appropriate XML file. All attributes are not required.
In java file all imports are not expected. Different relevant logic/code can be considered.)

Ans:
Examination Paper Analysis and Solution

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="40dp"
android:orientation="horizontal"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="CAMERA"
android:id="@+id/text"
android:textSize="20dp"
android:gravity="center"/>
<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/text"
android:layout_marginTop="81dp"
android:src="@drawable/rose"/>
<Button
android:id="@+id/photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/image"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:text="TAKE PHOTO" />
</RelativeLayout>

MainActivity.java
package com.example.ifcdiv;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.Bitmap; import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
Button b1;
ImageView imageView;
int CAMERA_REQUEST=1;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
Examination Paper Analysis and Solution

b1=findViewById(R.id.photo); imageView=findViewById(R.id.image);
b1.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
Intent i=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i,CAMERA_REQUEST); } }); }
@Override protected void onActivityResult(int requestCode, int resultCode, @Nullable
Intent data) { super.onActivityResult(requestCode, resultCode, data);
if (requestCode==CAMERA_REQUEST) { Bitmap image= (Bitmap)
data.getExtras().get("data");
imageView.setImageBitmap(image); } } }

Q6 a Write a program to implement Android Activity Life Cycle. Use toast messages to
display message through life cycle.
(S-22) 6Marks
(Note: No XML code is required. In java file all imports are not expected.)

Ans:
package com.example.p1;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(getApplicationContext(),"Activity
created",Toast.LENGTH_LONG).show(); }
@Override protected void onStart() {
super.onStart();
Toast.makeText(getApplicationContext(),"Activity
Started",Toast.LENGTH_LONG).show(); }
@Override protected void onStop() {
super.onStop();
Toast.makeText(getApplicationContext(),"Activity
Stop",Toast.LENGTH_LONG).show(); }
@Override protected void onDestroy() {
super.onDestroy();
Toast.makeText(getApplicationContext(),"Activity
Destroy",Toast.LENGTH_LONG).show(); }
@Override protected void onPause() {
super.onPause();
Toast.makeText(getApplicationContext(),"Activity
Pause",Toast.LENGTH_LONG).show(); }
@Override protected void onRestart() {
super.onResume();
Toast.makeText(getApplicationContext(),"Activity
Restart",Toast.LENGTH_LONG).show();
Examination Paper Analysis and Solution

@Override protected void onResume() {


super.onResume();
Toast.makeText(getApplicationContext(),"Activity
Resume",Toast.LENGTH_LONG).show(); } }

Q1 e State the uses of Intent in Android. .


(W-22) 2Marks
Ans:
An Intent is a messaging object you can use to request an action from
another app component.
Intents are used for facilitating communication between components like
Activities, Services and Broadcast Receivers.

Q1 g Explain significance of content provider. .


(W-22) 2Marks
Ans:
Content Providers are used to share data between two applications. This
can be implemented in two ways:
1. When you want to implement the existing content provider in another
application.
2. When you want to create a new content provider that can share its data
with other Applications

Q3 c Explain the activity life cycle.


. (W-22) 4Marks

Ans:
Examination Paper Analysis and Solution

Activities have a predefined life-cycle methods as follows:

onCreate (): Called then the activity is created. Used to initialize the
activity, for
example create the user interface.

onStart ():called when activity is becoming visible to the user.

onResume (): Called if the activity get visible again and the user starts
interacting
with the activity again. Used to initialize fields, register listeners, bind
to services, etc.

onPause (): Called once another activity gets into the foreground. Always
called
before the activity is not visible anymore. Used to release resources or
save application data. For example you unregister listeners, intent
receivers, unbind from services or remove system service listeners.

onStop (): Called once the activity is no longer visible. Time or CPU
intensive shutdown
operations, such as writing information to a database should be down in
the onStop() method. This method is guaranteed to be called as
of API 11.

onDestroy (): called before the activity is destroyed.


Examination Paper Analysis and Solution

Q.5 b Develop a program for providing Bluetooth connectivity.


(W-22) 6Marks

activity_main.xml
<RelativeLayout
xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView android:text=""
android:id="@+id/out"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="30dp"
android:layout_marginTop="49dp"
android:text="TURN_ON" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/button1"
android:layout_marginTop="27dp"
android:text="DISCOVERABLE" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button2"
android:layout_below="@+id/button2"
android:layout_marginTop="28dp"
android:text="TURN_OFF" />
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>

<manifest
xmlns:androclass="http://schemas.android.com/apk/res/android"
package="com.example.bluetooth"
android:versionCode="1"
Examination Paper Analysis and Solution

android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission
android:name="android.permission.BLUETOOTH_ADMIN" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.bluetooth.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.java
package com.example.bluetooth;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int REQUEST_ENABLE_BT = 0;
private static final int REQUEST_DISCOVERABLE_BT = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

final TextView out=(TextView)findViewById(R.id.out);


final Button button1 = (Button) findViewById(R.id.button1);
final Button button2 = (Button) findViewById(R.id.button2);
final Button button3 = (Button) findViewById(R.id.button3);
Examination Paper Analysis and Solution

final BluetoothAdapter mBluetoothAdapter =


BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
out.append("device not supported");
}
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if (!mBluetoothAdapter.isDiscovering()) {
//out.append("MAKING YOUR DEVICE DISCOVERABLE");
Toast.makeText(getApplicationContext(), "MAKING YOUR DEVICE
DISCOVERABLE",
Toast.LENGTH_LONG);
Intent enableBtIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(enableBtIntent,
REQUEST_DISCOVERABLE_BT);
}
}
});
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
mBluetoothAdapter.disable();
//out.append("TURN_OFF BLUETOOTH");
Toast.makeText(getApplicationContext(), "TURNING_OFF
BLUETOOTH", Toast.LENGTH_LONG);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Examination Paper Analysis and Solution

Q.6 a Develop an application to store customer's details like, customer-id,


customer-name, mobile number, address, pin-code and retrieve customer
information using customer-id in SQLite databases.
(W-22) 6Marks
Ans:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:text="Insert Customer Details"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:id="@+id/textView"
android:gravity="center"
android:textSize="20dp"
android:textColor="#000000"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="ID"
android:id="@+id/editid"
android:layout_below="@+id/textView"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Name"
android:id="@+id/editname"
android:layout_below="@+id/editid"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Mobile No."
android:id="@+id/editmobile"
android:layout_below="@+id/editname"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Address"
android:lines="3"
android:id="@+id/editaddress"
android:layout_below="@+id/editmobile"/>
<EditText
android:layout_width="fill_parent"
Examination Paper Analysis and Solution

android:layout_height="wrap_content"
android:hint="Pin Code"
android:id="@+id/editpincode"
android:layout_below="@+id/editaddress"/>
<Button
android:text="Insert Data"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/editpincode"
android:layout_centerHorizontal="true"
android:id="@+id/button" />
<TextView
android:text="Search Customer Details"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:layout_centerHorizontal="true"
android:id="@+id/textView1"
android:gravity="center"
android:textSize="20dp"
android:layout_below="@+id/button"
android:textColor="#000000"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Enter ID"
android:id="@+id/editsearchid"
android:layout_below="@+id/textView1"/>
<Button
android:text="Search Data"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/editsearchid"
android:layout_centerHorizontal="true"
android:id="@+id/button1" />
</RelativeLayout>
MainActivity.java
package in.msbte.database;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
SQLiteDatabase sqLiteDatabaseObj;
Examination Paper Analysis and Solution

EditText editTextID, editTextName, editMobileNo, editAddress,


editPincode, editSearchid;
String cid, cname, cmobile, caddress, cpincode, sql_query, sid;
Button EnterData, SearchData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EnterData = (Button)findViewById(R.id.button);
SearchData = (Button)findViewById(R.id.button1);
editTextID = (EditText)findViewById(R.id.editid);
editTextName = (EditText)findViewById(R.id.editname);
editMobileNo = (EditText)findViewById(R.id.editmobile);
editAddress = (EditText)findViewById(R.id.editaddress);
editPincode = (EditText)findViewById(R.id.editpincode);
editSearchid = (EditText)findViewById(R.id.editsearchid);
EnterData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sqLiteDatabaseObj = openOrCreateDatabase("AndroidJSonDataBase",
Context.MODE_PRIVATE, null);
sqLiteDatabaseObj.execSQL("CREATE TABLE IF NOT EXISTS
AndroidJSonTable(id INTEGER PRIMARY KEY AUTOINCREMENT
NOT NULL, cid VARCHAR, name VARCHAR, mobile VARCHAR,
address VARCHAR, pincode VARCHAR);");
cid = editTextID.getText().toString();
cname = editTextName.getText().toString() ;
cmobile = editMobileNo.getText().toString();
caddress = editAddress.getText().toString();
cpincode = editPincode.getText().toString();
sql_query = "INSERT INTO AndroidJSonTable (cid, name, mobile,
address, pincode) VALUES('"+cid+"', '"+cname+"', '"+cmobile+"',
'"+caddress+"', '"+cpincode+"');";
sqLiteDatabaseObj.execSQL(sql_query);

Toast.makeText(getApplicationContext(), "Data Inserted Successfully",


Toast.LENGTH_LONG).show();
}
});
SearchData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sid = editSearchid.getText().toString();
Cursor cursor = sqLiteDatabaseObj.rawQuery( "select * from
AndroidJSonTable where cid="+sid+"", null );
StringBuffer buffer= new StringBuffer();
while (cursor.moveToNext())
{
String cid =cursor.getString(1);
String name =cursor.getString(2);
Examination Paper Analysis and Solution

String mob =cursor.getString(3);


String addr =cursor.getString(4);
String pcode =cursor.getString(5);
buffer.append(cid+ " " + name + " " + mob +" " + addr +" " + pcode +"
\n");
Toast.makeText(getApplicationContext(), buffer,
Toast.LENGTH_LONG).show();
} }); } }

Q1 e State the use of fragments in android App development. (S-23)


2Marks
Ans:
Android Fragment is the part of activity, it is also known as sub-activity.
There can be more than one fragment in an activity.
Fragments represent multiple screen inside one activity.

Q1 g List different types of sensors used in android.


(S-23) 2Marks

Ans:
The android platform supports three broad categories of sensors.
• Motion Sensors These are used to measure acceleration forces and
rotational forces along with three axes.
• Environmental sensors These are used to measure the environmental
changes such as temperature, humidity etc.
• Position sensors These are used to measure the physical position of
device.

Q2 d Explain multimedia framework in android. (S-


23,S-22) 4Marks
Ans:
● The android multimedia system includes multimedia applications,
multimedia frameworks, OpenCore engine and hardware abstract for
audio/video input/output devices. And the goal of the android multimedia
framework is to provide a reliable interface for java services. The
multimedia framework consists of several core dynamic libraries such as
libmediajni, libmedia, libmediaplayservice and so on.
● Java classes call the Native C library Libmedia through Java JNI(Java
Native Interface). Libmedia library communications with Media Server
guard process through Android’s Binder IPc (inter process
communication) mechanism.
● Media Server process creates the corresponding multimedia service
according to the Java multimedia applications.
● The whole communication between Libmedia and Media Server forms
a Client/Server model
Examination Paper Analysis and Solution

Android Multimedia Framework Architecture

● Typical video/audio data stream works in Android as follows.


Particularly, Java applications first set the URI of the media (from file or
network) to PVPlayer through Java framework, JNI and Native C. In this
process, there are no data stream flows.
● Then PVPlayer processes the media data stream with the steps: demux
the media data to separate video/audio data stream, decode video/audio
data, sync video.audio time, send the decoded data out.
● The below is the description of media codec/format, container and
network protocol supported by the Android platform.
1. Container: The audio file format is a file for storing digital audio data
on a system. This data can be manipulated to reduce the size or change
the quality of the audio. It is a kind of container to store audio
information.
2. Audio Format: Any format or codec can be used including the ones
provided by Android or those which are specific devices. However it is
recommended to use the specified file formats as per devices.
3. Network Protocol: Protocols such as RTSP, HTTP,HTTPS are
supported in audio and video playback.

Q3 c Explain text to speech conversion technique in android (S-


23) 4Marks

Ans:
Text to Speech converts the text written on the screen to speech like you
have written “Hello World” on the screen and when you press the button
it will speak “Hello World”. Text-to-speech is commonly used as an
accessibility feature to help people who have trouble reading
Examination Paper Analysis and Solution

on-screen text, but it’s also convenient for those who want to be read too.
This feature has come out to be a very common and useful feature for the
users.
In android, by using TextToSpeech class we can easily convert our text
into voice and it supports different types of speaking languages. We can
choose the speaking language based on our requirements in the android
application.
The android TextToSpeech instance can only be used to synthesize text
once it has completed its initialization so implement TextToSpeech.
OnInitListener to notify the completion of initialization. During the
initialization, we can set the audio pitch rate, audio speed, type of
language to speak, etc. based on our requirements.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_margin="30dp"
tools:context=".MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/Text"
android:layout_marginBottom="20dp"
android:hint="Enter your text"
android:gravity="center"
android:textSize="16dp"/>
<Button
android:layout_width="wrap_content"
android:id="@+id/btnText"
android:layout_height="wrap_content"
android:text="Click"
android:layout_gravity="center"/>
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="70dp"
android:gravity="center_horizontal"
android:text="MobileApplicationDevelopment"
android:textSize="36sp" />
</LinearLayout>
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
Examination Paper Analysis and Solution

import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
EditText Text;
Button btnText;
TextToSpeech textToSpeech;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Text = findViewById(R.id.Text);
btnText = findViewById(R.id.btnText);
textToSpeech = new TextToSpeech(getApplicationContext(), new
TextToSpeech.OnInitListener() {
@Override
public void onInit(int i) {
if(i!=TextToSpeech.ERROR){
// To Choose language of speech
textToSpeech.setLanguage(Locale.UK);
}
}
});
btnText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
textToSpeech.speak(Text.getText().toString(),TextToSpeech.QUEUE_F
LUSH,null);
}
});
}
}

Q4 c Explain property animation method to animate the properties of


view object with example.
(S-23) 4Marks

Ans:

A property animation changes a property's (a field in an object) value


over a specified length of time. To animate something, you specify the
object property that you want to animate, such as an object's position on
the screen, how long you want to animate it for, and what values you
want to animate between.
The property animation system lets you define the following
characteristics of an animation:
Examination Paper Analysis and Solution

Duration: You can specify the duration of an animation. The default


length is 300 ms.
Time interpolation: You can specify how the values for the property are
calculated as a

function of the animation's current elapsed time.


Repeat count and behavior: You can specify whether or not to have an
animation repeat when it reaches the end of a duration and how many
times to repeat the animation. You can also specify whether you want the
animation to play back in reverse. Setting it to reverse plays the
animation forwards then backwards repeatedly, until the number of
repeats is reached.
Animator sets: You can group animations into logical sets that play
together or sequentially or after specified delays.
Frame refresh delay: You can specify how often to refresh frames of your
animation. The default is set to refresh every 10 ms, but the speed in
which your application can refresh frames is ultimately dependent on how
busy the system is overall and how fast the system can service the
underlying timer.
Strings.xml
<resources>
<string name="app_name">Animation</string>
<string name="blink">BLINK</string>
<string name="fade">FADE</string>
<string name="move">MOVE</string>
</resources>
activity_main.xml

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


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageview"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:contentDescription="@string/app_name"
android:src="@drawable/image" />
<LinearLayout
android:id="@+id/linear1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/imageview"
android:layout_marginTop="30dp"
android:orientation="horizontal"
Examination Paper Analysis and Solution

android:weightSum="3">
<Button
android:id="@+id/BTNblink"
style="@style/TextAppearance.AppCompat.Widget.Button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_weight="1"
android:padding="3dp"
android:text="@string/blink"
android:textColor="@color/white" />
<Button
android:id="@+id/BTNfade"
style="@style/TextAppearance.AppCompat.Widget.Button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_weight="1"
android:padding="3dp"
android:text="@string/fade"
android:textColor="@color/white" />
<Button
android:id="@+id/BTNmove"
style="@style/TextAppearance.AppCompat.Widget.Button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_weight="1"
android:padding="3dp"
android:text="@string/move"
android:textColor="@color/white" />
</LinearLayout>
</RelativeLayout>

1) Blink Animation
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha android:fromAlpha="0.0"
android:toAlpha="1.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:duration="500"
android:repeatMode="reverse"
android:repeatCount="infinite"/>
</set>
2) Fade Animation
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_interpolator">
<alpha
Examination Paper Analysis and Solution

android:duration="1000"
android:fromAlpha="0"
android:toAlpha="1" />
<alpha
android:duration="1000"
android:fromAlpha="1"
android:startOffset="2000"
android:toAlpha="0" />
</set>
3) Move Animation
<?xml version="1.0" encoding="utf-8"?>
<set
xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator"
android:fillAfter="true">
<translate
android:fromXDelta="0%p"
android:toXDelta="75%p"
android:duration="700" />
</set>
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
ImageView imageView;
Button blinkBTN, fadeBTN, moveBTN;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageview);
blinkBTN = findViewById(R.id.BTNblink);
fadeBTN = findViewById(R.id.BTNfade);
moveBTN = findViewById(R.id.BTNmove);

blinkBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// To add blink animation
Animation animation =
AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.blink_animation);
imageView.startAnimation(animation);
}
});
Examination Paper Analysis and Solution

fadeBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// To add fade animation
Animation animation =
AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.fade_animation);
imageView.startAnimation(animation);
}
});
moveBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// To add move animation
Animation animation =
AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.move_animation);
imageView.startAnimation(animation);
}
}); } }

Q5 b Develop an android application for taking student feedback with


database connectivity. (S-23) 6Marks

Ans:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Student Feedback Form" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name"
android:id="@+id/editname"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
Examination Paper Analysis and Solution

android:hint="Roll No."

android:id="@+id/editrollno"/> <EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Class" android:id="@+id/editclass"/>
<EditText android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your Feedback" android:lines="3"
android:id="@+id/editfeedback"/> <Button
android:text="Submit Feedback"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:id="@+id/button" /> </LinearLayout>

MapsActivity.java

package com.example.feedback;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
{ SQLiteDatabase sqLiteDatabaseObj;
Button submitBtn;
EditText std_name, std_rollno, std_class,
std_feedback;
String sname, srollno, sclass, sfeedback, sql_query;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); submitBtn =
Examination Paper Analysis and Solution

(Button)findViewById(R.id.button); std_name =
(EditText)findViewById(R.id.editname); std_rollno =
(EditText)findViewById(R.id.editrollno); std_class =
(EditText)findViewById(R.id.editclass); std_class =
(EditText)findViewById(R.id.editfeedback);
submitBtn.setOnClickListener(new
View.OnClickListener() { @Override public void
onClick(View view) { sqLiteDatabaseObj =
openOrCreateDatabase("FeedbaseDataBase",
Context.MODE_PRIVATE, null);
sqLiteDatabaseObj.execSQL("CREATE TABLE IF
NOT EXISTS Student(id INTEGER PRIMARY KEY
AUTOINCREMENT NOT NULL, name VARCHAR,
rollno VARCHAR, class VARCHAR, feedback
VARCHAR);"); sname =
std_name.getText().toString(); srollno =
std_rollno.getText().toString() ; sclass =
std_class.getText().toString(); sfeedback =
std_class.getText().toString(); sql_query = "INSERT
INTO Student (name, rollno, class, feedback)
VALUES('"+sname+"', '"+srollno+"', '"+sclass+"',
'"+sfeedback+"')";
sqLiteDatabaseObj.execSQL(sql_query);
Toast.makeText(getApplicationContext(), "Feedback
Submitted Successfully",
Toast.LENGTH_LONG).show(); } }); } }

Q6 a Design an android application to show the list of paired devices by Bluetooth. (S-
23)6 Marks
Ans:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:transitionGroup="true">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="List all Paired devices"
android:onClick="list"
android:id="@+id/button1"/>
<TextView
android:layout_width="wrap_content"
Examination Paper Analysis and Solution

android:layout_height="wrap_content"
android:text="Paired devices:"
android:id="@+id/textView1"
android:textColor="#ff34ff06"
android:textSize="25dp"
android:layout_below="@+id/button1" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/listView"
android:layout_alignParentBottom="true"
android:layout_below="@+id/textView1" />
</RelativeLayout> AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:androclass="http://schemas.android.com/apk/res/android"
package="com.example.bluetooth"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=" in.org.msbte.bluetooth.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.java
package in.org.msbte.bluetooth;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
Examination Paper Analysis and Solution

import android.widget.Toast;
import java.util.ArrayList;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
Button b1;
private BluetoothAdapter BA;
private Set<BluetoothDevice>pairedDevices;
ListView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button1);
BA = BluetoothAdapter.getDefaultAdapter();
lv = (ListView)findViewById(R.id.listView);
}
public void list(View v){
pairedDevices = BA.getBondedDevices();
ArrayList list = new ArrayList();
for(BluetoothDevice bt : pairedDevices) list.add(bt.getName());
Toast.makeText(getApplicationContext(), "Showing Paired
Devices",Toast.LENGTH_SHORT).show();
final ArrayAdapter adapter = new
ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
}
}

Q1 e State intent. List types of intent. (W-23) 2Marks


Ans:
Intent is the message that is passed between components such as activities. Android uses
Intent for communicating between the components of an Application and also from one
application to another application.
Types:
1. Explicit Intent
2. Implicit Intent

Q1 g Define: i) Fragment ii) Broadcast receiver (W-23)


2Marks

Ans:
Fragment: Fragment is the part of activity, it is also known as sub-activity.
Broadcast receiver: A broadcast receiver is a dormant component of the Android system.
Examination Paper Analysis and Solution

The Broadcast Receiver’s job is to pass a notification to the user, in case a specific event
occurs.

Q3 a Describe service life cycle with its diagram. (W-


23,S-22) 4Marks

Ans:
● A service is an application component which runs without direst interaction with the
user in the background.
● Services are used for repetitive and potentially long running operations, i.e., Internet
downloads, checking for new data, data processing, updating content providers and the
like.
● Service can either be started or bound we just need to call either startService() or
bindService() from any of our android components. Based on how our service was started
it will either be “started” or “bound”

Service Lifecycle
1. Started
a. A service is started when an application component, such as an activity, starts it by
calling startService().
b. Now the service can run in the background indefinitely, even if the component that
started it is destroyed.
2. Bound
a. A service is bound when an application component binds to it by calling bindService().
Examination Paper Analysis and Solution

b. A bound service offers a client-server interface that allows components to interact with
the service, send requests, get results, and even do so across processes with InterProcess
Communication (IPC).
c. Like any other components service also has callback methods. These will be invoked
while the service is running to inform the application of its state. Implementing these in
our custom service would help you in performing the right operation in the right state. •
d. There is always only a single instance of service running in the app. If you are calling
startService() for a single service multiple times in our
application it just invokes the onStartCommand() on that service. Neither is the service
restarted multiple times nor are its multiple instances created
1. onCreate():
This is the first callback which will be invoked when any component starts the service. If
the same service is called again while it is still running this method wont be invoked.
Ideally one time setup and intializing should be done in this callback.
2. onStartCommand() /startSetvice()
This callback is invoked when service is started by any component by calling
startService(). It basically indicates that the service has started and can now run
indefinetly.
3. onBind()
To provide binding for a service, you must implement the onBind() callback method. This
method returns an IBinder object that defines the programming interface that clients can
use to interact with the service.
4. onUnbind()
This is invoked when all the clients are disconnected from the service.
5. onRebind()
This is invoked when new clients are connected to the service. It is called after onRebind
6. onDestroy()
This is a final clean up call from the system. This is invoked just before the service is
being destroyed.

Q4 e Draw and explain activity life cycle. (W-23, W-


22) 4Marks
Ans:
Examination Paper Analysis and Solution

Activities have a predefined life-cycle methods as follows:

onCreate (): Called then the activity is created. Used to initialize the activity, for
example create the user interface.

onStart ():called when activity is becoming visible to the user.

onResume (): Called if the activity get visible again and the user starts interacting
with the activity again. Used to initialize fields, register listeners, bind
to services, etc.

onPause (): Called once another activity gets into the foreground. Always called
before the activity is not visible anymore. Used to release resources or
save application data. For example you unregister listeners, intent
receivers, unbind from services or remove system service listeners.

onStop (): Called once the activity is no longer visible. Time or CPU intensive
shutdown
operations, such as writing information to a database should be down in the onStop()
method. This method is guaranteed to be called as
of API 11.

onDestroy (): called before the activity is destroyed.


Examination Paper Analysis and Solution

Q5 c Develop an application to convert thanks" text to speech as given in the following


GUI.

(W-23) 6Marks
Ans:

Code of activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
Examination Paper Analysis and Solution

android:paddingBottom="@dimen/activity_vertical_margin
"
tools:context=".MainActivity"
android:transitionGroup="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android Text to Speech(TTS) Demo"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_below="@+id/textView"
android:layout_marginTop="46dp"
android:text="thanks"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textColor="#ff7aff10"
android:textColorHint="#ffff23d1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CLICK TO CONVERT TEXT TO SPEECH"
android:id="@+id/button"
android:layout_below="@+id/editText"
android:layout_centerHorizontal="true"
android:layout_marginTop="46dp"
android:textSize="15dp" />
</RelativeLayout>

Code of toolbar_title_layout.xml file


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/androi
d"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center"
<TextView
android:padding="4dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextToSpeechDemo"
Examination Paper Analysis and Solution

android:gravity="center"
android:textSize="16sp"
android:textStyle="bold"
android:textColor="@android:color/white"/>
</LinearLayout>

Code of MainActivity.java.
package com.example.texttospeech.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.Locale;
import android.widget.Toast;
public class MainActivity extends Activity { TextToSpeech
t1; EditText ed1; Button b1; @Override protected void
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayOptions(ActionBar.DISP
LAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.toolbar_tit
le_layout); setContentView(R.layout.activity_main);
ed1=(EditText)findViewById(R.id.editText);
b1=(Button)findViewById(R.id.button); t1=new
TextToSpeech(getApplicationContext(), new
TextToSpeech.OnInitListener() { @Override public void
onInit(int status) {

if(status != TextToSpeech.ERROR) {
t1.setLanguage(Locale.UK); } } });
b1.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) { String toSpeak =
ed1.getText().toString();
Toast.makeText(getApplicationContext(),
toSpeak,Toast.LENGTH_SHORT).show();
t1.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null); }
}); } public void onPause(){ if(t1 !=null){ t1.stop();
t1.shutdown(); } super.onPause(); } }

Q6 a Develop an application to update a record of an employee whose emp.id is ‘E101’


in SQlite database. Change employee name from “POR" to “XYZ". Also display the
updated record (Write .java and .xml files).

(W-23) 6Marks

Ans:
Examination Paper Analysis and Solution

activity_update_emp.xml file

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


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<!--Edit text to enter employee name-->
<EditText
android:id="@+id/idEdtEmpName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Enter Employee Name" />
<!--edit text for employee salary-->
<EditText
android:id="@+id/idEdtEmpSalary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Enter Employee Salary" />
<!--button for adding new employee-->
<Button
android:id="@+id/idBtnAddCourse"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Add Employee"
android:textAllCaps="false" />
</LinearLayout>

DBHandler.java file

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHandler extends SQLiteOpenHelper {
// creating a constant variables for our database.
// below variable is for our database name.
private static final String DB_NAME = "empdb";
// below int is our database version
private static final int DB_VERSION = 1;
// below variable is for our table name.
private static final String TABLE_NAME = "myemp";
// below variable is for our id column.
Examination Paper Analysis and Solution

private static final String ID_COL = "id";


// below variable is for our course name column
private static final String NAME_COL = "emp_name";
// below variable is for our employee salary column.
private static final String TRACKS_COL = "emp_salary";
// creating a constructor for our database handler.
public DBHandler(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
// below method is for creating a database by running a sqlite query
@Override
public void onCreate(SQLiteDatabase db) {
// on below line we are creating
// an sqlite query and we are
// setting our column names
// along with their data types.
String query = "CREATE TABLE " + TABLE_NAME + " ("
+ ID_COL + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ NAME_COL + " TEXT,"
+ SALARY_COL + " TEXT)";
// at last we are calling a exec sql
// method to execute above sql query
db.execSQL(query);
}
// this method is use to add new EMPLOYEE to our sqlite database.
public void addNewCourse(String empName, String empSalary) {
// on below line we are creating a variable for
Examination Paper Analysis and Solution

// our sqlite database and calling writable method


// as we are writing data in our database.
SQLiteDatabase db = this.getWritableDatabase();
// on below line we are creating a
// variable for content values.
ContentValues values = new ContentValues();
// on below line we are passing all values
// along with its key and value pair.
values.put(NAME_COL, empName);
values.put(TRACKS_COL, empSalary);
// after adding all values we are passing
// content values to our table.
db.insert(TABLE_NAME, null, values);
// at last we are closing our
// database after adding database.
db.close();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// this method is called to check if the table exists already.
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}

empRVAdapter.java file
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
// creating variables for our edittext, button and dbhandler
private EditText empNameEdt, empSalaryEdt;
private Button addempBtn;
private DBHandler dbHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initializing all our variables.
empNameEdt = findViewById(R.id.idEdtempName);
empSalaryEdt = findViewById(R.id.idEdtempSalary);
addempBtn = findViewById(R.id.idBtnAddemp);
// creating a new dbhandler class
// and passing our context to it.
dbHandler = new DBHandler(MainActivity.this);
// below line is to add on click listener for our add emp button.
addCourseBtn.setOnClickListener(new View.OnClickListener() {
Examination Paper Analysis and Solution

@Override
public void onClick(View v) {

below line is to get data from all edit text fields.


String empName = empNameEdt.getText().toString();
String empSalary = empSalaryEdt.getText().toString();
// validating if the text fields are empty or not.
if (empName.isEmpty() && empSalary.isEmpty() &&) {
Toast.makeText(MainActivity.this, "Please enter all the data..",
Toast.LENGTH_SHORT).show();
return;
}
// on below line we are calling a method to add new
// employee to sqlite data and pass all our values to it.
dbHandler.addNewemp(empName, empSalary);
// after adding the data we are displaying a toast message.
Toast.makeText(MainActivity.this, "Employee has been added.",
Toast.LENGTH_SHORT).show();
empNameEdt.setText("");
empSalaryEdt.setText("");
}
});
}
}
Update employee record java file:
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
Examination Paper Analysis and Solution

import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
public class UpdateCourseActivity extends
AppCompatActivity {
// variables for our edit text, button, strings and dbhandler class.
private EditText empNameEdt, empSalaryEdt;
private Button updateempBtn;
private DBHandler dbHandler;
String empName, empSalary;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_emp);
// initializing all our variables.
empNameEdt = findViewById(R.id.idEdtempName);
empSalaryEdt = findViewById(R.id.idEdtempSalary);
updateempBtn = findViewById(R.id.idBtnUpdateemp);
// on below line we are initializing our dbhandler class.
dbHandler = new DBHandler(UpdateempActivity.this);
// on below lines we are getting data which
// we passed in our adapter class.
empName = getIntent().getStringExtra("emp_name");
empSalary = getIntent().getStringExtra("emp_salary");
// setting data to edit text
// of our update activity.
empNameEdt.setText(empName);
Examination Paper Analysis and Solution

empSalaryEdt.setText(empSalary);
// adding on click listener to our update course button.
updateempBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// inside this method we are calling an update employee
// method and passing all our edit text values.
dbHandler.updateemp(empName, empNameEdt.getText().toString(),
empSalaryEdt.getText().toString());
// displaying a toast message that our employee database has been updated.
Toast.makeText(UpdateempActivity.this, "Employee Record Updated..",
Toast.LENGTH_SHORT).show();
// launching our main activity.
Intent i = new Intent(UpdateempActivity.this, MainActivity.class);
startActivity(i);
}
});
}
}

unit 6
Examination Paper Analysis and Solution

Q1 Define Geocoding and Reverse Geocoding. (W-23) 2 Marks

Ans: Geocoding :
Geocoding is the process of transforming a street address or other description of a
location into a (latitude, longitude) coordinate.
Reverse Geocoding :
Reverse geocoding is the process of transforming a (latitude, longitude) coordinate into a
(partial) address.

Q2 Develop a program to add "Hello World" marker at (10 ,10) co-ordinates. Write only
.java file. (W-23) 4 Marks

Ans: Activity_maps.xml
package com.example.googlemap;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback
{
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get
notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager() .findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap)
{
mMap = googleMap; // Add a marker in Sydney and move the camera
LatLng hello = new LatLng(10,10);
mMap.addMarker(new MarkerOptions().position(hello).title("Marker Hello World"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mumbai,10F));
}
}
Examination Paper Analysis and Solution

Q3 Elaborate Android Security Model. (W-23) 4 Marks

Ans: Android security model

• Android is a multi-process system, in which each application (and parts of the system)
runs in its own process.

• Most security between applications and the system is enforced at the process level
through standard Linux facilities, such as user and group IDs that are assigned to
applications.

• Additional finer-grained security features are provided through a “permission”


mechanism that enforces restrictions on the specific operations that a particular
process can perform, and per-URI permissions for granting ad-hoc access to specific
pieces of data.

• The Android security model is primarily based on a sandbox and permission


mechanism. Each application is running in a specific Dalvik virtual machine with a
unique user ID assigned to it, which means the application code runs in isolation from
the code of all others applications. As a consequence, one application has not granted
access to other applications’ files.

• Android application has been signed with a certificate with a private key Know the
owner of the application is unique.

• This allows the author of The application will be identified if needed.

• When an application is installed in The phone is assigned a user ID, thus avoiding it
from affecting it Other applications by creating a sandbox for it. This user ID is
permanent on which devices and applications with the same user ID are allowed to
run in a single process. This is a way to ensure that a malicious application has Can
not access / compromise the data of the genuine application.

• It is mandatory for an application to list all the resources it will Access during
installation.

• The purpose of a permission is to protect the privacy of an Android user. Android


apps must request permission to access sensitive user data (such as contacts and
SMS), as well as certain system features (such as camera and internet).

• Permissions are divided into several protection levels. The protection level affects
whether runtime permission requests are required.
Examination Paper Analysis and Solution

Android introduced shared user ID & permission to allow application components talk

to each other & enable application to access to critical system in Android devices.

Q4 Develop an application to send and receive SMS. (Write only Java and permission
tag in manifest file) (W-23) 4 Marks

Ans:

Permissions and <receiver> tag required in AndroidManifest.xml

<uses-permission android:name="android.permission.RECEIVE_SMS" />


<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.WRITE_SMS"/>
<receiver
android:name=".SmsReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>

MainActivity.java
Examination Paper Analysis and Solution

(Cosidering appropriate layout file with 2 edit text boxes namely for phone number,
message and a button for sending sms)

package com.example.testreceivesms;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity


{
SmsReceiver sms= new SmsReceiver();
EditText et1,et2;
Button b1;
@Override
protected void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1=findViewById(R.id.etPhno);
et2=findViewById(R.id.etmsg);
b1=findViewById(R.id.btnSms);
if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.SEND_
SMS)!=
PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(MainActivity.this,new
String[]{Manifest.permission.SEND_SMS},100);
}
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
String phno= et1.getText().toString();
String msg=et2.getText().toString();
SmsManager smsManager= SmsManager.getDefault();
smsManager.sendTextMessage(phno,null,msg,null,null);
Toast.makeText(MainActivity.this,"Sms sent successfully",
Toast.LENGTH_LONG).show();
}
catch(Exception e)
Examination Paper Analysis and Solution

{
Toast.makeText(MainActivity.this,"Sms failed to send... try again",
Toast.LENGTH_LONG).show();
}
}
});
}
@Override
protected void onStart() {
super.onStart();
IntentFilter filter=new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(sms,filter);
}
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(sms);
}
}
SmsReceiver.java
package com.example.testreceivesms;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class SmsReceiver extends BroadcastReceiver


{
SmsReceiver(){}
@Override
public void onReceive(Context context, Intent intent)
{
Bundle bundle = intent.getExtras();
if (bundle != null) {
// Retrieve the SMS Messages received
Object[] sms = (Object[]) bundle.get("pdus");
// For every SMS message received
for (int i=0; i < sms.length; i++) {
// Convert Object array
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);
String phone = smsMessage.getOriginatingAddress();
String message = smsMessage.getMessageBody().toString();
Toast.makeText(context, “Received from “+ phone + ": " + message,
Toast.LENGTH_SHORT).show();
}
}
}
}
Examination Paper Analysis and Solution

Q5 Develop an application to display a Google Map. (Write JAVA & Manifest file)

(W-23) 6 Marks

Ans: AndroidManifest.xml code:

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="example.com.mapexample">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="@string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

code of MapsActivity.java :
package example.com.mapexample;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback


{
private GoogleMap mMap;
Examination Paper Analysis and Solution

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);

// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap)
{
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}

Q6 i) Describe all steps in application deployment on google play store. (S-23 4 Marks)
(S-22 4 Marks)

ii) Write steps for customized permissions. (W-23 6 Marks)

Ans:

i. Step-by-Step Process to Upload App To Google Play Store

Step 1: Create a Developer Account


• Before you can publish any app on Google Play, you need to create a Developer
Account. You can easily sign up for one using your existing Google Account.
• You’ll need to pay a one-time registration fee of $25 using your international
credit or debit card. It can take up to 48 hours for your registration to be fully
processed.

Step 2: Plan to Sell? Link Your Merchant Account


• If you want to publish a paid app or plan to sell in-app purchases, you need to
create a payments center profile, i.e. a merchant account.
• A merchant account will let you manage your app sales and monthly payouts,
as well as analyze your sales reports right in your Play Console.

Step 3: Create an App


• Now you have create an application by clicking on 'Create Application'. Here
you have to select your app’s default language from the drop-down menu and
Examination Paper Analysis and Solution

then type in a title for your app. The title of your app will show on Google Play
after you’ve published.

Step 4: Prepare Store Listing


• Before you can publish your app, you need to prepare its store listing. These are
all the details that will show up to customers on your app’s listing on Google
Play. You not necessarily complete it at once , you can always save a draft and
revisit it later when you’re ready to publish.
• The information required for your store listing is divided into several categories
such as Product Details containing title, short and full description of the app,
Your app’s title and description should be written with a great user experience in
mind. Use the right keywords, but don’t overdo it. Make sure your app doesn’t
come across as spam-y or promotional, or it will risk getting suspended on the
Play Store.
• Graphic Assets where you can add screenshots, images, videos, promotional
graphics, and icons that showcase your app’s features and functionality.
• Languages & Translations, Categorization where in category can be selected to
which your app belong to. Contact Details , Privacy Policy for apps that request
access to sensitive user data or permissions, you need to enter a comprehensive
privacy policy that effectively discloses how your app collects, uses, and shares
that data.

Step 5: Upload APK to an App Release


• Finally upload your app, by uploading APK file. Before you upload APK, you
need to create an app release. You need to select the type of release you want to
upload your first app version to.
• You can choose between an internal test, a closed test, an open test, and a
production release. The first three releases allow you to test out your app
among a select group of users before you make it go live for everyone to access.
• This is a safer option because you can analyze the test results and optimize or fix
your app accordingly if you need to before rolling it out to all users.
• Once you create a production release, your uploaded app version will become
accessible to everyone in the countries you choose to distribute it in and click on
‘Create release.’

Step 6: Provide an Appropriate Content Rating


• If you don’t assign a rating to your app, it will be listed as ‘Unrated’. Apps that
are ‘Unrated’ may get removed from Google Play.
• To rate your app, you need to fill out a content rating questionnaire An
appropriate content rating will also help you get to the right audience, which will
eventually improve your engagement rates.

Step 7: Set Up Pricing & Distribution


Examination Paper Analysis and Solution

• Before you can fill out the details required in this step, you need to determine
your app’s monetization strategy. Once you know how your app is going to
make money, you can go ahead and set up your app as free or paid.
• You can always change your app from paid to free later, but you cannot change
a free app to paid. For that, you’ll need to create a new app and set its price.

Step 8: Rollout Release to Publish Your App


• The final step involves reviewing and rolling out your release after making sure
you’ve taken care of everything else.
• Before you review and rollout your release, make sure the store listing, content
rating, and pricing and distribution sections of your app each have a green check
mark next to them.
• Once you’re sure about the correctness of the details, select your app and
navigate to ‘Release management’ – ‘App releases.’
• You can always opt for reviews by clicking on ‘Review’ to be taken to the
‘Review and rollout release’ screen. Here, you can see if there are any issues or
warnings you might have missed out on.
• Finally, select ‘Confirm rollout.’ This will also publish your app to all users in
your target countries on Google Play.

ii. Write steps for customized permissions.

By defining custom permissions, an app can share its resources and capabilities with other
apps.
App signing
⚫ All APKs must be signed with a certificate whose private key is held by their
developer. This certificate identifies the author of the app.
⚫ The certificate does not need to be signed by a certificate authority; it is perfectly
allowable, and typical, for Android apps to use self-signed certificates.
⚫ The purpose of certificates in Android is to distinguish app authors.
User IDs and file access
⚫ At install time, Android gives each package a distinct Linux user ID.
⚫ The identity remains constant for the duration of the package's life on that device.
⚫ On a different device, the same package may have a different UID; what matters is
that each package has a distinct UID on a given device.
Defining and enforcing permissions
⚫ To enforce your own permissions, you must first declare them in
your AndroidManifest.xml using one or more <permission> elements.
Examination Paper Analysis and Solution

⚫ For example, an app that wants to control who can start one of its activities could
declare a permission for this operation as follows:
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp" >

<permission
android:name="com.example.myapp.permission.DEADLY_ACTIVITY"
android:label="@string/permlab_deadlyActivity"
android:description="@string/permdesc_deadlyActivity"
android:permissionGroup="android.permission-group.COST_MONEY"
android:protectionLevel="dangerous" />
...
</manifest>

Q7 Define SMS service in android application development. (S-23 2 Marks)


Ans:
• In Android, you can use SmsManager API or devices Built-in SMS application
to send SMS's
• Android SMS is stored in PDU (protocol description unit) format
• SmsManager class takes care of sending the SMS message.
• We just need to get an instance of it and send the SMS message.
• We need to add permission to SEND_SMS in the Android manifest file.

SmsManager smsManager = SmsManager.getDefault();


smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);

Q8 Describe the process of getting the map API key. (S-23 4 Marks)
Ans:
The API key is a unique identifier that authenticates requests associated with your project
for usage and billing purposes. You must have at least one API key associated with your
project.

1. Browse the site on your browser. https://console. developers. google.com/project


2. Login with your google account.
3. Create a new project by clicking on Create Project option.
4. Add your project name and organization name in the fields present on the screen.
5. Now click on APIs and Services.
6. Enable APIs and services.
7. Select Google maps Android API
8. To create an API key for Maps click on Create credentials option and then select the
API key option
Examination Paper Analysis and Solution

Click on the API key option to generate your API key. After clicking on this option your
API key will be generated

Q9 Describe steps for deploying android application on Google Play Store (S-23 4 Marks)
Ans: Refer the answer of Q6 i

Q10 Describe permissions required for android application development. (S-23 4 Marks)
Ans:

Types of permissions

1. Install-time permissions
Install-time permissions give your app limited access to restricted data, and they allow
your app to perform restricted actions that minimally affect the system or other apps.
When you declare install-time permissions in your app, the system automatically grants
your app the permissions when the user installs your app.

An app store presents an install-time permission notice to the user when they view an
app's details page .

Android includes several sub-types of install-time permissions,

Normal permissions and Signature permissions.

• Normal permissions

These permissions allow access to data and actions that extend beyond your app's
sandbox. However, the data and actions present very little risk to the user's privacy, and
the operation of other apps.
Examination Paper Analysis and Solution

• Signature permissions

If the app declares a signature permission that another app has defined, and if the two
apps are signed by the same certificate, then the system grants the permission to the first
app at install time. Otherwise, that first app cannot be granted the permission.

2. Runtime permissions
Runtime permissions, also known as dangerous permissions, give your app additional
access to restricted data, and they allow your app to perform restricted actions that more
substantially affect the system and other apps.

Many runtime permissions access private user data, a special type of restricted data that
includes potentially sensitive information. Examples of private user data include
location and contact information.

The system assigns the "dangerous" protection level to runtime permissions.

3. Special permissions
Special permissions correspond to particular app operations. Only the platform and
OEMs can define special permissions. Additionally, the platform and OEMs usually
define special permissions when they want to protect access to particularly powerful
actions, such as drawing over other apps.

The Special app access page in system settings contains a set of user-toggleable
operations. Many of these operations are implemented as special permissions.

Declaring and Using Permissions


⚫ The purpose of a permission is to protect the privacy of an Android user. Android
apps must request permission to access sensitive user data (such as contacts and
SMS), as well as certain system features (such as camera and internet).
⚫ Depending on the feature, the system might grant the permission automatically or
might prompt the user to approve the request.

Permission Approval
⚫ An app must publicize the permissions it requires by including <uses-
permission> tags in the app manifest.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.snazzyapp">

<uses-permission android:name="android.permission.SEND_SMS"/>

<application ...>
...
Examination Paper Analysis and Solution

</application>
</manifest>

If your app lists normal permissions in its manifest the system automatically grants
those permissions to your app.

If your app lists dangerous permissions in its manifest such as


the SEND_SMS permission above, the user must explicitly agree to grant those
permissions.

Request prompts for dangerous permissions


⚫ Only dangerous permissions require user agreement. The way Android asks the
user to grant dangerous permissions depends on the version of Android running on
the user's device, and the system version targeted by your app.
1. Runtime requests
2. Install-time requests

Request prompts to access sensitive user information

⚫ Some apps depend on access to sensitive user information related to call logs and
SMS messages.
⚫ If you want to request the permissions specific to call logs and SMS messages and
publish your app to the Play Store, you must prompt the user to set your app as
the default handler for a core system function before requesting these runtime
permissions.

Permissions for optional hardware features

Access to some hardware features (such as Bluetooth or the camera) require an app
permission.
<uses-feature android:name="android.hardware.camera" android:required="false" />

Q11 Develop an android application to show current location of an user's car (S-23 4
Marks)
activity_maps.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.com.mapexample.MapsActivity" />
MapsActivity.java
import android.os.Build;
import android.support.v4.app.FragmentActivity;
Examination Paper Analysis and Solution

import android.os.Bundle;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.location.LocationServices;
import android.location.Location;
import android.Manifest;
import android.content.pm.PackageManager;
import android.support.v4.content.ContextCompat;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
LocationListener,GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener{
private GoogleMap mMap;
Location mLastLocation;
Marker mCurrLocationMarker;
GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
Examination Paper Analysis and Solution

}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
mGoogleApiClient.connect();
}
@Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_A
CCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.
HUE_GREEN));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Examination Paper Analysis and Solution

}
}
Add the following user-permission in AndroidManifest.xml file.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />

Q12 Explain Geocoding and Reverse Geocoding with suitable example. (S-23 6 Marks)

Geocoding is the process of transforming a street address or other description of a location


into a (latitude, longitude) coordinate.
Reverse geocoding is the process of transforming a (latitude, longitude) coordinate into a
(partial) address.
The amount of detail in a reverse geocoded location description may vary, for example
one might contain the full street address of the closest building, while another might
contain only a city name and postal code.
The Geocoder class is used for handling geocoding and reverse geocoding.
activity_maps.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.com.mapexample.MapsActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:layout_width="248dp"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:hint="Search Location" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="searchLocation"
android:text="Search" />
</LinearLayout>
</fragment>
AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
Examination Paper Analysis and Solution

MapsActivity.java
package example.com.mapexample;
import android.location.Address;
import android.location.Geocoder;
import android.os.Build;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.location.LocationServices;
import android.location.Location;
import android.Manifest;
import android.content.pm.PackageManager;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import java.io.IOException;
import java.util.List;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
LocationListener,GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener{
private GoogleMap mMap;
Location mLastLocation;
Marker mCurrLocationMarker;
GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Examination Paper Analysis and Solution

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {


if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
mGoogleApiClient.connect();
}
@Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_A
CCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.
HUE_GREEN));
Examination Paper Analysis and Solution

mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public void searchLocation(View view) {
EditText locationSearch = (EditText) findViewById(R.id.editText);
String location = locationSearch.getText().toString();
List<Address> addressList = null;
if (location != null || !location.equals("")) {
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title(location));
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
Toast.makeText(getApplicationContext(),address.getLatitude()+"
"+address.getLongitude(),Toast.LENGTH_LONG).show();
}
}
}

Q13 List and elaborate steps to deploy an Android application on Google play store.
Refer Q6 i

Q14State and elaborate the syntax of required class and methods for Geocoding.
Geocoder:
A class for handling geocoding and reverse geocoding.
Geocoding is the process of transforming a street address or other description of a location
into a (latitude, longitude) coordinate.
Reverse geocoding is the process of transforming a (latitude, longitude) coordinate into a
(partial) address. The amount of detail in a reverse geocoded location description may
vary, for example one might contain the full street address of the closest building, while
another might contain only a city name and postal code.
The Geocoder class requires a backend service that is not included in the core android
framework.
The Geocoder query methods will return an empty list if there no backend service in the
platform. Use the isPresent() method to determine whether a Geocoder implementation
exists.
Examination Paper Analysis and Solution

Syntax
Geocoder (Context context)

Constructs a Geocoder localized for the default locale.

Geocoder(Context context, Locale locale)

Constructs a Geocoder localized for the given locale.


Methods with Syntax
a. getFromLocation

Syntax
public List<Address> getFromLocation (double latitude, double longitude, int
maxResults)
public void getFromLocation (double latitude, double longitude, int maxResults,
Geocoder.GeocodeListener listener)

This method returns an array of Addresses that attempt to describe the area immediately
surrounding the given latitude and longitude. The returned addresses should be
localized for the locale provided to this class's constructor.

b. getFromLocationName
Syntax :
● public List<Address> getFromLocationName (String locationName, int maxResults,
double lowerLeftLatitude, double lowerLeftLongitude, double upperRightLatitude,
double upperRightLongitude)
● public void getFromLocationName (String locationName, int maxResults, double
lowerLeftLatitude, double lowerLeftLongitude, double upperRightLatitude, double
upperRightLongitude, Geocoder.GeocodeListener listener)
● public void getFromLocationName (String locationName, int maxResults,
Geocoder.GeocodeListener listener)
● public List<Address> getFromLocationName (String locationName, int
maxResults)

c. isPresent

Returns an array of Addresses that attempt to describe the named location, which may be
a place name such as "Dalvik, Iceland", an address such as "1600 Amphitheatre Parkway,
Mountain View, CA", an airport code such as "SFO", and so forth. The returned addresses
should be localized for the locale provided to this class's constructor.
Syntax
public static boolean isPresent ()
Returns true if there is a geocoder implementation present that may return results. If true,
there is still no guarantee that any individual geocoding attempt will succeed.

Q15 Discuss developer console with at least four features


Examination Paper Analysis and Solution

Google Play Developer Console is the platform that Google provides for Google Play and
Android developers to publish their apps.
● The Google Play Developer console allows app developers and marketers to better
understand how their apps are performing in terms of growth, technical performance such as
crashes or display issues, and financials.
● The console offers acquisition reports and detailed analysis which can help app devs find
out how well an app is really performing.
● The platform is important as it provides developers with access to first party data
(trustworthy information collected about an app’s audience that comes straight from Google
Play) that highlights the real performance of an app.
● It shows the number of impressions an app listing receives and the number of Installs an
app receives from different sources over time.

Q16 Write a program to demonstrate declaring and using permissions with any relevant
example.
Permission declaring :
The permissions are declared in AndroidManifest.xml file under Manifest folder.
Permission can be set by <uses-permission> tag in AndroidManifest.xml.
Example:
Following example is to send SMS.
AndroidManifest.xml
<uses-permission android:name="android.permission.SEND_SMS"/>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="81dp"
android:layout_height="41dp"
android:layout_marginEnd="268dp"
android:layout_marginBottom="576dp"
android:text="To :"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
<TextView
android:id="@+id/textView2"
android:layout_width="70dp"
android:layout_height="43dp"
android:layout_marginEnd="276dp"
android:layout_marginBottom="512dp"
android:text="Sms Text"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<EditText
android:id="@+id/etPhno"
Examination Paper Analysis and Solution

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="40dp"
android:layout_marginBottom="572dp"
android:ems="10"
android:inputType="textPersonName"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<EditText
android:id="@+id/etmsg"
android:layout_width="193dp"
android:layout_height="51dp"
android:layout_marginEnd="56dp"
android:layout_marginBottom="504dp"
android:inputType="textPersonName"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
tools:ignore="SpeakableTextPresentCheck" />
<Button
android:id="@+id/btnSms"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="156dp"
android:layout_marginBottom="400dp"
android:text="SEND SMS"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package com.example.testreceivesms;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText et1,et2;
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1=findViewById(R.id.etPhno);
Examination Paper Analysis and Solution

et2=findViewById(R.id.etmsg);
b1=findViewById(R.id.btnSms);
if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.SE
ND_SMS)!=
PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(MainActivity.this,new
String[]{Manifest.permission.SEND_SMS},100);
}
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
String phno= et1.getText().toString();
String msg=et2.getText().toString();
SmsManager smsManager= SmsManager.getDefault();
smsManager.sendTextMessage(phno,null,msg,null,null);
Toast.makeText(MainActivity.this,"Sms sent successfully",
Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
Toast.makeText(MainActivity.this,"Sms failed to send... try again",
Toast.LENGTH_LONG).show();
}
}
});
}
}

Q17 Develop and application to send and receive SMS (Design minimal UI as per your
choice. Write XML, java and manifest file)
Refer Q4 answer

Q18 Develop an application to display Google map with user's current location.
act ivity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/google_map"
android:name="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
MainActivity.Java
Examination Paper Analysis and Solution

package com.example.location;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;

public class MainActivity extends FragmentActivity implements OnMapReadyCallback


{
Location currentlocation;
FusedLocationProviderClient fusedLocationProviderClient;
private static final int REQUEST_CODE = 101;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fusedLocationProviderClient =
LocationServices.getFusedLocationProviderClient(this);
fetchLastLocation();
}
private void fetchLastLocation() {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,new
String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_CODE);
return;
}
Task<Location> task = fusedLocationProviderClient.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if(location!=null)
Examination Paper Analysis and Solution

{
currentlocation=location;
Toast.makeText(getApplicationContext(),currentlocation.getLatitude()+""+curre
ntlocation.getLongitude(), Toast.LENGTH_SHORT).show();
SupportMapFragment supportMapFragment =
(SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.g
oogle_map);
supportMapFragment.getMapAsync(MainActivity.this);
}
}
});
}

Q19 Name any four methods to get location data in android. (W-22 2 Marks)
float distanceTo(Location dest)
float getAccuracy()
float getBearing()
double getAltitude()
double getLatitude()
float getSpeed()
boolean hasAccuracy()
boolean hasAltitude()
boolean hasBearing()
boolean hasBearing()
boolean hasSpeed()
void reset()
void setAccuracy(float accuracy)
void setAltitude(double altitude)

Q20 Elaborate the need of permissions in Android. Explain the permissions to set system
functionalities like SEND-SMS, bluetooth. (W-22 4 Marks)
The purpose of a permission is to protect the privacy of an Android user. Android apps must
request permission to access sensitive user data (such as contacts and SMS), as well as certain
system features (such as camera and internet). Depending on the feature, the system might
grant the permission automatically or might prompt the user to approve the request.
● android. permission. SEND_SMS

Allows the app to send SMS messages. This may result in unexpected charges. Malicious
apps may cost you money by sending messages without your confirmation.
Following is the code snippet to set SEND_SMS permissions in manifest file.
<uses-permission android: name="android.permission.SEND_SMS"/>
● android. permission. BLUETOOTH

You need to provide following permissions in AndroidManifest.xml file.


<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

Q21 Explain the steps to deploy app on Google Play Store. (W-22 4 Marks)
Refer Q6 i
Q22 Explain the procedure of Geo-coding and reverse Geo-coding. (W-22 4 Marks)
Examination Paper Analysis and Solution

Geo-Coding:
• If we know the latitude and longitude of a location, we can find out its address using a
process known as Geocoding. Google Maps in Android supports this via the Geocoder class.
• The following code shows how we can find out the address of a location we have just
touched using the getFromLocation() method:
classMapOverlay extends com.google.android.maps.Overlay
{
@Override
publicboolean draw(Canvas canvas, MapViewmapView,
boolean shadow, long when)
{
//...
}
@Override
publicbooleanonTouchEvent(MotionEvent event, MapViewmapView)
{
//---when user lifts his finger---
if (event.getAction() == 1) {
GeoPoint p = mapView.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
Geocoder geoCoder = new Geocoder(
getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
p.getLatitudeE6() / 1E6,
p.getLongitudeE6() / 1E6, 1);
String add = "";
if (addresses.size() > 0)
{
for (inti=0; i<addresses.get(0).getMaxAddressLineIndex();
i++)
add += addresses.get(0).getAddressLine(i) + "n";
}
Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT).show();
}
catch (IOException e) {
e.printStackTrace();
}
return true;
}
else
return false;
}
}
Reverse-geocoding:
If we know the address of a location but want to know its latitude and longitude, we can do
so via reverse-Geocoding. Again, we can use the Geocoder class for this purpose.
• The following code shows how we can find the exact location of the Empire State Building
by using the getFromLocationName() method:
Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
try {
Examination Paper Analysis and Solution

List<Address> addresses = geoCoder.getFromLocationName(


"empire state building", 5);
String add = "";
if (addresses.size() > 0) {
p = new GeoPoint(
(int) (addresses.get(0).getLatitude() * 1E6),
(int) (addresses.get(0).getLongitude() * 1E6));
mc.animateTo(p);
mapView.invalidate();
}
} catch (IOException e) {
e.printStackTrace();
}
Once. the location is found, the above code navigates the map to the location.

Q23 Develop a program to send and receive an Email. (W-22 6 Marks)


Program to send Email
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_marginTop="18dp"
android:layout_marginRight="22dp" />
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_alignLeft="@+id/editText1"
android:layout_marginTop="20dp" />
<EditText
android:id="@+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText2"
android:layout_alignLeft="@+id/editText2"
android:layout_marginTop="30dp" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText1"
Examination Paper Analysis and Solution

android:layout_alignBottom="@+id/editText1"
android:layout_alignParentLeft="true"
android:text="Send To:"
android:textColor="#0F9D58" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText2"
android:layout_alignBottom="@+id/editText2"
android:layout_alignParentLeft="true"
android:text="Email Subject:"
android:textColor="#0F9D58" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText3"
android:layout_alignBottom="@+id/editText3"
android:text="Email Body:"
android:textColor="#0F9D58" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText3"
android:layout_alignLeft="@+id/editText3"
android:layout_marginLeft="76dp"
android:layout_marginTop="20dp"
android:text="Send email!!" />
</RelativeLayout>
MainActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
// define objects for edit text and button
Button button;
EditText sendto, subject, body;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting instance of edittext and button
sendto = findViewById(R.id.editText1);
subject = findViewById(R.id.editText2);
body = findViewById(R.id.editText3);
button = findViewById(R.id.button);
// attach setOnClickListener to button with Intent object define in it
button.setOnClickListener(view -> {
Examination Paper Analysis and Solution

String emailsend = sendto.getText().toString();


String emailsubject = subject.getText().toString();
String emailbody = body.getText().toString();
// define Intent object with action attribute as ACTION_SEND
Intent intent = new Intent(Intent.ACTION_SEND);
// add three fields to intent using putExtra function
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{emailsend});
intent.putExtra(Intent.EXTRA_SUBJECT, emailsubject);
intent.putExtra(Intent.EXTRA_TEXT, emailbody);
// set type of intent
intent.setType("message/rfc822");
// startActivity with intent with chooser as Email client using createChooser function
startActivity(Intent.createChooser(intent, "Choose an Email client :"));
});
}
}
Program to receive Email
(Note: Receiving email is not the service of Android OS, instead it uses some third party
applicaton like Gmail, so instead of receiving email in android app, a code which
broadcasts message if email comes using broadcast receiver or any relevant logic can be
considered.)
MainActivity.java
package com.example.myemailprog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.IntentFilter;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
GmailReceiver gml;
IntentFilter intf;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gml = new GmailReceiver();
intf = new IntentFilter("android.intent.action.VIEW");
}
@Override
protected void onResume() {
super.onResume();
registerReceiver(gml, intf);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(gml);
}
}
Gmailrerciever..java
package com.example.myemailprog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
Examination Paper Analysis and Solution

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.widget.Toast;
public class GmailReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context, "Email Received", Toast.LENGTH_LONG).show();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myemailprog">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MyEmailProg">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="GmailReceiver"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.PROVIDER_CHANGED"
android:priority="-10">
</action>
<action android:name="android.intent.action.VIEW" />
<data android:scheme="content" android:host="gmail-ls"
android:pathPattern="/unread/.*">
</data>
</intent-filter>
</receiver>
</application>
</manifest>

Q24 Write a program to find the direction from user's current location to MSBTE, Bandra.
(Write only Java and manitest file). (W-22 6 Marks)

AndroidManifest.xml
Examination Paper Analysis and Solution

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.msbte.google_map_currentlocationroute">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.java
import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.net.Uri;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
Examination Paper Analysis and Solution

import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions; <meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.java
import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.net.Uri;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.MultiplePermissionsReport;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.DexterError;
Examination Paper Analysis and Solution

import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.PermissionRequestErrorListener;
import com.karumi.dexter.listener.multi.MultiplePermissionsListener;
import java.util.List;
public class MainActivity extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener , OnMapReadyCallback,
TaskLoadedCallback{
//variables for map and route
private GoogleMap mMap;
private MarkerOptions place1, place2;
Button getDirection;
private Polyline currentPolyline;
private MapFragment mapFragment;
private boolean isFirstTime = true;
//variables for current location
private static final String TAG = "MainActivity";
private TextView tvLocation;
private GoogleApiClient mGoogleApiClient;
private Location mLocation;
private LocationRequest mLocationRequest;
private com.google.android.gms.location.LocationListener listener;
private long UPDATE_INTERVAL = 2 * 1000; /* 10 secs */
private long FASTEST_INTERVAL = 2000; /* 2 sec */
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//code for getting current location
requestMultiplePermissions();
tvLocation = (TextView) findViewById((R.id.tv));
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
//code for drawing route
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.clear();
Log.d("mylog", "Added Markers");
mMap.addMarker(place1);
mMap.addMarker(place2);
CameraPosition googlePlex = CameraPosition.builder()
.target(new LatLng(22.7739,71.6673))
.zoom(7)
.bearing(0)
.tilt(45)
.build();
Examination Paper Analysis and Solution

mMap.animateCamera(CameraUpdateFactory.newCameraPosition(googlePlex), 5000,
null);
}
private String getUrl(LatLng origin, LatLng dest, String directionMode) {
// Origin of route
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Mode
String mode = "mode=" + directionMode;
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + mode;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters
+ "&key=" + getString(R.string.google_maps_key);
return url;
}
@Override
public void onTaskDone(Object... values) {
if (currentPolyline != null)
currentPolyline.remove();
currentPolyline = mMap.addPolyline((PolylineOptions) values[0]);
}
//runtime permission method
private void requestMultiplePermissions(){
Dexter.withActivity(this)
.withPermissions(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION )
.withListener(new MultiplePermissionsListener() {
@Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
// check if all permissions are granted
if (report.areAllPermissionsGranted()) {
Toast.makeText(getApplicationContext(), "All permissions are granted by user!",
Toast.LENGTH_SHORT).show();
}
// check for permanent denial of any permission
if (report.isAnyPermissionPermanentlyDenied()) {
// show alert dialog navigating to Settings
openSettingsDialog();
}
}
@Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions,
PermissionToken token) {
token.continuePermissionRequest();
}
}).
withErrorListener(new PermissionRequestErrorListener() {
Examination Paper Analysis and Solution

@Override
public void onError(DexterError error) {
Toast.makeText(getApplicationContext(), "Some Error! ",
Toast.LENGTH_SHORT).show();
}
})
.onSameThread()
.check();
}
private void openSettingsDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Required Permissions");
builder.setMessage("This app require permission to use awesome feature. Grant them in app
settings.");
builder.setPositiveButton("Take Me To SETTINGS", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, 101);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
//methods for getting current location
@Override
public void onConnected(Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
return;
}
startLocationUpdates();
mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLocation == null){
startLocationUpdates();
}
if (mLocation != null) {
// mLatitudeTextView.setText(String.valueOf(mLocation.getLatitude()));
//mLongitudeTextView.setText(String.valueOf(mLocation.getLongitude()));
Examination Paper Analysis and Solution

} else {
Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show();
}}
@Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Connection Suspended");
mGoogleApiClient.connect();
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode());
}
@Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}}
@Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}}
protected void startLocationUpdates() {
// Create the location request
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(UPDATE_INTERVAL)
.setFastestInterval(FASTEST_INTERVAL);
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
}
@Override
public void onLocationChanged(Location location) {
String msg = "Updated Location: " +
Double.toString(location.getLatitude()) + "," +
Double.toString(location.getLongitude());
tvLocation.setText(String.valueOf(location.getLatitude() +"
"+String.valueOf(location.getLongitude())));
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
if(isFirstTime){
//code to draw path on map
getDirection = findViewById(R.id.btnGetDirection);
Examination Paper Analysis and Solution

getDirection.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new FetchURL(MainActivity.this).execute(getUrl(place1.getPosition(),
place2.getPosition(), "driving"), "driving");
}
});
place1 = new MarkerOptions().position(new LatLng(location.getLatitude(),
location.getLongitude())).title("Location 1");
place2 = new MarkerOptions().position(new
LatLng(19.021824,72.8662016)).title("MSBTE");
mapFragment = (MapFragment)
getFragmentManager().findFragmentById(R.id.mapNearBy);
mapFragment.getMapAsync(this);
isFirstTime = false;
} }}
Examination Paper Analysis and Solution

You might also like