Download as pdf or txt
Download as pdf or txt
You are on page 1of 338

T H E C O D E J O U R N A L

P R E S E N T S

P Y T H O N

S O L V E D

S A M P L E

2 0 2 0

A L S O A V A I L A B L E F O R

P H P

M O B I L E A P P L I C A T I O D E V E L O P M E N T

W W W . T H E C O D E J O U R N A L . I N
Python Solved Sample 2020

Instructions:

(1) All questions are compulsory.


(2) Illustrate your answers with neat sketches wherever necessary.
(3) Figures to the right indicate full marks.
(4) Assume suitable data if necessary.
(5) Preferably, write the answers in sequential order.

Q1. Attempt any FIVE of the following. (10 Marks)


a) Name different modes of Python.

Answer: We can develop a python program in 2 different styles.

 Interactive Mode and


 Batch Mode.

Interactive Mode:

Interactive mode is a command line shell. If we write a python program in the command line shell.

Typically the interactive mode is used to test the features of the python, or to run a smaller script
that may not be reusable.

The >>> indicates that the Python shell is ready to execute and send your commands to the
Python interpreter. The result is immediately displayed on the Python shell as soon as the Python
interpreter interprets the command.

To run your Python statements, just type them and hit the enter key. You will get the results
immediately, unlike in script mode. For example, to print the text "Hello World", we can type the
following:

>>> print("Hello World")


Hello World
>>>
Python Solved Sample 2020
Script Mode

If you need to write a long piece of Python code or your Python script spans multiple files,
interactive mode is not recommended. Script mode is the way to go in such cases. In script mode,
You write your code in a text file then save it with a .py extension which stands for "Python". Note
that you can use any text editor for this, including Sublime, Atom, notepad++, etc.

b) List identity operators.

Answer: Identity operators compare the memory locations of two objects. There are two Identity
operators as explained below −

Operator Description Example


Evaluates to true if the variables on either
x is y, here is results in 1 if id(x) equals
is side of the operator point to the same object
id(y).
and false otherwise.
Evaluates to false if the variables on either
x is not y, here is not results in 1 if id(x) is
is not side of the operator point to the same object
not equal to id(y).
and true otherwise.

c) Describe Dictionary.

Answer: Dictionary in Python is an unordered collection of data values, used to store data values
like a map,

In Python, a Dictionary can be created by placing sequence of elements within curly {} braces,
separated by ‘comma’. Dictionary holds a pair of values, one being the Key and the other
corresponding pair element being its Key:value. Values in a dictionary can be of any datatype and
can be duplicated, whereas keys can’t be repeated and must be immutable.

Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}


print("\nDictionary with the use of Integer Keys: ")
print(Dict)
Python Solved Sample 2020
d) State use of namespace in Python.

Answer: A namespace is a simple system to control the names in a program. It ensures that names
are unique and won’t lead to any conflict.

Python implements namespaces in the form of dictionaries. It maintains a name-to-object mapping


where names act as keys and the objects as values. Multiple namespaces may have the same name
but pointing to a different variable..

 Local Namespace
This namespace covers the local names inside a function. Python creates this namespace
for every function called in a program. It remains active until the function returns.
 Global Namespace
This namespace covers the names from various imported modules used in a project. Python
creates this namespace for every module included in your program. It’ll last until the
program ends.
 Built-in Namespace
This namespace covers the built-in functions and built-in exception names. Python creates
it as the interpreter starts and keeps it until you exit.

e) List different Object Oriented features supported by Python.

Answer: Python is also an object-oriented language since its beginning. Python is an object-
oriented programming language. It allows us to develop applications using an Object Oriented
approach. In Python, we can easily create and use classes and objects.

Major principles of object-oriented programming system are given below.

 Object
 Class
 Method
 Inheritance
 Polymorphism
 Data Abstraction
Python Solved Sample 2020
 Encapsulation

g) Describe Python Interpreter.

Answer: An interpreter is a program that reads and executes code. This includes source code, pre-
compiled code, and scripts. Common interpreters include Perl, Python, and Ruby interpreters,
which execute Perl, Python, and Ruby code respectively.

The Python interpreter is the application that runs your python script. Read the script line by line
and converts that script into python byte code, and then writes the byte code into a pyc file. If your
application has multiple files it creates a pyc file for every .py file. It is at this stage that syntax
errors are generated.

Q.2) Attempt any THREE of the following. (12 Marks)

a) Explain two Membership and two logical operators in python with appropriate examples.

Answer: Python’s membership operators test for membership in a sequence, such as strings, lists,
or tuples. There are two membership operators as explained below −

Operator Description Example

Evaluates to true if it finds a variable in the x in y, here in results in a 1 if x is a member


in
specified sequence and false otherwise. of sequence y.

Evaluates to true if it does not finds a


x not in y, here not in results in a 1 if x is
not in variable in the specified sequence and false
not a member of sequence y.
otherwise.

Example

#!/usr/bin/python

a = 10
b = 20
list = [1, 2, 3, 4, 5 ];

if ( a in list ):
print "Line 1 - a is available in the given list"
else:
Python Solved Sample 2020
print "Line 1 - a is not available in the given list"

if ( b not in list ):
print "Line 2 - b is not available in the given list"
else:
print "Line 2 - b is available in the given list"

a = 2
if ( a in list ):
print "Line 3 - a is available in the given list"
else:
print "Line 3 - a is not available in the given list"

When you execute the above program it produces the following result −

Line 1 - a is not available in the given list


Line 2 - b is not available in the given list
Line 3 - a is available in the given list

There are following logical operators supported by Python language. Assume variable a holds 10
and variable b holds 20 then −

Operator Description Example


and
If both the operands are true then condition
Logical (a and b) is true.
becomes true.
AND
or
If any of the two operands are non-zero
Logical (a or b) is true.
then condition becomes true.
OR
not
Used to reverse the logical state of its
Logical Not(a and b) is false.
operand.
NOT

b) Describe any four methods of lists in Python.


Python Solved Sample 2020
Answer: The list is a most versatile datatype available in Python which can be written as a list of
comma-separated values (items) between square brackets. Important thing about a list is that items
in a list need not be of the same type.

Creating a list is as simple as putting different comma-separated values between square brackets.
For example −

list1 = ['physics', 'chemistry', 1997, 2000];


list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]

The methods of list are as follows -:

1. cmp(list1,list2) -: Comapre elements of both lists

Syntax

cmp(list1, list2)

Parameters

 list1 − This is the first list to be compared.


 list2 − This is the second list to be compared.

list1, list2 = [123, 'xyz'], [456, 'abc']


print cmp(list1, list2)
print cmp(list2, list1)
list3 = list2 + [786];
print cmp(list2, list3)

When we run above program, it produces following result −

-1
1
-1

2. Python list method len() returns the number of elements in the list.

Syntax len(list)
Python Solved Sample 2020
Parameters

 list − This is a list for which number of elements to be counted.

Example

#!/usr/bin/python

list1, list2 = [123, 'xyz', 'zara'], [456, 'abc']


print "First list length : ", len(list1)
print "Second list length : ", len(list2)

When we run above program, it produces following result −

First list length : 3


Second list length : 2

3. Python list method max returns the elements from the list with maximum value.

Syntax

max(list)

Parameters

 list − This is a list from which max valued element to be returned.

Example

#!/usr/bin/python

list1, list2 = [123, 'xyz', 'zara', 'abc'], [456, 700, 200]


print "Max value element : ", max(list1)
print "Max value element : ", max(list2)

When we run above program, it produces following result −

Max value element : zara


Max value element : 700

c) Comparing between local and global variable.

Answer:
Python Solved Sample 2020

d) Write a python program to print Fibonacci series up to n terms.

Answer:

nterms = int(input("How many terms? "))

# first two terms


n1, n2 = 0, 1
count = 0

# check if the number of terms is valid


if nterms <= 0:
Python Solved Sample 2020
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1

Q.3) Attempt any THREE of the following. (12 Marks)

a) Write a program to input any two tuples and interchange the tuple variable.

Answer:

t1 = tuple( )
n = input(“Total number of values m first tuple”)
for i in range (n):
a = input(“Enter elements”)
t2 = t2 + (a, )
print “First tuple”
print t1
print “Second tuple”
print t2 t1, t2 = t2, t1
print “After swapping”
print “First tuple”
print t1
print “Second tuple”
print t2
Python Solved Sample 2020
b) Explain different loops available in python with suitable examples.

Answer: In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on. There may be a situation when you need to
execute a block of code several number of times.

Programming languages provide various control structures that allow for more complicated
execution paths.

A loop statement allows us to execute a statement or group of statements multiple times. The
following diagram illustrates a loop statement –

1. While Loop

A while loop statement in Python programming language repeatedly executes a target statement
as long as a given condition is true.

Syntax

The syntax of a while loop in Python programming language is −

while expression:
Python Solved Sample 2020
statement(s)

Example

count = 0
while (count < 9):
print 'The count is:', count
count = count + 1

print "Good bye!"

2. For Loop

It has the ability to iterate over the items of any sequence, such as a list or a string.

Syntax

for iterating_var in sequence:


statements(s)
Python Solved Sample 2020
If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence
is assigned to the iterating variable iterating_var. Next, the statements block is executed. Each item
in the list is assigned to iterating_var, and the statement(s) block is executed until the entire
sequence is exhausted.

Flow Diagram

Example

#!/usr/bin/python

for letter in 'Python': # First Example


print 'Current Letter :', letter

fruits = ['banana', 'apple', 'mango']


for fruit in fruits: # Second Example
print 'Current fruit :', fruit

print "Good bye!"

3. Nested Loops
Python Solved Sample 2020
Python programming language allows to use one loop inside another loop. Following section
shows few examples to illustrate the concept.

Syntax

for iterating_var in sequence:


for iterating_var in sequence:
statements(s)
statements(s)

The syntax for a nested while loop statement in Python programming language is as follows –

while expression:
while expression:
statement(s)
statement(s)

Example

The following program uses a nested for loop to find the prime numbers from 2 to 100 –

#!/usr/bin/python

i = 2
while(i < 100):
j = 2
while(j <= (i/j)):
if not(i%j): break
j = j + 1
if (j > i/j) : print i, " is prime"
i = i + 1

print "Good bye!"

d) Illustrate the use of method overriding? Explain with example.

Answer: Method overriding is an ability of any object-oriented programming language that allows
a subclass or child class to provide a specific implementation of a method that is already provided
by one of its super-classes or parent classes. When a method in a subclass has the same name,
same parameters or signature and same return type (or sub-type) as a method in its super-class,
then the method in the subclass is said to override the method in the super-class.
Python Solved Sample 2020

Example -:

# Python program to demonstrate


# method overriding

# Defining parent class


class Parent():

# Constructor
def __init__(self):
self.value = "Inside Parent"

# Parent's show method


def show(self):
print(self.value)

# Defining child class


class Child(Parent):

# Constructor
def __init__(self):
self.value = "Inside Child"

# Child's show method


Python Solved Sample 2020
def show(self):
print(self.value)

# Driver's code
obj1 = Parent()
obj2 = Child()

obj1.show()

obj2.show()

Output:

Inside Parent
Inside Child

Q.4) Attempt any THREE of the following. (12 Marks)

a) Use of any four methods of tuple in python?

Answer: A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists.
The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples
use parentheses, whereas lists use square brackets.

1. LEN() Function -:

Python tuple method len() returns the number of elements in the tuple.

Syntax

len(tuple)

Example -:

tuple1, tuple2 = (123, 'xyz', 'zara'), (456, 'abc')


print "First tuple length : ", len(tuple1)
print "Second tuple length : ", len(tuple2)

2. MAX() Function -:
Python Solved Sample 2020
Python tuple method max() returns the elements from the tuple with maximum value.

Syntax

max(tuple)

Example -:

tuple1, tuple2 = (123, 'xyz', 'zara', 'abc'), (456, 700, 200)


print "Max value element : ", max(tuple1)
print "Max value element : ", max(tuple2)

3. MIN() Function -:

Python tuple method min() returns the elements from the tuple with minimum value.

Syntax

min(tuple)

Example -:

tuple1, tuple2 = (123, 'xyz', 'zara', 'abc'), (456, 700, 200)


print "min value element : ", min(tuple1)
print "min value element : ", min(tuple2)

4. CMP() Function -:

Python tuple method cmp() compares elements of two tuples.

Syntax

cmp(tuple1, tuple2)

Example -:

tuple1, tuple2 = (123, 'xyz'), (456, 'abc')


print cmp(tuple1, tuple2)
print cmp(tuple2, tuple1)
tuple3 = tuple2 + (786,);
print cmp(tuple2, tuple3)

b) Write a python program to read contents of first.txt file and write same content in
second.txt file.
Python Solved Sample 2020
with open("test.txt") as f:
with open("out.txt", "w") as f1:
for line in f:
f1.write(line)

c) Show how try…except blocks is used for exception handling in Python with example

Answer: The try block lets you test a block of code for errors. The except block lets you handle
the error.

When an error occurs, or exception as we call it, Python will normally stop and generate an error
message. These exceptions can be handled using the try statement:

How try() works?

 First try clause is executed i.e. the code between try and except clause.
 If there is no exception, then only try clause will run, except clause is finished.
 If any exception occured, try clause will be skipped and except clause will run.
 If any exception occurs, but the except clause within the code doesn’t handle it, it is passed
on to the outer try statements. If the exception left unhandled, then the execution stops.
 A try statement can have more than one except clause.

try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")

Another Example -:

def divide(x, y):


try:
# Floor Division : Gives only Fractional Part as Answer
result = x // y
print("Yeah ! Your answer is :", result)
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ")
Python Solved Sample 2020
d) Write the output for the following if the variable fruit=’banana’:
>>>fruit[:3]
>>>fruit[3:]
>>>fruit[3:3]
>>>fruit[:]

Answer: The output for the following code are as follows -:

>>>fruit[:3] ban
>>>fruit[3:] ana
>>>fruit[3:3] n
>>>fruit[:] banana

Q.5) Attempt any TWO of the following. (12 Marks)

a) Determine various data types available in Python with example.

Answer: A variable can hold different types of values. For example, a person's name must be stored
as a string whereas its id must be stored as an integer.

Python provides various standard data types that define the storage method on each of them. The
data types defined in Python are given below.

1. Number 2. String

3. List 4. Tuple

5. Dictionary
Python Solved Sample 2020
Numbers

Number stores numeric values. Python creates Number objects when a number is assigned to a
variable. For example;

a = 3 , b = 5 #a and b are number objects

Python supports 4 types of numeric data.

int (signed integers like 10, 2, 29, etc.)

long (long integers used for a higher range of values like 908090800L, -0x1929292L, etc.)

float (float is used to store floating point numbers like 1.9, 9.902, 15.2, etc.)

complex (complex numbers like 2.14j, 2.0 + 2.3j, etc.)

String

The string can be defined as the sequence of characters represented in the quotation marks.

The following example illustrates the string handling in python.

str1 = 'hello javatpoint' #string str1

str2 = ' how are you' #string str2

print (str1[0:2]) #printing first two character using slice operator

print (str1[4]) #printing 4th character of the string

print (str1*2) #printing the string twice

print (str1 + str2) #printing the concatenation of str1 and str2


Python Solved Sample 2020
Output:

he
o
hello javatpointhello javatpoint
hello javatpoint how are you

List
Lists are similar to arrays in C. However; the list can contain data of different types. The items
stored in the list are separated with a comma (,) and enclosed within square brackets [].

We can use slice [:] operators to access the data of the list. The concatenation operator (+) and
repetition operator (*) works with the list in the same way as they were working with the strings.

example.

l = [1, "hi", "python", 2]

print (l[3:]);

print (l[0:2]);

print (l);

print (l + l);

print (l * 3);

Output:

[2]
[1, 'hi']
[1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2]
Python Solved Sample 2020
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2, 1, 'hi', 'python', 2]

Tuple

A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the items
of different data types. The items of the tuple are separated with a comma (,) and enclosed in
parentheses ().

A tuple is a read-only data structure as we can't modify the size and value of the items of a tuple.

Example -:

t = ("hi", "python", 2)

print (t[1:]);

print (t[0:1]);

print (t);

print (t + t);

print (t * 3);

print (type(t))

t[2] = "hi";

Output:
Python Solved Sample 2020
('python', 2)
('hi',)
('hi', 'python', 2)
('hi', 'python', 2, 'hi', 'python', 2)
('hi', 'python', 2, 'hi', 'python', 2, 'hi', 'python', 2)
<type 'tuple'>
Traceback (most recent call last):
File "main.py", line 8, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment

Dictionary

Dictionary is an ordered set of a key-value pair of items. It is like an associative array or a hash
table where each key stores a specific value. Key can hold any primitive data type whereas value
is an arbitrary Python object.

The items in the dictionary are separated with the comma and enclosed in the curly braces {}.

example. -:

d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'};

print("1st name is "+d[1]);

print("2nd name is "+ d[4]);

print (d);

print (d.keys());

print (d.values());
Python Solved Sample 2020
Output:

1st name is Jimmy


2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
[1, 2, 3, 4]
['Jimmy', 'Alex', 'john', 'mike']

b) Write a python program to calculate factorial of given number using function.

Answer: The factorial of a number is the product of all the integers from 1 to that number.

For example, the factorial of 6 is 1*2*3*4*5*6 = 720. Factorial is not defined for negative numbers
and the factorial of zero is one, 0! = 1.

def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)

num = 7

# check if the number is negative


if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))

Output

The factorial of 7 is 5040


Python Solved Sample 2020
c) Show the output for the following:

1. >>> a=[1,2,3] 2. >>>[1,2,3]*3 3.


>>>t=[‘a’,’b’,’c’,’d’,’e’,’f’]
>>>b=[4,5,6]
>>>t[1:3]=[‘x’,’y’]
>>> c=a+b
>>>print t

Answer:

1. 2. 3.

[1,2,3,4,5,6] [1,2,3,1,2,3,1,2,3] [‘a’,’x’,’y’,’d’,’e’,’f’]

Q.6) Attempt any TWO of the following. (12 Marks)

a) Describe Set in python with suitable examples.

Answer: A Set is an unordered collection data type that is iterable, mutable and has no duplicate
elements. Python’s set class represents the mathematical notion of a set. The major advantage of
using a set, as opposed to a list, is that it has a highly optimized method for checking whether a
specific element is contained in the set. This is based on a data structure known as a hash table.

If Multiple values are present at the same index position, then the value is appended to that index
position, to form a Linked List. In, Python Sets are implemented using dictionary with dummy
variables, where key beings the members set with greater optimizations to the time complexity.

Set = set(["a", "b", "c"])

print("Set: ")
print(Set)

# Adding element to the set


Set.add("d")
Python Solved Sample 2020

print("\nSet after adding: ")

print(Set)

Output:

Set:
set(['a', 'c', 'b'])

Set after adding:


set(['a', 'c', 'b', 'd'])

b) Illustrate class inheritance in Python with an example.

Answer: Inheritance enable us to define a class that takes all the functionality from parent class
and allows us to add more. In this article, you will learn to use inheritance in Python.

It refers to defining a new class with little or no modification to an existing class. The new class is
called derived (or child) class and the one from which it inherits is called the base (or parent)
class.

Python Inheritance Syntax

class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class

Example -:
Python Solved Sample 2020

class Polygon:
def __init__(self, no_of_sides):
self.n = no_of_sides
self.sides = [0 for i in range(no_of_sides)]

def inputSides(self):
self.sides = [float(input("Enter side "+str(i+1)+" : ")) for i in range(self.n)]

def dispSides(self):
for i in range(self.n):
print("Side",i+1,"is",self.sides[i])

c) Design a class Employee with data members: name, department and salary. Create
suitable methods for reading and printing employee information.

Answer:

class Employee:

__name=""

__dep=""

__salary=0

def setData(self):

self.__name = input("Enter Name\t:")

self.__dep = input("Enter department\t:")


Python Solved Sample 2020

self.__salary = int(input("Enter Salary:"))

def showData(self):

print("Name\t:", self.__name)

print("Department\t:", self.__dep)

print("Salary\t:", self.__salary)

def main():

#Employee Object

emp=Employee()

emp.setData()

emp.showData()

if __name__=="__main__":

main()

Output -:
Python Solved Sample 2020
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
SUMMER – 2023 EXAMINATION
Model Answer – Only for the Use of RAC Assessors

Subject Name: Programming with Python Subject Code: 22616


Important Instructions to examiners: XXXXX
1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme.
2) The model answer and the answer written by candidate may vary but the examiner may try to assess the
understanding level of the candidate.
3) The language errors such as grammatical, spelling errors should not be given more Importance (Not applicable for
subject English and Communication Skills.
4) While assessing figures, examiner may give credit for principal components indicated in the figure. The figures
drawn by candidate and model answer may vary. The examiner may give credit for any equivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the assumed constant values may vary and
there may be some difference in the candidate’s answers and model answer.
6) In case of some questions credit may be given by judgement on part of examiner of relevant answer based on
candidate’s understanding.
7) For programming language papers, credit may be given to any other program based on equivalent concept.
8) As per the policy decision of Maharashtra State Government, teaching in English/Marathi and Bilingual (English +
Marathi) medium is introduced at first year of AICTE diploma Programme from academic year 2021-2022. Hence if
the students in first year (first and second semesters) write answers in Marathi or bilingual language (English
+Marathi), the Examiner shall consider the same and assess the answer based on matching of concepts with model
answer.

Q. Sub Answer Marking


No. Q. Scheme
N.

1 Attempt any FIVE of the following: 10 M

a) List features of Python. 2M

Ans Features of Python are listed below: Any 2,


• Easy to Learn and Use 1 M each
• Interpreted Language
• Interactive Mode
• Free and Open Source
• Platform Independence/Cross-platform Language/Portable
• Object-Oriented Language
• Extensible
b) Describe membership operators in python 2M

Ans • The membership operators in Python are used to find the existence of a particular 2 M for
element in the sequence, and used only with sequences like string, tuple, list, proper
dictionary etc. explanation
• Membership operators are used to check an item or an element that is part of a
string, a list or a tuple. A membership operator reduces the effort of searching an
element in the list.

Page No: 1 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
• Python provides ‘in’ and ‘not in’ operators which are called membership
operators and used to test whether a value or variable is in a sequence.
c) Write down the output of the following Python code 2M
>>>indices-['zero','one','two',' three,' four, five']
i) >>>indices[:4]
ii) >>>indices[:-2]
Ans Output as follows: 1 M for
i) >>>indices[:4] each
[zero, one, two, three] correct
ii) >>>indices[:-2] output
[zero, one, two, three]

d) Describe any two data conversion function. 2M

Ans • int(x [,base]): Converts x to an integer. base specifies the base if x is a Any 2
string. Conversion
Example: x=int('1100',base=2)=12 function
• long(x [,base]): Converts x to a long integer. base specifies the base if x is 2M
a string.
Example: x=long(‘123’base=8)=83L
• float(x): Converts x to a floating point number.
Example: x=float('123.45')=123.45
• complex(real[,imag]) : Creates a complex number.
Example: x=complex(1,2) = (1+2j)
• str(x): Converts object x to a string representation.
Example: x=str(10) = ‘10’
• repr(x): Converts object x to an expression string
Example: x=repr(3) = 3
• repr(x): Evaluates a string and returns an object.
Example: x=eval('1+2') = 3
• tuple(s): Converts s to a tuple
Example:
x=tuple('123') = ('1', '2', '3')
x=tuple([123]) = (123,)
• list(s): Converts s to a list
Example:
x=list('123') = ['1', '2', '3']
x=list(['12'] = ['12']
• set(s): Converts s to a set
Example:
x=set('Python')
= {'y', 't', 'o', 'P', 'n', 'h'}
• dict(d): Creates a dictionary. d must be a sequence of (key, value) tuples.

Page No: 2 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Example:
dict={'id':'11','name':'vijay'}
print(dict)
={'id': '11', 'name': 'vijay'}
• chr(x): Converts an integer to a character.
Example: x=chr(65) = ‘A’
• unichr(x): Converts an integer to a Unicode character
Example: x=unichr(65) =u’A’
• ord(x): Converts a single character to its integer value.
Example: x=ord('A')= 65
• hex(x): Converts an integer to a hexadecimal string.
Example: x=hex(12) = 0xc
• oct(x): Converts an integer to an octal string.
Example: x=oct(8) = 0o10

e) With neat example explain default constructor concept in Python. 2M

Ans The default constructor is simple constructor which does not accept any arguments. It’s Explanation
definition has only one argument which is a reference to the instance being constructed. 1 M,
Example
Example 1: Display Hello message using default constructor. 1M

class Student:

def _ _init_ _(self):

print("This is non parametrized constructor")

def show(self,name):

print("Hello",name)

s1 = Student()

s1.show("Student1")

Output:

This is non parametrized constructor


Hello Student1

f) Describe mkdir() function. 2M

Ans • We can make a new directory using the mkdir() method. Explanation
• This method takes in the path of the new directory. If the full path is not specified, 2M
the new directory is created in the current working directory.

Page No: 3 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Syntax: os.mkdir(“newdir”)

Example:

>>> import os

>>> os.mkdir("testdir")

g) Describe Multiline comment in python. 2M

Ans • In some situations, multiline documentation is required for a program. If we have 2 M for
comments that extend multiple lines, one way of doing it is to use hash (#) in the proper
beginning of each line. Another way of doing this is to use quotation marks, either explanation
''' or """.
• Similarly, when it sees the triple quotation marks ''' it scans for the next ''' and
ignores any text in between the triple quotation marks.
Example: For multiline comment.

'''This is first python program

Print is a statement'''

2. Attempt any THREE of the following: 12 M

a) Describe Keyword "continue" with example. 4M

Ans • The continue statement in Python returns the control to the beginning of the while Explanation
loop. 2M,
• The continue statement rejects all the remaining statements in the current iteration Example
of the loop and moves the control back to the top of the loop. 2M

Syntax: continue

Example: For continue statement.

i=0

while i<10:

i=i+1

if i==5:

continue

print("i= ",i)

Page No: 4 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Output:

i=1
i=2
i=3
i=4
i=6
i=7
i=8
i=9
i=10
b) Explain creating Dictionary and accessing Dictionary Elements with 4M
example.
Ans Creating Dictionary Creating
Dictionary
The simplest method to create dictionary is to simply assign the pair of key:values explanation
to the dictionary using operator (=). with example
• There are two ways for creation of dictionary in python. 2 M,
1. We can create a dictionary by placing a comma-separated list of key:value Accessing
pairs in curly braces{}. Each key is separated from its associated value by a Dictionary
colon: Element with
Example: For creating a dictionary using { }. example 2 M
>>> dict1={} #Empty dictionary
>>> dict1
{}
>>> dict2={1:"Orange", 2:"Mango", 3:"Banana"} #Dictionary with
integer keys
>>> dict2
{1: 'Orange', 2: 'Mango', 3: 'Banana'}
>>> dict3={"name":"vijay", 1:[10,20]} #Dictionary with mixed keys
>>> dict3
{'name': 'vijay', 1: [10, 20]}

2. Python provides a build-in function dict() for creating a dictionary

Example: Creating directory using dict().


>>> d1=dict({1:"Orange",2:"Mango",3:"Banana"})
>>> d2=dict([(1,"Red"),(2,"Yellow"),(3,"Green")])
>>> d3=dict(one=1, two=2, three=3)
>>> d1
{1: 'Orange', 2: 'Mango', 3: 'Banana'}
>>> d2
{1: 'Red', 2: 'Yellow', 3: 'Green'}
>>> d3
{'one': 1, 'two': 2, 'three': 3}

Page No: 5 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Accessing Values in a Dictionary
• We can access the items of a dictionary by following ways:
1. Referring to its key name, inside square brackets([]).
Example: For accessing dictionary items [ ] using.
>>> dict1={'name':'vijay','age':40}
>>> dict1['name']
'vijay'
>>> dict1['adr']
Traceback (most recent call last):
File "<pyshell#79>", line 1, in <module>
dict1['adr']
KeyError: 'adr'
>>>
Here, if we refer to a key that is not in the dictionary, you’ll get an
exception. This error can be avoided by using get() method.

2. Using get() method returns the value for key if key is in the dictionary, else
None, so that this method never raises a KeyError.
Example: For accessing dictionary elements by get().
>>> dict1={'name':'vijay','age':40}
>>> dict1.get('name')
'vijay'

c) Explain any four Python's Built-in Function with example. 4M

Ans • len(list) Any 4 Built-


It returns the length of the list. in function
Example: with example
>>> list1 4M
[1, 2, 3, 4, 5]
>>> len(list1)
5
• max(list)
It returns the item that has the maximum value in a list
Example:
>>> list1
[1, 2, 3, 4, 5]
>>> max(list1)
5

• sum(list)
Calculates sum of all the elements of list.
Example:
>>>list1
[1, 2, 3, 4, 5]
>>>sum(list1)

Page No: 6 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
15

• min(list)
It returns the item that has the minimum value in a list.
Example:
>>> list1
[1, 2, 3, 4, 5]
>>> min(list1)
1

• list(seq)
It converts a tuple into a list.
Example:

>>> list1
[1, 2, 3, 4, 5]
>>> list(list1)
[1, 2, 3, 4, 5]
• abs(n)
It returns the absolute value of a number.
Example:
>>> abs(10)
10

• all()
The all() function returns True if all items in an iterable are true, otherwise it
returns False.
Example:
>>> x=[True, True, True]
>>> all(x)
True

• any()
The any() function returns True if any item in an iterable are true, otherwise it
returns False. If the iterable object is empty, the any() function will return False.
Example:
>>> x=[True, False, True]
>>> any(x)
True

• bin()
The bin() function returns the binary version of a specified integer. The result
will always start >>> bin(10)
Example:

Page No: 7 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
'0b1010'
with the prefix 0b.

• bool()
The bool() function returns the boolean value of a specified object.
Example:
>>> bool(1)
True

• exp()
The method exp() returns returns exponential of x: ex.
x: This is a numeric expression.

Example:
>>> math.exp(1)
2.718281828459045
>>>

d) Write a Python program to find the factorial of a number provided by the 4M


user.

Ans num=int(input("Enter Number:")) Correct


fact=1 program
if num< 0: 4M
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
fact=fact*i
print("The factorial of ",num," is ",fact)

Output:
Enter Number: 5
The factorial of 5 is 120

3. Attempt any THREE of the following: 12 M

a) Write a python program to input any two tuples and interchange the tuple 4M
variables.

Ans def interchange_tuples(tup1, tup2): Any correct


programming

Page No: 8 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
new_tup1 = tup2 logic 4 M
new_tup2 = tup1
return new_tup1, new_tup2
# Input two tuples
tuple1 = tuple(input("Enter the elements of the first tuple (separated by commas):
").split(","))
tuple2 = tuple(input("Enter the elements of the second tuple (separated by commas):
").split(","))

# Interchange the tuples


result_tuple1, result_tuple2 = interchange_tuples(tuple1, tuple2)

# Display the result


print("Interchanged tuples:")
print("Tuple 1:", result_tuple1)
print("Tuple 2:", result_tuple2)
output:
Enter the elements of the first tuple (separated by commas): 10,20
Enter the elements of the second tuple (separated by commas): 30,40
Interchanged tuples:
Tuple 1: ('30', '40')
Tuple 2: ('10', '20')

b) Explain Bitwise operator in Python with appropriate example. 4M

Ans Bitwise operators available in Python: Any four


operator
1) Bitwise AND (&): Performs a bitwise AND operation on the corresponding bits (Each for 1
of two numbers. Each bit of the output is 1 if the corresponding bits of both M)
operands are 1; otherwise, it is 0.
Example:
a = 10 # binary: 1010
b = 6 # binary: 0110

Page No: 9 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
result = a & b
print(result) # Output: 2 (binary: 0010)
2) Bitwise OR (|): Performs a bitwise OR operation on the corresponding bits of two
numbers. Each bit of the output is 0 if the corresponding bits of both operands are
0; otherwise, it is 1.
Example:
a = 10 # binary: 1010
b = 6 # binary: 0110
result = a | b
print(result) # Output: 14 (binary: 1110)
3) Bitwise XOR (^): Performs a bitwise XOR (exclusive OR) operation on the
corresponding bits of two numbers. Each bit of the output is 1 if the
corresponding bits of the operands are different; otherwise, it is 0.
Example:
a = 10 # binary: 1010
b = 6 # binary: 0110
result = a ^ b
print(result) # Output: 12 (binary: 1100)
4) Bitwise NOT (~): Performs a bitwise NOT operation on a single operand, which
inverts all the bits. It returns the complement of the given number.
Example:
a = 10 # binary: 1010
result = ~a
print(result) # Output: -11 (binary: -1011)
5) Bitwise left shift (<<): Shifts the bits of the left operand to the left by a specified
number of positions. Zeros are shifted in from the right side.
Example:
a = 10 # binary: 1010
result = a << 2
print(result) # Output: 40 (binary: 101000)
6) Bitwise right shift (>>): Shifts the bits of the left operand to the right by a

Page No: 10 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
specified number of positions. Zeros are shifted in from the left side.
Example:
a = 10 # binary: 1010
result = a >> 2

print(result) # Output: 2 (binary: 10)

c) With neat example differentiate between readline () and readlines ( ) 4M


functions in file-handling.

Ans readline(): This method reads a single line from the file and returns it as a string. It moves readline()
the file pointer to the next line after reading. If called again, it will read the subsequent explanation
line. for 1 M and
Example for
# Open the file in read mode 1M
file = open("example.txt", "r") and
readlines()
# Read the first line
explanation
line1 = file.readline() for 1 M and
Example for
print(line1) 1M

# Read the second line


line2 = file.readline()
print(line2)

# Close the file


file.close()
readlines(): This method reads all lines from the file and returns them as a list of strings.
Each line is an individual element in the list. It reads the entire file content and stores it in
memory.
Example:
# Open the file in read mode
file = open("example.txt", "r")

# Read all lines

Page No: 11 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
lines = file.readlines()

# Close the file


file.close()
# Print each line
for line in lines:
print(line)

d) Describe 'Self Parameter with example. 4M

Ans In Python, the self parameter is a convention used in object-oriented programming (OOP) Explanation
to refer to the instance of a class within the class itself. It allows you to access the 2 M and
attributes and methods of the class from within its own methods. The name self is not a
example 2
keyword in Python, but it is widely adopted and recommended as a convention.
M
Example:
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year

def get_info(self):
info = f"Make: {self.make}, Model: {self.model}, Year: {self.year}"
return info

def start_engine(self):
print("Engine started!")

# Create an instance of the Car class


my_car = Car("Toyota", "Corolla", 2022)

Page No: 12 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
# Access the attributes using the self parameter
print(my_car.make) # Output: Toyota
print(my_car.model) # Output: Corolla
print(my_car.year) # Output: 2022

# Call the method using the self parameter


car_info = my_car.get_info()
print(car_info) # Output: Make: Toyota, Model: Corolla, Year: 2022

# Call the method that does not require any additional parameters
my_car.start_engine() # Output: Engine started!

4. Attempt any THREE of the following: 12 M

a) Differentiate between list and Tuple. 4M

Ans Any 4
correct point
List Tuple 4M
Lists are mutable Tuples are immutable

The implication of iterations is Time- The implication of iterations is


consuming comparatively Faster

The list is better for performing A Tuple data type is appropriate for
operations, such as insertion and deletion. accessing the elements

Lists consume more memory Tuple consumes less memory as


compared to the list

Lists have several built-in methods Tuple does not have many built-in
methods.

Unexpected changes and errors are more In a tuple, it is hard to take place.
likely to occur

b) Explain any four file modes in Python. 4M

Ans Sr. No. Mode Description 1 Mode for 1


1 r Opens a file for reading only. The file pointer is placed at the M
beginning of the file. This is the default mode.
2 rb Opens a file for reading only in binary format. The file pointer
Page No: 13 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
is placed at the beginning of the file. This is the default mode.
3 r+ Opens a file for both reading and writing. The file pointer placed at
the beginning of the file.
4 rb+ Opens a file for both reading and writing in binary format. The
file pointer placed at the beginning of the file.
5 w Opens a file for writing only. Overwrites the file if the file
exists. If the file does not exist, creates a new file for writing.
6 wb Opens a file for writing only in binary format. Overwrites the
file if the file exists. If the file does not exist, creates a new file
for writing
7 w+ Opens a file for both writing and reading. Overwrites the
existing file if the file exists. If the file does not exist, creates a
new file for reading and writing.
8 wb+ Opens a file for both writing and reading in binary format.
Overwrites the existing file if the file exists. If the file does not
exist, creates a new file for reading
and writing
9 a Opens a file for appending. The file pointer is at the end of the
file if the file exists. That is, the file is in the append mode. If
the file does not exist, it creates a new file for writing.
10 ab Opens a file for appending in binary format. The file pointer is
at the end of the file if the file exists. That is, the file is in the
append mode. If the file does not exist, it creates a new file for
writing
11 a+ Opens a file for both appending and reading. The file pointer
is at the end of the file if the file exists. The file opens in the
append mode. If the file does not exist, it creates a new file for
reading and writing.
12 ab+ Opens a file for both appending and reading in binary format.
The file pointer is at the end of the file if the file exists. The file
opens in the append mode. If the file does not exist, it creates
a new file for reading and writing.
13 t Opens in text mode (default).
14 b Opens in binary mode.
15 + Opens a file for updating (reading and writing).
c) Write a program to show user defined exception in Python. 4M

Ans class MyException(Exception): Any correct


logic
def __init__(self, message): program 4 M
self.message = message

# Function that raises the custom exception


def divide_numbers(a, b):

Page No: 14 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
if b == 0:
raise MyException("Division by zero is not allowed!")
return a / b

# Main program
try:
num1 = int(input("Enter the numerator: "))
num2 = int(input("Enter the denominator: "))

result = divide_numbers(num1, num2)


print("Result:", result)

except MyException as e:
print("Exception:", e.message)
Note: Any correct program of user defined exception can be considered.
Output:
Enter the numerator: 10
Enter the denominator: 0
Exception: Division by zero is not allowed!
Enter the numerator: 10
Enter the denominator: 5
Result: 2.0

d) Explain Module and its use in Python. 4M

Ans Modules are primarily the (.py) files which contain Python programming code defining Explanation
functions, class, variables, etc. with a suffix .py appended in its file name. 2 M and use
2M
• A file containing .py python code is called a module.
• If we want to write a longer program, we can use file where we can do editing,
correction. This is known as creating a script. As the program gets longer, we may want
to split it into several files for easier maintenance.
• We may also want to use a function that you’ve written in several programs without
Page No: 15 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
copying its definition into each program.
• In Python we can put definitions in a file and use them in a script or in an interactive
instance of the interpreter. Such a file is called a module.
Use of module in python :
Code organization: Modules allow you to organize related code into separate files,
making it easier to navigate and maintain large projects.
Code reusability: Modules can be imported and reused in multiple programs, enabling
code reuse and reducing duplication.
Encapsulation: Modules provide a way to encapsulate code and hide the implementation
details, allowing users to focus on the functionality provided by the module.
Name spacing: Modules help avoid naming conflicts by providing a separate namespace
for the names defined within the module.

5. Attempt any TWO of the following: 12 M

a) Write a Python Program to check if a string is palindrome Or not. 6M

Ans def is_palindrome(string): Any correct


logic
# Remove whitespace and convert to lowercase program 6M.
string = string.replace(" ", "").lower()
# Reverse the string
reversed_string = string[::-1]
# Check if the original and reversed strings are the same
if string == reversed_string:
return True
else:
return False
# Test the function
input_string = input("Enter a string: ")
if is_palindrome(input_string):
print("The string is a palindrome.")
else:

Page No: 16 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
print("The string is not a palindrome.")
output:
Enter a string: madam
The string is a palindrome.
Enter a string: abc
The string is not a palindrome.

b) Write a Python program to calculate sum of digit of given number using 6M


function.

Ans def calculate_digit_sum(number): Any correct


logic
# Convert the number to a string program 6M.
num_str = str(number)
# Initialize a variable to store the sum
digit_sum = 0
# Iterate over each character in the string
for digit in num_str:
# Convert the character back to an integer and add it to the sum
digit_sum += int(digit)
# Return the sum of the digits
return digit_sum
# Test the function
input_number = int(input("Enter a number: "))
sum_of_digits = calculate_digit_sum(input_number)
print("Sum of digits:", sum_of_digits)
output:
Enter a number: 123
Sum of digits: 6

c) Write a Python Program to accept values from user in a list and find the 6M
largest number and smallest number in a list.

Ans list = [] Any correct


logic
Page No: 17 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
num = int(input('How many numbers: ')) program 6M

for n in range(num):

numbers = int(input('Enter number '))

list.append(numbers)

print("Maximum element in the list is :", max(list), "\nMinimum element in the list is :",
min(list))

output:

How many numbers: 5

Enter number 10

Enter number 20

Enter number 30

Enter number 40

Enter number 50

Maximum element in the list is : 50

Minimum element in the list is : 10

6. Attempt any TWO of the following: 12 M

a) Explain any six set function with example. 6M

Ans 1) union():Return a new set containing the union of two or more sets 1 function
for 1 M each
Example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print(union_set) # Output: {1, 2, 3, 4, 5}
2) Intersection:
Intersection operation performed on two sets returns all the elements which are
common or in both the sets.
Example:

Page No: 18 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
set1 = {1, 2, 3}
set2 = {2, 3, 4}
intersection_set = set1.intersection(set2)
print(intersection_set) # Output: {2, 3}
3) Difference:
Difference operation on two sets set1 and set2 returns all the elements which are
present on set1 but not in set2.
Example:
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4}
difference_set = set1.difference(set2)
print(difference_set) # Output: {1, 2, 5}
4) add(element):
This function adds an element to a set.
Example:
fruits = {"apple", "banana", "cherry"}
fruits.add("orange")
print(fruits) # Output: {'apple', 'banana', 'cherry', 'orange'}

5) remove(element):
This function removes an element from a set.
Example:
numbers = {1, 2, 3, 4, 5}
numbers.remove(3)
print(numbers) # Output: {1, 2, 4, 5}
6) clear():
This function removes all elements from a set, making it an empty set.
Example:
numbers = {1, 2, 3, 4, 5}

Page No: 19 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
numbers.clear()
print(numbers) # Output: set()
7) isdisjoint():
The isdisjoint() method in Python's set class is used to check whether two sets
have any common elements. It returns True if the sets are disjoint (i.e., they have
no common elements), and False otherwise.
Example:
# Example 1
set1 = {1, 2, 3, 4}
set2 = {5, 6, 7}
set3 = {3, 4, 5}

print(set1.isdisjoint(set2)) # True, no common elements


print(set1.isdisjoint(set3)) # False, both sets have elements 3 and 4

# Example 2
fruits = {"apple", "banana", "orange"}
colors = {"red", "green", "blue"}

print(fruits.isdisjoint(colors)) # True, no common elements

# Example 3
setA = {1, 2, 3}
setB = {4, 5, 6}

print(setA.isdisjoint(setB)) # True, no common elements

8) pop():method in Python's set class is used to remove and return an arbitrary


element from the set. Since sets are unordered collections, there is no guarantee
on which element will be popped.
Example:
fruits = {"apple", "banana", "orange", "grape"}

# Remove and return an arbitrary element from the set


popped_element = fruits.pop()

print(popped_element) # Output: an arbitrary element from the set


print(fruits) # Output: the modified set after popping an element

9) update():The update() method in Python's set class is used to update a set by


adding elements from another iterable or set. It modifies the set in place by adding
all the elements from the iterable or set specified.
Example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}

Page No: 20 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
set1.update(set2)

print(set1) # Output: {1, 2, 3, 4, 5}

b) Design a class student with data members : name, roll no., department, 6M
mobile no. Create suitable methods for reading and printing student
information.

Ans class Student: Any correct


logic
def __init__(self): program 6
M
self.name = ""
self.roll_no = ""
self.department = ""
self.mobile_no = ""

def read_student_info(self):
self.name = input("Enter student name: ")
self.roll_no = input("Enter roll number: ")
self.department = input("Enter department: ")
self.mobile_no = input("Enter mobile number: ")

def print_student_info(self):
print("Student Information:")
print("Name:", self.name)
print("Roll Number:", self.roll_no)
print("Department:", self.department)
print("Mobile Number:", self.mobile_no)

# Create an instance of the Student class


student = Student()

Page No: 21 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
# Read and set student information
student.read_student_info()

# Print student information


student.print_student_info()
output:
Enter student name: raj
Enter roll number: 11
Enter department: computer
Enter mobile number: 123456
Student Information:
Name: raj
Roll Number: 11
Department: computer
Mobile Number: 123456

c) With suitable example explain inheritance in Python. 6M

Ans In inheritance objects of one class procure the properties of objects of another class. Explanation
Inheritance provide code usability, which means that some of the new features can be 3 M and
added to the code while using the existing code. The mechanism of designing or Correct
constructing classes from other classes is called inheritance. example 3 M
• The new class is called derived class or child class and the class from which this
derived class has been inherited is the base class or parent class.
• In inheritance, the child class acquires the properties and can access all the data
members and functions defined in the parent class. A child class can also provide its
specific implementation to the functions of the parent class.
Syntax:
class A:
# properties of class A
class B(A):
# class B inheriting property of class A
# more properties of class B

Page No: 22 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Example:
# Base class
class Animal:
def __init__(self, name):
self.name = name

def speak(self):
print("Animal speaks")

# Derived class inheriting from Animal


class Dog(Animal):
def speak(self):
print("Dog barks")

# Derived class inheriting from Animal


class Cat(Animal):
def speak(self):
print("Cat meows")

# Create instances of derived classes


dog = Dog("Buddy")
cat = Cat("Whiskers")

# Call the speak method of the derived classes


dog.speak() # Output: Dog barks
cat.speak() # Output: Cat meows

Page No: 23 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________

Page No: 24 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
WINTER – 2022 EXAMINATION
Subject Name: Programming with Python Model Answer Subject Code: 22616
Important Instructions to examiners: XXXXX
1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme.
2) The model answer and the answer written by candidate may vary but the examiner may try to assess the
understanding level of the candidate.
3) The language errors such as grammatical, spelling errors should not be given more Importance (Not applicable for
subject English and Communication Skills.
4) While assessing figures, examiner may give credit for principal components indicated in the figure. The figures
drawn by candidate and model answer may vary. The examiner may give credit for any equivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the assumed constant values may vary and
there may be some difference in the candidate’s answers and model answer.
6) In case of some questions credit may be given by judgement on part of examiner of relevant answer based on
candidate’s understanding.
7) For programming language papers, credit may be given to any other program based on equivalent concept.
8) As per the policy decision of Maharashtra State Government, teaching in English/Marathi and Bilingual (English +
Marathi) medium is introduced at first year of AICTE diploma Programme from academic year 2021-2022. Hence if
the students in first year (first and second semesters) write answers in Marathi or bilingual language (English
+Marathi), the Examiner shall consider the same and assess the answer based on matching of concepts with
model answer.

Q. Sub Answer Marking


No. Q. Scheme
N.

1 Attempt any FIVE of the following: 10 M

a) List Python features. (Any four) 2M

Ans  Easy to Learn and Use 2M (1/2 M each)


 Interactive Mode Any Four
 Expressive Language
 Interpreted Language
 Cross-platform Language
 Portable
 Free and Open Source
 Object-Oriented Language
 Extensible
 Large Standard Library
 GUI Programming Support
 Integrated
 Databases
 Scalable
b) List comparision operators in Python. 2M

Ans Comparison operators in Python are 2M (1M each)

Operator Meaning
== Equal to
Page No: 1 | 21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
!= Not Equal to
< Less than
> Greater than
<= Less than and Equal to
>= Greater than and Equal to
c) Describe Tuples in Python. 2M

Ans A tuple is a collection of items which is ordered and unchangeable. 2M for


Tuples are the sequence or series values of different types separated by commas (,). Definition.
Example: tup1=(10,20,30)

d) Write use of lambda function in python. 2M

Ans The lambda function, which is also called anonymous function. A lambda function can 2M for use
take any number of arguments, but can only have one expression.
Syntax: lambda arguments : expression
Example: x= lambda a,b : a*b
Print(x(10,5)
Output: 50
e) Write syntax of defining class in Python. 2M

Ans class <ClassName>: 2M for syntax


<statement1>
<statement2>
.
.
<statementN>

f) List file operations in Python. 2M

Ans  Opening file (using open() function) 2M


 Reading file (using read() function)
 Writing file (using write() function)
 Copy files
 Delete files (using remove() function)
 Closing file (Using close() function)
g) Describe indentation in Python. 2M

Ans Indentation refers to the spaces at the beginning of a code line. Python indentation 2M
refers to adding white space before a statement to a particular block of code. In another
word, all the statements with the same space to the right, belong to the same code
block.

Page No: 2 | 21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________

2. Attempt any THREE of the following: 12 M

a) Describe bitwise operators in Python with example. 4M

Ans Bitwise operators acts on bits and performs bit by bit operation. Assume a=10 (1010) 4M (for any
and b=4 (0100) four, 1M each)
Operator Meaning Description Example
& Binary AND This operation a &b =
performs AND 1010 &
operation 0100 =
between 0000 =0
operands.
Operator copies a
bit, to the result,
if it exists in both
operands
| Binary OR This operation a|b = 1010 |
performs OR 0100 =
operation 1110 = 14
between
operands. It
copies a bit, if it
exists in either
operand.
^ Binary XOR This operation a^b=1010 ^
performs XOR 0100 =
operations 1110 =14
between
operands. It
copies the bit, if it
is set in one
operand but not
both.
~ Binary Ones It is unary ~a= ~ 1010
Complement operator and has = 0101
the effect of
'flipping' bits i.e.
opposite the bits
of operand.
<< Binary Left The left operand's a<<2 =
Page No: 3 | 21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Shift value is moved 1010 << 2
left by the =101000 =
number of bits 40
specified by the
right operand.
>> Binary Right The left operand's a>>2 =
Shift value is moved 1010 >> 2
right by the =0010 = 2
number of bits
specified by the
right operand.
b) Write any four methods of dictionary. 4M

Ans 4M (any four,


1M each)

Page No: 4 | 21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________

c) What is local and global variables? Explain with appropriate example. 4M

Ans  Global variables: global variables can be accessed throughout the program 4M (2M for
body by all functions. explanation
 Local variables: local variables can be accessed only inside the function in and 2M for
which they are declared example)
Concept Diagram:

A global variable (x) can be reached and modified anywhere in the code, local
variable (z) exists only in block 3.
Example:
g=10 #global variable g
def test():
l=20 #local variable l
print("local variable=",l)
# accessing global variable
print("Global variable=",g)

Page No: 5 | 21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________

test()
print("global variable=",g)

output:
local variable= 20
Global variable= 10
global variable= 10

d) Write python program to illustrate if else ladder. 4M

Ans i = 20 4M (for correct


if (i == 10): program and
print ("i is 10") logic)
elif (i == 15):
print ("i is 15")
elif (i == 20):
print ("i is 20")
else:
print ("i is not present")

output:
i is 20
(Similar type of program can consider)

3. Attempt any THREE of the following: 12 M

a) Write basis operations of list. 4M

Ans 1)Accessing values in list: Any two


Accessing elements liters from a list in Python is a method to get values that are stared operations:
in the list at a particular location or index.
To access values in lists, use the square brackets for slicing along with the index or 2 M for each
indices to obtain value available at that index.
Example: accessing list values.
>>> list1 = ["one","two",3,10,"six",20]
>>> list1[0]
'one'
>>> list1[-2]
'six'
>>> list1[1:3]
['two', 3]
>>> list1[3:]
[10, 'six', 20]
>>> list1[:4]
['one', 'two', 3, 10]
>>>

Page No: 6 | 21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
2) Deleting Values in List
The pop() method in Python is used to remove a particular item/element from the given
index in the list. The pop() method removes and returns the last item if index is not
provided. This helps us implement lists as stacks (first in, last out data structure).
>>> list= [10, 20, 30, 40]
>>> list
[10, 20, 30, 40]
30
>>> list
[10, 20, 40]
>>> list.pop()
40
>>> list
[10, 30]
We can delete one or more items from a list using the keyword del. It can even delete
the list entirely. But it does not store the value for further use
>>> list= [10, 20, 30, 40]
>>> list
[10, 20, 30, 40]
>>> del (list[1]) # del() with index
>>> list
[10, 30, 40]
>>> del list[2] # del with index
>>> list
[10, 30]
The remove() method in Python issued to remove a particular element from the list. We
use the remove() method if we know the item that we want to remove or delete from the
list (but not the index).
>>> list=[10,"one",20,"two"]
>>> list.remove(20)
>>> list
[10, 'one', 'two']
>>> list.remove("one")
>>> list
[10, 'two']
>>>

3. Updating Lists:
• List are mutable, meaning their elements can be changed or updated unlike string or
tuple.
• Mutability is the ability for certain types of data to be changed without entirely
recreating it. Using
mutable data types can allow programs to operate quickly and efficiently.

Page No: 7 | 21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
• Multiple values can be added into list. We can use assignment operator (=) to change
an item or a
range of items.
• We can update items of the list by simply assigning the value at the particular index
position. We
can also remove the items from the list using remove() or pop() or del statement.

>>> list1= [10, 20, 30, 40, 50]


>>> list1
[10, 20, 30, 40, 50]
>>> list1[0]=0 # change 0th index element
>>> list1
[0, 20, 30, 40, 50]
>>> list1[-1]=60 # change last index element
>>> list1
[0, 20, 30, 40, 60]
>>> list1[1]=[5,10] # change 1st index element as sublist
>>> list1
[0, [5, 10], 30, 40, 60]
>>> list1[1:1]=[3,4] # add elements to a list at the desired location
>>> list1
[0, 3, 4, [5, 10], 30, 40, 60]

4 Indexing
There are various ways in which we can access the elements of a list.
List Index: We can use the index operator [] to access an item in a list. Index starts
from 0. So, a list having 5 elements will have index from 0 to 4.
Example:
>>> list1=[10,20,30,40,50]
>>> list1[0]
10
>>> list1[4]
50
>>> list1[1:3]
[20, 30]

5. List Slicing
The slicing operator returns a subset of a list called slice by specifying two indices, i.e.
start and end.
Syntax:
List_variable[start_index:end_index]
Example:
>>> l1=([10,20,30,40,50])
>>> l1[1:4]
[20, 30, 40]
Page No: 8 | 21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________

b) Write Python code for finding greatest among four numbers. 4M

Ans list1 = [ ] Any correct


num = int(input("Enter number of elements in list: ")) logic program
for i in range(1, num + 1): 4M
element = int(input("Enter elements: "))
list1.append(element)
print("Largest element is:", max(list1))
Output:
Enter number of elements in list: 4
Enter elements: 10
Enter elements: 20
Enter elements: 45
Enter elements: 20
Largest element is: 45
c) Illustrate with example method over loading. 4M

Ans • Method overloading is the ability to define the method with the same name but with a Explanation
different number of arguments and data types. 1 M and
• With this ability one method can perform different tasks, depending on the number of Example 3 M
arguments or the types of the arguments given.
• Method overloading is a concept in which a method in a class performs operations
according to the parameters passed to it.
Example: With a method to perform different operations using method overloading.
class operation:
def add(self,a,b):
return a+b
op1=operation()
# To add two integer numbers
print("Addition of integer numbers=",op1.add(10,20))
# To add two floting point numbers
print("Addition of integer numbers=",op1.add(11.12,12.13))
# To add two strings
print("Addition of integer numbers=",op1.add("Hello","Python"))
Output:
Addition of integer numbers= 30
Addition of integer numbers= 23.25
Addition of integer numbers= HelloPython
Python does not support method overloading, that is, it is not possible to define more
than one method with the same name in a class in Python.
• This is because method arguments in python do not have a type. A method accepting
one argument can be called with an integer value, a string or a double as shown in next
example.
Page No: 9 | 21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
class Demo:
def method(self, a):
print(a)
obj= Demo()
obj.method(50)
obj.method('Meenakshi')
obj.method(100.2)
Output:
50
Meenakshi
100.2
d) Explain how try-catch block is used for exception handling in python. 4M

Ans • In Python, exceptions can be handled using a try statement. A try block Proper
consisting of one or more statements is used by programmers to partition code explanation
that might be affected by an exception.
• A critical operation which can raise exception is placed inside the try clause and the 4 M
code that handles exception is written in except clause.
• The associated except blocks are used to handle any resulting exceptions thrown in
the try block. That is we want the try block to succeed and if it does not succeed, we
want to control to pass to the catch block.
• If any statement within the try block throws an exception, control immediately shifts
to the catch block. If no exception is thrown in the try block, the catch block is skipped.
• There can be one or more except blocks. Multiple except blocks with different
exception names can be chained together.
• The except blocks are evaluated from top to bottom in the code, but only one except
block is executed for each exception that is thrown.
• The first except block that specifies the exact exception name of the thrown exception
is executed. If no except block specifies a matching exception name then an except
block that does not have an exception name is selected, if one is present in the code.
• For handling exception in Python, the exception handler block needs to be written
which consists of set of statements that need to be executed according to raised
exception. There are three blocks that are used in the exception handling process,
namely, try, except and finally.
1. try Block: A set of statements that may cause error during runtime are to be written
in the try
block.
2. except Block: It is written to display the execution details to the user when certain
exception occurs in the program. The except block executed only when a certain type as
exception occurs in the execution of statements written in the try block.

Syntax:
try:
D the operations here
......................

Page No: 10 | 21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
except Exception1:
If there is Exception1, then execute this block.
except Exception2:
If there is Exception2, then execute this block.
......................
else:
If there is no exception then execute this block.

Example: For try-except clause/statement.


n=10
m=0
try:
n/m
except ZeroDivisionError:
print("Divide by zero error")
else:
print (n/m)
Output:
Divide by zero error

4. Attempt any THREE of the following: 12 M

a) Compare list and dictionary. (Any 4 points) 4M

Ans List Dictionary Any four point,

List is a collection of index values pairs Dictionary is a hashed structure of 1 M for 1 point
as that of array in c++. key and value pairs.

List is created by placing elements in [ ] Dictionary is created by placing


separated by commas “, “ elements in { } as “key”:”value”,
each key value pair is separated by
commas “, “

The indices of list are integers starting The keys of dictionary can be of any
from 0. data type.

The elements are accessed via indices. The elements are accessed via key-
values.

The order of the elements entered are There is no guarantee for


maintained. maintaining order.

b) What is command line argument? Write python code to add b) two 4M


numbers given as input from command line arguments and print its sum.

Page No: 11 | 21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Ans Python Command line arguments are input parameters passed to the script when 1 M for
executing them. Almost all programming language provide support for command line definition and
arguments. Then we also have command line options to set some specific options for 3 M for
the program. program
There are many options to read python command line arguments. The three most
common ones are:
Python sys.argv
Python getopt module
Python argparse module

Program:
import sys
x=int(sys.argv[1])
y=int(sys.argv[2])
sum=x+y
print("The addition is :",sum)

Output:
C:\Python34\python sum.py 6 4
The addition is : 10
c) Write python code to count frequency of each characters in a given file. 4M

Ans import collections Any proper


import pprint logic program
file_input = input('File Name: ') 4M
with open(file_input, 'r') as info:
count = collections.Counter(info.read().upper())
value = pprint.pformat(count)
print(value)
d) Write python program to read contents of abc.txt and write same content to 4M
pqr.txt.
Ans with open('abs.txt','r') as firstfile, open('prq.txt','w') as secondfile: Any proper
# read content from first file logic program
for line in firstfile: for 4 M
# write content to second file
secondfile.write(line)

5. Attempt any TWO of the following: 12 M

a) Write different data types in python with suitable example. 6M

Ans Data types in Python programming includes:


 Numbers: Represents numeric data to perform mathematical operations.
Page No: 12 | 21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
 String: Represents text characters, special symbols or alphanumeric data.
 List: Represents sequential data that the programmer wishes to sort, merge etc.
6m for data
 Tuple: Represents sequential data with a little difference from list. types
 Dictionary: Represents a collection of data that associate a unique key with each
value.
 Boolean: Represents truth-values (true or false).

1. Integers (int Data Type): An integer is a whole number that can be positive (+) or
negative (−). Integers can be of any length, it is only limited by the memory available.
Example: For number data types are integers.
>>>a=10
>>>b -10
To determine the type of a variable type() function is used.
>>>type(a)
>>> <class 'int'>

2. Boolean (Bool Data Type: The simplest build-in type in Python is the bool type, it
represents the truth-values False and True. Internally the true value is represented as
1 and false is 0.
For example
>>>a = 18 > 5
>>>print(a)
True
b=2>3
print(b)
False

3. Floating-Point/Float Numbers (Float Data Type): Floating-point number or Float is


a positive or negative number with a fractional part. A floating point number is
accurate up to 15 decimal places. Integer and floating points are separated by decimal
points. 1 is integer, 1.0 is floating point number.
Example: Floating point number.
x=10.1
type(x)
<class 'float'>

4. Complex Numbers (Complex Data Type): Complex numbers are written in the form,
x + yj, where x is the real part and y is the imaginary part.
Example:
Complex number.
>>>x = 3+4j
>>>print(x.real)
3.0
>>>print(x.imag)
4.0

Page No: 13 | 21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
5. String Data Type: String is a collection of group of characters. Strings are identified
as a contiguous set of characters enclosed in single quotes (' ') or double quotes (" ").
Any letter, a number or a symbol could be a part of the string. Strings are
unchangeable (immutable). Once a string is created, it cannot be modified.
Example: For string data type.
>>> s1="Hello" #string in double quotes
>>> s2='Hi' #string in single quotes
>>> s3="Don't open the door" #single quote string in double quotes
>>> s4='I said "yipee"' #double quote string in single quotes
>>>type(s1)
<class 'str'>

6. List Data Type: List is an ordered sequence of items. It is one of the most used
datatype in Python and is very flexible.
List can contain heterogeneous values such as integers, floats, strings, tuples, lists and
dictionaries but they are commonly used to store collections of homogeneous objects.
The list datatype in Python programming is just like an array that can store a group of
elements and we can refer to these elements using a single name. Declaring a list is
pretty straight forward. Items separated by commas ( , ) are enclosed within brackets [
].
Example: For list.
>>> first=[10, 20, 30] # homogenous values in list
>>> second=["One","Two","Three"] # homogenous values in list
>>> first
[10, 20, 30]
>>> second
['One', 'Two', 'Three']
>>> first + second # prints the concatenated lists
[10, 20, 30, 'One', 'Two', 'Three']

7. Tuple Data Type: Tuple is an ordered sequence of items same as list. The only
difference is that tuples are immutable.
Tuples once created cannot be modified. It is defined within parentheses ( ) where
items are separated by commas ( , ).
A tuple data type in python programming is similar to a list data type, which also
contains heterogeneous items/elements.
Example: For tuple.
>>> a=(10,'abc',1+3j)
>>> a
(10, 'abc', (1+3j))
>>> a[0]
10
>>> a[0]=20
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>

Page No: 14 | 21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
8. Dictionary: Dictionary is an unordered collection of key-value pairs. It is the same as
the hash table type. The order of elements in a dictionary is undefined, but we can
iterate over the following:
o The key
o The value
o The items (key-value pairs) in a dictionary.
When we have the large amount of data, the dictionary data type is used. Items in
dictionaries are enclosed in curly braces { } and separated by the comma (,). A colon (:)
is used to separate key from value. Values can be assigned and accessed using square
braces ([]).
Example: For dictionary data type.
>>> dic1={1:"First","Second":2}
>>> dic1
{1: 'First', 'Second': 2}
>>> type(dic1)
<class 'dict'>
>>> dic1[3]="Third"
>>> dic1
{1: 'First', 'Second': 2, 3: 'Third'}
>>> dic1.keys()
dict_keys([1, 'Second', 3])
>>> dic1.values()
dict_values(['First', 2, 'Third'])
>>>

b) Example module. How to define module. 6M

Ans A module allows you to logically organize your Python code. Grouping related code 2 M for
into a module makes the code easier to understand and use. A module is a Python module
object with arbitrarily named attributes that you can bind and reference. explanation

Simply, a module is a file consisting of Python code. A module can define functions,
classes and variables. A module can also include runnable code.
Example
The Python code for a module named aname normally resides in a file named
aname.py. Here's an example of a simple module, support.py 2 M for
creating
def print_func( par ): module
print "Hello : ", par
return
To create a module just save the code you want in a file with the file extension .py:
Example
Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
Now we can use the module we just created, by using the import statement: 2 M for
accessing/using
Page No: 15 | 21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Example module
Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("ABC")
c) Write python program to perform following operations on Set (Instead of 6M
Tuple)

i) Create set
ii) Access set Element
iii) Update set
iv) Delete set

Ans # To Create set


S={10,20,30,40,50}
6m for any
# To Access Elements from set suitable
print (S) program

#To add element into set using add method


S.add(60) (If students
print(S) attempted with
“set” give
#To update set using update method marks as per
S.update(['A','B']) marking
print(S) scheme)

#To Delete element from Set using discard() method OR


S.discard(30) (If students
print(S) attempted with
“Tuple”
#To delete element from set using remove() method
S.remove('A') Then
print(S)
2M-create
#To delete element from set using pop() method Tuple
S.pop() 2M-Access
print(S) tuple

output: 2M-delete
{50, 20, 40, 10, 30} Tuple)
{50, 20, 40, 10, 60, 30}
{'B', 50, 20, 'A', 40, 10, 60, 30}
{'B', 50, 20, 'A', 40, 10, 60}
{'B', 50, 20, 40, 10, 60}
{50, 20, 40, 10, 60}

(Any other suitable example can consider)


Page No: 16 | 21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________

*If students have attempted by using “Tuple” then

#To create tuple


tuple1=(10,20,30,40,50)
print (tuple1)
#Access tuple values
print (tuple1[1])
print (tuple1[0:3])
# deleting tuple
del tuple1
print (tuple1)

output:
(10, 20, 30, 40, 50)
20
(10, 20, 30)
Traceback (most recent call last):
File "C:\Users\Vijay Patil\AppData\Local\Programs\Python\Python310\temp.py", line
9, in <module>
print (tuple1)
NameError: name 'tuple1' is not defined. Did you mean: 'tuple'?

6. Attempt any TWO of the following: 12 M

a) Explain mutable and immutable data structures. 6M

Ans The data types in Python are divided in two categories: 3m for mutable
Immutable data types – Values cannot be changed. Immutable data types in Python are data structure
1. Numbers and 3m for
2. String immutable data
3. Tuple structure
Mutable data types – Values can be changed. Mutable data types in Python are:
1. List
2. Dictionaries
3. Sets

1. Numbers
Python supports integers, floats and complex numbers.
An integer is a number without decimal point for example 5, 6, 10 etc.
A float is a number with decimal point for example 6.7, 6.0, 10.99 etc.
A complex number has a real and imaginary part for example 7+8j, 8+11j etc.

Page No: 17 | 21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Example:

# int
num1 = 10
num2 = 100

# float
a = 10.5
b = 8.9

# complex numbers
x = 3 + 4j
y = 9 + 8j

2. String
A string is usually a bit of text (sequence of characters). In Python we use ” (double
quotes) or ‘ (single quotes) to represent a string.
There are several ways to create strings in Python:
1. We can use ‘ (single quotes), see the string str in the following code.
2. We can use ” (double quotes), see the string str2 in the source code below.

3. Triple double quotes “”” and triple single quotes ”’ are used for creating multi-line
strings in Python.
Example:
str = 'beginnersbook'
str2 = "Chaitanya"
# multi-line string
str3 = """Welcome to
Pythonsbook"""

str4 = '''This is a tech


paper'''

3. Tuple
In Python, a tuple is similar to List except that the objects in tuple are immutable which
means we cannot change the elements of a tuple once assigned. On the other hand, we
can change the elements of a list.
To create a tuple in Python, place all the elements in a () parenthesis, separated by
commas. A tuple can have heterogeneous data items, a tuple can have string and list as
data items as well.
Example
# tuple of strings
my_data = ("hi", "hello", "bye")
Page No: 18 | 21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________

# tuple of int, float, string


my_data2 = (1, 2.8, "Hello World")

# tuple of string and list


my_data3 = ("Book", [1, 2, 3])

# tuples inside another tuple


# nested tuple
my_data4 = ((2, 3, 4), (1, 2, "hi"))

4. List
A list is a data type that allows you to store various types data in it. List is a compound
data type which means you can have different-2 data types under a list, for example we
can have integer, float and string items in a same list.
To create a list all you have to do is to place the items inside a square bracket []
separated by comma ,.`
Example:
# list of floats
num_list = [11.22, 9.9, 78.34, 12.0]

# list of int, float and strings


mix_list = [1.13, 2, 5, "beginnersbook", 100, "hi"]

# an empty list
nodata_list = []

5. Dictionaries
Dictionary is a mutable data type in Python. A python dictionary is a collection of key
and value pairs separated by a colon (:), enclosed in curly braces {}.
Left side of the colon(:) is the key and right side of the : is the value.
mydict = {'StuName': 'Ajeet', 'StuAge': 30, 'StuCity': 'Agra'}

6. Sets
Set is an unordered and unindexed collection of items in Python. Unordered means
when we display the elements of a set, it will come out in a random order. Unindexed
means, we cannot access the elements of a set using the indexes like we can do in list
and tuples.
The elements of a set are defined inside curly brackets and are separated by commas.
For example –
myset = {1, 2, 3, 4, "hello"}

b) Design a class student with data members; Name, roll number address. 6M

Page No: 19 | 21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Create suitable method for reading and printing students details.
Ans class Student: 2 M for class
definition
def getStudentDetails(self):
self.rollno=input("Enter Roll Number : ")
self.name = input("Enter Name : ")

self.address =input("Enter Address : ")


def printStudentDetails(self):
2 M to define
print(self.rollno,self.name, self.address) functions
S1=Student()
S1.getStudentDetails()
print("Student Details ")
S1.printStudentDetails ()

Output: 2 M to create
objects
Enter Roll Number : 001
Enter Name : ABC
Enter Address : New York
Student Details :
001 ABC New York
(Any suitable program can consider)
c) Create a parent class named Animals and a child class Herbivorous which will 6M
extend the class Animal. In the child class Herbivorous over side the method feed (
). Create a object
Ans # parent class 2 M to create
class Animal: parent class
# properties
multicellular = True
# Eukaryotic means Cells with Nucleus
eukaryotic = True

# function breath 2 M to define


def breathe(self): child class
print("I breathe oxygen.")

# function feed
def feed(self):
print("I eat food.")
2 M to create
# child class object and call
class Herbivorous(Animal): function
Page No: 20 | 21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________

# function feed
def feed(self):
print("I eat only plants. I am vegetarian.")

herbi = Herbivorous()

herbi.feed()
# calling some other function
herbi.breathe()

Output:
I eat only plants. I am vegetarian.
I breathe oxygen.

Page No: 21 | 21
Sample Paper Questions
Q.1) Attempt any FIVE of the following. (10 Marks)
a) List features of Android Operating System.
b) Define Android Virtual Devices (AVD).
c) Write the directory path where images are stored while developing Android application.
d) List all attributes to develop a simple button.
e) Write the syntax for Intent-Filter tag.
f) Define services in Android operating system.
g) Enlist the steps to publish the Android application.
Q.2) Attempt any THREE of the following. (12 Marks)
a) Describe the Android architecture in detail.
b) Differentiate between JVM and DVM.
c) Explain the activity life cycle.
d) Discuss the need of permissions in Android. Describe the permissions to set system
functionalities like Bluetooth, camera.
Q.3) Attempt any THREE of the following. (12 Marks)
a) Explore the Steps to install and configure Android Studio and SDK.
b) Explain Date and Time picker with its methods.
c) Describe the significance of SQLite database in Android.
d) Discuss Developer console with its purpose.
Q.4) Attempt any THREE of the following. (12 Marks)
a) Observe the following GUI and write an XML file using relative layout to create the same.

1
b) Write a program to display circular progress bar.
c) List sensors in Android and explain any one in detail.
d) Explain zoom control (IN / OUT) with the help of an example.
e) Develop an application to send and receive SMS. (Write ONLY .java and permission tag
in manifest file)
Q.5) Attempt any TWO of the following. (12 Marks)
a) Develop the registration form using the following GUI.

b) Write a program to capture an image using camera and display it.


c) Develop a program to send an email.
Q.6) Attempt any TWO of the following. (12 Marks)
a) Develop an application to store student details like roll no, name, branch, marks,
percentage and retrieve student information using roll no. in SQLite databases.
b) Write a program to locate user’s current location. (Write ONLY .java and manifest file)
c) Develop a simple calculator using table layout.

2
Sample Question Paper Solutions

Q.1) Attempt any FIVE of the following. (10 Marks)


a) List features of Android Operating System.
Ans: 1. Beautiful UI: Android OS basic screen provides a beautiful and intuitive user interface.
2. Connectivity: GSM/EDGE, Bluetooth, Wi-Fi, LTE, NFC and WiMAX.
3. Storage: SQLite, a lightweight relational database, is used for data storage purposes.
4. Web browser: Based on the open-source WebKit layout engine, coupled with Chrome's V8
JavaScript engine supporting HTML5 and CSS3.
5. Multi-touch: Android has native support for multi-touch which was initially made available
in handsets such as the HTC Hero.
6. Multi-tasking: User can jump from one task to another and same time various application can
run simultaneously.
7. Resizable widgets: Widgets are resizable, so users can expand them to show more content or
shrink them to save space.

b) Define Android Virtual Devices (AVD).


Ans: An Android Virtual Device (AVD) is an emulator configuration that allows developers to
test the application by simulating the real device capabilities. We can configure the AVD by
specifying the hardware and software options. AVD manager enables an easy way of creating
and managing the AVD with its graphical interface. We can create as many AVDs as we need,
based on the types of device we want to test for.

c) Write the directory path where images are stored while developing Android
application.
Ans: Images, including photographs and screenshots, which are stored in the DCIM/ and
Pictures/ directories. The system adds these files to the MediaStore. Images table. For example
these are manifest file, java file, activity file and the most important file is resource file. This is
also shows as res file sometimes.

3
We stored our image in the resource file by following steps.
• First we need to download the image from our browser.
• Then we have to copy it from the folder in which the image is stored.
• Then after that we have to simple paste it in the resource
• If we want to put the icon or launcher icon then we have to paste the image in the mipmap
folder and select the shape and size.

d)List all attributes to develop a simple button.


Ans: The following attributes to develop a button in android studio are:
• id: id is an attribute used to uniquely identify a text Button.
• 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 Button. We can set the text in xml as well as in the
java
• textColor: textColor attribute is used to set the text color of a Button. Color value is in the
form of “#argb”, “#rgb”, “#rrggbb”, or “#aarrggbb”
• textSize: textSize attribute is used to set the size of the text on Button. We can set the text size
in sp(scale independent pixel) or dp(density pixel)

e) Write the syntax for Intent-Filter tag.


Ans: An Android Intent is an abstract description of an operation to be performed. It can be
used with startActivity to launch an Activity, broadcastIntent to send it to any interested
BroadcastReceiver components, and startService(Intent) or bindService(Intent,
ServiceConnection, int) to communicate with a background Service.
syntax:
<intent-filter
android:icon=”drawable resource”
android:label=”string resource”
android:priority=”integer” >
</intent-filter>

4
f) Define services in Android operating system.
Ans: Android service is a component that is used to perform operations on the background such
as playing music, handle network transactions, interacting content providers etc. It doesn’t has
any UI (user interface). The service runs in the background indefinitely even if application is
destroyed. Moreover, service can be bounded by a component to perform interactivity and inter
process communication (IPC). There can be two forms of a service. The lifecycle of service can
follow two different paths: started or bound.
1. Started
2. Bound
1)Started Service: A service is started when component (like activity) calls startService()
method, now it runs in the background indefinitely. It is stopped by stopService() method. The
service can stop itself by calling the stopSelf() method.
2) Bound Service: A service is bound when another component (e.g. client) calls bindService()
method. The client can unbind the service by calling the unbindService() method

g) Enlist the steps to publish the Android application.


Ans:
1)Create a Developer Account 6) Provide an appropriate content rating
2) Link our Merchant Account 7) Set up pricing & Distribution
3) Create an App 8) Rollout Release to publish the App
4) Prepare store Listing
5)Upload APK to an App Release

5
Q.2) Attempt any THREE of the following. (12 Marks)
a) Describe the Android architecture in detail.
Ans: Android application is divided into five parts they are as followed:
1.Application
2.Application Framework
3.Andriod Runtime
4.Native Libraries
5.Linux Kernel

1. Linux Kernel: Linux Kernel is the core of the android operating system architecture that
exists at the root of android architecture. It is responsible for device drivers, power management,
memory management, device management, and resource management.
2. Native Libraries: On the top of the Linux kernel, there are Native libraries such as WebKit,
OpenGL, FreeType, SQLite, Media, C runtime library (libs), etc. The WebKit library is
responsible for browser support, SQLite is for database, Free Type for font support, Media for
playing and recording audio and video formats.
3. Android runtime: In the android runtime, there are core libraries and DVM (Dalvik Virtual
Machine) which is responsible for run android applications. DVM is like JVM but it is optimized
for mobile devices. It consumes less memory and provides fast performance.

6
4. Android framework: On the top of Native libraries and android runtime, there is an Android
framework. Android framework includes Android APIs such as UI (User Interface), telephony,
resources, locations, Content Providers(data), and package managers. It provides a lot of classes
and interfaces for android application development.
5. Applications: On top of the Android framework, there are applications. All applications such
as home, contact, settings, games, gallery, browsers are using the android framework that uses
android runtime and libraries. Android runtime and native libraries are using the Linux kernel.

b) Differentiate between JVM and DVM.


Ans:

Sr.no Java Virtual Machine (JVM) Dalvik Virtual Machine (DVM)

1. JVM Supports multiple OS. DVM Supports only Android OS.

2. JVM uses java byte code and runs .class DVM uses its own byte code and runs its
file having JIT (Just in Time). own.dex byte code file.

3. It forms separate classes in separate It forms multiple classes in one.dex file.S


.class files.

4. Its Stack Based VM. Its Register Based VM.

5. Runs on More Memory Runs on Less Memory.

6. Executable file generated is .JAR file. Executable file generated is .APK file.
Multiple instances can be run efficiently.

7. Single instance of JVM is shared with Applicates are given their own instance.
multiple applications.

8. There is a constant pool for every class There is a constant pool for every
application.

7
c) Explain the activity life cycle.
Ans: Android Activity Lifecycle is controlled by 7 methods of android.app.Activity class. The
android Activity is the subclass of ContextThemeWrapper class. An activity is the single screen
in android. It is like window or frame of Java. By the help of activity, you can place all your UI
components or widgets in a single screen.

The 7 lifecycle method of Activity describes how activity will behave at different states.
1. onCreate: called when activity is first created.
2. onStart: called when activity is becoming visible to the user.
3. onResume: called when activity will start interacting with the user.
4. onPause: called when activity is not visible to the user.
5. onStop: called when activity is no longer visible to the user.
6. onRestart: called after your activity is stopped, prior to start.
7. onDestroy: called before the activity is destroyed.

8
d) Discuss the need of permissions in Android. Describe the permissions to set
system functionalities like bluetooth,camera.
Ans: Permission requests protect sensitive information available from a device and should only
be used when access to information is necessary for the functioning of your app. This document
provides tips on ways you might be able to achieve the same (or better) functionality without
requiring access to such information; it is not an exhaustive discussion of how permissions work
in the Android operating system.
For example, suppose your app needs to be able to take pictures with the device camera. Your
app can request the CAMERA permission, which allows your app to access the camera directly.
Your app would then use the camera APIs to control the camera and take a picture. This
approach gives your app full control over the photography process, and lets you incorporate the
camera UI into your app.
Requesting Camera Permissions for Your App:
If your app requires a dangerous permission, check whether your app has been granted access for
the operation that requires the permission:
if (ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted
}
Requesting Bluetooth Permissions for Your App:
In order to use Bluetooth features in your application, you must declare two permissions. The
first of these is BLUETOOTH. You need this permission to perform any Bluetooth
communication, such as requesting a connection, accepting a connection, and transferring data.
<uses-permission android:name=”android.permission.BLUETOOTH” />
<uses-permission android:name=”android.permission.BLUETOOTH_ADMIN” />

9
Q.3) Attempt any THREE of the following. (12 Marks)
a) Explore the Steps to install and configure Android Studio and SDK.
Ans: Follow steps below for complete installation and configuration of Android Studio.
Step 1: Download android studio
You can download Android Studio from this link or go to developer.android.com homepage and
search for downloads. Choose appropriate platform either for windows, mac or linux. Following
are the pre requirements for windows operating system.
Step 2: Run Exe File
Now the next step is to launch .exe file you just download. Following screen will appear. Click
next and select Android SDK checked if you don’t have it already. Better is to leave the default
settings. Make sure Android virtual device is also checked.
Step 3: Choose components
Next step is to accept license and agreement. Click on I Agree
Step 4: Accept license
Next step is to set location of installation. Please make sure your disk has minimum required
space before clicking on Next. For Android Studio installation location must have at least
500MB free space. For Android SDK installation, selected location must have at least 3.25GB
free space.
Step 5: Install location
Next step is to choose the start menu folder, where you want to create shortcut. If you don’t want
to create a shortcut just mark Do not create shortcut.
Step 6: Choose start menu folder And hit Install button. It will start installation.
Step 7: Finish
This informs you installation has completed. Click Finish. Make sure Start Android Studio is
checked. Following splash screen of Android Studio will appear.

10
b) Explain Date and Time picker with its methods.
Ans: Android Date Picker allows you to select the date consisting of day, month and year in
your custom user interface. For this functionality android provides DatePicker and
DatePickerDialog components.
Apart form date attributes, DatePicker object is also passed into this function. You can use the
following methods of the DatePicker to perform further operation.
1. getDayOfMonth(): This method gets the selected day of month
2. getMonth(): This method gets the selected month
3. getYear(): This method gets the selected year
4. setMaxDate(long maxDate): This method sets the maximal date supported by this DatePicker
in milliseconds since January 1, 1970 00:00:00 in getDefault() time zone
5. setMinDate(long minDate): This method sets the minimal date supported by this
NumberPicker in milliseconds since January 1, 1970 00:00:00 in getDefault() time zone
6. setSpinnersShown(boolean shown): This method sets whether the spinners are shown
7. updateDate(int year, int month, int dayOfMonth): This method updates the current date
8. getCalendarView(): This method returns calendar view
9. getFirstDayOfWeek(): This Method returns first day of the week
Android Time Picker allows you to select the time of day in either 24 hour or AM/PM mode.
The time consists of hours, minutes and clock format. Android provides this functionality
through TimePicker class.
Apart form these methods, there are other methods in the API that gives more control over
TimePicker Component. They are listed below.
1. is24HourView(): This method returns true if this is in 24 hour view else false
2. isEnabled(): This method returns the enabled status for this view
3. setCurrentHour(Integer currentHour): This method sets the current hour
4. setCurrentMinute(Integer currentMinute): This method sets the current minute
5. setEnabled(boolean enabled): This method set the enabled state of this view
6. setIs24HourView(Boolean is24HourView): This method set whether in 24 hour or AM/PM
mode
7. setOnTimeChangedListener(TimePicker.OnTimeChangedListener onTimeChangedListener):
This method Set the callback that indicates the time has been adjusted by the user

11
c) Describe the significance of SQLite database in Android.
Ans: Android SQLite is very important lightweight database which comes with android as.
Android SQLuite combines a clean SQL interface with. Very Small memory footprint and decent
speed for android sqlite is "baked into" the Android runtime. So every Android application can
create its own sqluite database sqlite is typical relational database, containing tables index
SQLite Database has method to create, delete, execute sql command & perform other common
relational database management task SQLite is embedded Relational Database Management
system Most relational database are standalone server processes that run independently, and in
cooperation with application that require database access. SQLite is referred to as embedded
because it is provided in I the form of a library that is linked into the application AG such there is
no standalone database Server running in the background. All database operation are handled
internally within the application through calls to function contained in the SQLite library. The
developers of sqlite have placed the technology into the public domain with the result that it is
now q widely deployed database solution, sqlite is Written in the c programming language and as
such, the android SDK provides a Java based "wrapper around the underlying database Interface.
The essentially consist of set of classes that may be utilized within the Java code of an
application to create and manage SQLite based database...
Necessity of SQL lite database:
Self-contained (requires no other components)
Serverless (requires no server backend)
Zero-configuration (does not need to configured for your application)
Transactional (changes within a single transaction in sqlite either occur completely or not at all)
Sqlite is the most widely deployed database engine in the world. The source code for SQLite is
in the public domain.

12
d) Discuss Developer console with its purpose?
Ans: Once we have registered and received-verification by we can e-mail sign in to the google
play android developer console which will be the home for the app publishing operations tools
on google play
Developer profile: The developer profile identifies us to Google play and to the customers
during registration we can provide information for the profile but que can go back at any time to
edit the information and change the settings.
The developer profile contains: The developer’s name, the name we wait to show users on the
Product details page and elsewhere a Google play. The developer contact information show
Google can contact me if needed (this information is not exposed to users). Merchant
information in-app billing information. The developers public key for licensing and in-app
Billing
Multiple User Account:
1. if we are working with a team, we can set up multiple user account to access different parts of
the Developer console.
2. The first account registered is the account owner with Full access to all parts of the console.
3. The owner can add user accounts manage what parts of the console they have access to for
example, an owner can grant users access to publishing and app configuration. but not access to
financial reports.
Linking the merchant hunt:
1. if we are working with a team, we can set up multiple user account to access different parts of
the developer console. The first account registered is the account with full access to all parts of
the console.
2. if we want to tell sell apps or in-app product, you can link the google checkout merchant
account to the developer profile.google paly uses the linked checkout account for financial and
tax identification and month pay out of sales.
The product and listing details:
1. The developer console lets we set up a colourful store front page for the app called the product
details pack. The product details page is the home for app in google play, It i's page users see on
their mobile phone or on the web when they want to learn about the app and download it.

13
2. we can upload custom brand assets screen shots and videos to high light what's great about the
app, and we can provide a localized description add notes about the latest version and more we
can update the store listing of any time even if we don't have a new version of the application.
Uploading and Publishing:
1. From the developer console can quickly upload a release ready APK and publish it when
ready.
2. The app is a draft until publish it at which time Google play makes the product details page &
app available to users, we can unpublish the app at any time.
Distribution controls:
In the Developer console we can manage what countries & territories the app is distributed to
and for some countries. we can choose what carries we want to target.
Selling and pricing the products:
1. The Developer console gives us tool to set prices for the Lapps and in-apps products The app
can either be free to download or priced.
2. if publish the app as free, it must remain free apps can be downloaded by any users in Google
play. If publish it as priced, we can change it to free priced app can be purchased and
downloaded only by users who have registered a form of payment in Google play.
3. if we are selling a priced app or in-app products or subscription the developer console lets set
prices in a large number of different currencies.
App Statistics:
1. The Developer console gives us detailed statics on the install performance of the app we can
view installation of the app measured by unique users, as well as by unique devices.
2. For user Installation, we can view active details install total installs and daily installs and
uninstall for devices, we can see active installs as well as daily install, uninstall upgrade
3. At a glance these charts highlight the app's installation peaks and longer-terms trend which
can correlate to promotion app improvement or other factors.

14
Q.4) Attempt any THREE of the following. (12 Marks)
a) Observe the following GUI and write an XML file using relative layout to
create the same.

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


android:layout_width= “fill_parent”
android:layout_height= “fill_parent” android:paddingLeft= “16dp”
android:paddingRight= “16dp” >
<EditText
android:id= “@+id/name” android:layout_width= “fill_parent”
android:layout_height= “wrap_content” android:hint= “@string/reminder” />
<LinearLayout android:orientation= “vertical” android:layout_width= “fill_parent”
android:layout_height= “fill_parent” android:layout_alignParentStart= “true”
android:layout_below= “@+id/name” android:orientation= “horizontal”>
<EditText
android:id= “@+id/name” android:layout_width= “fill_parent”
android:layout_height= “wrap_content” android:hint= “@string/reminder” />
<EditText
android:id= “@+id/name” android:layout_width= “fill_parent”
android:layout_height= “wrap_content” android:hint= “@string/reminder” />
</LinearLayout>
<Button android:layout_width= “wrap_content” android:layout_height= “wrap_content”
android:text= “New Button” android:id= “@+id/button” /
</RelativeLayout>

15
b) Write a program to display circular progress bar.
Ans:
activity_main.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:gravity="center_horizontal"
android:orientation="vertical"
tools:context=".MainActivity">
<RelativeLayout
android:id="@+id/progress_layout"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_margin="100dp">
<!--progress bar implementation-->
<ProgressBar
android:id="@+id/progress_bar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/circular_shape"
android:indeterminate="false"
android:progressDrawable="@drawable/circular_progress_bar"
android:textAlignment="center" />

16
<!--Text implementation in center of the progress bar-->
<TextView
android:id="@+id/progress_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:gravity="center"
android:text="---"
android:textColor="@color/colorPrimary"
android:textSize="28sp"
android:textStyle="bold" />
</RelativeLayout>
</LinearLayout>
MainActivity.java file:
import android.os.Bundle;
import android.os.Handler;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private ProgressBar progressBar;
private TextView progressText;
int i = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// set the id for the progressbar and progress text

17
progressBar = findViewById(R.id.progress_bar);
progressText = findViewById(R.id.progress_text);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
// set the limitations for the numeric
// text under the progress bar
if (i <= 100) {
progressText.setText("" + i);
progressBar.setProgress(i);
i++;
handler.postDelayed(this, 200);
} else {
handler.removeCallbacks(this);
}
}
}, 200);
}
}
Output:

18
c) List sensors in Android and explain any one in detail.
Ans: List sensors in Android:
TYPE_ ACCELEROMETER
TYPE _AMBIENT_TEMPERATURE
TYPE _GRAVITY
TYPE _LIGHT
TYPE _GYROSCOPE.
TYPE _ PRESSURE
TYPE _PROXIMITY
TYPE _ ROTATION_VECTOR
TYPE _ ORIENTATION
TYPE _ MAGNETIC_FIELD
Motion Sensor: Motion Sensor are useful for monitoring device movement, such as tilt shake
rotation, or swing. The movement is usually a reflection of direct user input (for example, a user
steering a car in a game or user controlling a ball in game) but it can also be a reflection of the
physical environment in which the device is sitting (for example moving with you drive you
while car) in first case you are monitoring motion relative to the devices' frame of reference or
your application's frame or reference in the second case you are monitoring motion relative to the
device's frame of reference or your application's Frame of Reference. Motion sensors are by
themselves are not typically used to monitor device position but they can be used with others
sensor such as the geomagnetic field sensor to determine a device position relative to the world's
frame of reference

d) Explain zoom control (IN / OUT) with the help of an example.


Ans: In Android, Zoom Controls class display simple set of controls that is used for zooming
and provides callback to register for events. Zoom Controls has two buttons ZoomIn and
ZoomOut which are used to control the zooming functionality.
Zoom Controls code in XML:
<ZoomControls android:id=”@+id/simpleZoomControl”
android:layout_width=”wrap_content”

19
android:layout_height=”wrap_content” />
Important Methods Of Zoom Controls: Now let’s discuss some common methods which are
used to configure ZoomControls in our application.
1. hide(): This method is used to hide the ZoomControls from the screen. In some cases we need
to hide the ZoomControls from the screen so that we use this function.
2. show(): This method is used to show the ZoomControls which we hide from the screen by
using hide method.
This example demonstrates how do I Zoom In and Zoom Out an android ImageView.
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″?>
<LinearLayout
xmlns:android=”http://schemas.android.com/apk/res/android” xmlns:tools=”http://schemas.a
ndroid.com/tools”
android:layout_width=”match_parent” android:layout_height=”match_parent”
android:orientation=”vertical” android:padding=”16dp” android:gravity=”center”
tools:context=”.MainActivity”>
<ImageView android:id=”@+id/imageView” android:layout_width=”match_parent”
android:layout_height=”match_parent” android:src=”@drawable/image” />
</LinearLayout>
Step 3: Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector; import android.widget.ImageView;
public class MainActivity extends AppCompatActivity { private ScaleGestureDetector
scaleGestureDetector; private float mScaleFactor = 1.0f;
private ImageView imageView; @Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); imageView=findViewById(R.id.imageView);
scaleGestureDetector = new ScaleGestureDetector(this, new

20
ScaleListener());
}
@Override
public boolean onTouchEvent(MotionEvent motionEvent) {
scaleGestureDetector.onTouchEvent(motionEvent); return true;
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScale(ScaleGestureDetector scaleGestureDetector) { mScaleFactor *=
scaleGestureDetector.getScaleFactor(); mScaleFactor = Math.max(0.1f,
Math.min(mScaleFactor, 10.0f)); imageView.setScaleX(mScaleFactor);
imageView.setScaleY(mScaleFactor);
return true; }
}
}
Step 4 : Add the following code to androidManifest.xml
<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”app.com.
sample”>
<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”>
<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>

21
e) Develop an application to send and receive SMS. (Write ONLY .java and
permission tag in manifest file)
Ans:
MainActivity.java
package com.example.DemoProgram;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.app.Activity;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int MY_PERMISSIONS_REQUEST_SEND_SMS =0 ;
Button sendBtn;
EditText txtphoneNo;
EditText txtMessage;
String phoneNo;
String message;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendBtn = (Button) findViewById(R.id.btnSendSMS);
txtphoneNo = (EditText) findViewById(R.id.editText);
txtMessage = (EditText) findViewById(R.id.editText2);
sendBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendSMSMessage();
}
});
}

22
protected void sendSMSMessage() {
phoneNo = txtphoneNo.getText().toString();
message = txtMessage.getText().toString();
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.SEND_SMS)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode,String permissions[], int[]
grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_SEND_SMS: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent.",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.", Toast.LENGTH_LONG).show();
return;
}
}
}

}
}

23
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.DemoProgram" >
<uses-permission android:name="android.permission.SEND_SMS" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.DemoProgram.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>

24
Q.5) Attempt any TWO of the following. (12 Marks)
a) Develop the registration form using the following GUI.

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">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/iv"
android:src="@drawable/ic_account"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="45dp"

25
android:id="@+id/name"
android:layout_margin="10dp"
android:padding="10dp"
android:hint="Name"
android:drawableLeft="@drawable/ic_name"
android:drawablePadding="10dp"
android:background="@drawable/ic_box"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="45dp"
android:id="@+id/email"
android:layout_margin="10dp"
android:padding="10dp"
android:hint="Email ID"
android:drawableLeft="@drawable/ic_email"
android:drawablePadding="10dp"
android:background="@drawable/ic_box"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="45dp"
android:id="@+id/password"
android:layout_margin="10dp"
android:padding="10dp"
android:hint="Password"
android:drawableLeft="@drawable/ic_password"
android:drawablePadding="10dp"
android:background="@drawable/ic_box"
/>

26
<EditText
android:layout_width="match_parent"
android:layout_height="45dp"
android:id="@+id/confirm"
android:layout_margin="10dp"
android:padding="10dp"
android:hint="Confirm Password"
android:drawableLeft="@drawable/ic_password"
android:drawablePadding="10dp"
android:background="@drawable/ic_box"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="45dp"
android:id="@+id/mobile"
android:layout_margin="10dp"
android:padding="10dp"
android:hint="Enter Mobile"
android:drawableLeft="@drawable/ic_mobile"
android:drawablePadding="10dp"
android:background="@drawable/ic_box"
/>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/male"

27
android:text="Male"
android:layout_marginRight="20dp"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/female"
android:text="Female" />
</RadioGroup>
<Button
android:layout_width="200dp"
android:layout_height="70dp"
android:layout_gravity="center"
android:text="Register"
android:onClick="register"
/>
</LinearLayout>
MainActivity.java
package com.example.q5_a_guiregistrationform;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

28
public void register(View view) {
EditText name = findViewById(R.id.name);
EditText email = findViewById(R.id.email);
EditText password = findViewById(R.id.password);
EditText confirm = findViewById(R.id.confirm);
RadioButton male = findViewById(R.id.male);
RadioButton female = findViewById(R.id.female);
String nameTxt = name.getText().toString();
String emailTxt = email.getText().toString();
String passTxt = password.getText().toString();
String confirmTxt = confirm.getText().toString();
if( ! ( nameTxt.isEmpty() && emailTxt.isEmpty() && passTxt.isEmpty() &&
confirmTxt.isEmpty() )
){
if( male.isChecked() || female.isChecked() ) {
Toast.makeText(this, "Registration Successful", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "Registration Unsuccessful", Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(this, "Registration Unsuccessful", Toast.LENGTH_SHORT).show();
}
}
}

29
b) Write a program to capture an image using camera and display it.
Ans:
Activity-main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.mm\
apk/res/android"
xmlns: tools "http:\\schemas android.com/tools"
android:id="@+id/activity main"
android layout width="match_parent"
android layout. height="match_parent"
android : background="#FFF9c4"
android orientation="vertical"
tools context = "MainActivity">
<Imageview
android & id="@+id/ imageview"
android : layout width ="match_parent"
android:layout_height =" "goodp"
android:layout_centertlarizontal/="true"/>
<Button
android : id = @+id/button"
android:laybut width = "match-Parent"
android:layout_height="wrap_content"
android : text = "click help to capture image using camera"/>
</LinearLayout>
MainActivity Java
package com.example, my camera;
import android.Manifest;
import android.content. Intent
import android.content.pm.PackageManager;
import android.graphics Bitmap;
import android.as Bundle;.

30
import android.view view;
import android.widget. Button;
import android.widget. Imageview;
import android.widget. Toast;
import android.appcompot app AppCompatActivity
import androidx.core app.Acivitycompat;
public class MainActivity extends AppCompatActivity {
Button button;
Imageview imageview.
Intent intent
public static final int RequestPermissionCode = 1;
Protected void onCreate(Bundle savedInstanceState) {
Super.oncreate (savedInstanceState);
setContentView(R.layout.activity.main);
button = (Button) findViewById(R.id. button);
imageview (imageview) findViewById(R.id.imageview)
EnableRuntime Permission();
button setonclickListener ((view) {
intent = new Intent(android.provider mediastore.ACTION_IMAGE_CAPTURE);
StartActivity For
Result ( intent, request code: 7);
} );
}
Protected void onActivityResult(intRequestCode, int resultcode, Intent data) {
if (requestCode==7 && resultcode == RESULT_OK) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data")
imageview.SetImageBitmap (bitmap);
}
}
Public void EnableRuntimepermission () {
if (Activitycompat.shouldshowRequestpermissionRationale)

31
(activity: MainActivity. this, Manifest. Permission.CAMERA)
{
Toast.makeText (context: mainActivity this text "CAMERA permission allow us to access
camera App",
Toast.LENGTH_SHORT_LONG) Show();
}
else
{
ActivityCompat.onRequestPermissions(activity mainActivity.this, new string [] {
Manifest.permission.CAMERA), Requestpermissioncode);
}
}
Public void onRequestPermissionResult(int RC, string per[], int[] PResult) {
Switch (Rc) {
case Request Permission code :
if (PResult.length > 0 && PResult (0] == PackageManager PERMISSION_GRANTED) {
Toast.makeText(context: MainActivity.this text;"
Permission Granted, Now your application can access camera",
Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText( context: MainActivity this, text: "Perimission canceled " +
Toost.LENGTH_LONG).show();
}
break;
}
}
}

32
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8" ?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
Package "com.example.mycamera">
<uses-permission android:name="android.permission CAMERA"/>
<application
android:allow Backup="true"
android:icon="@mipmap/ic launcher"
android:label="Mycamera"
android:roundIcon="@mipmap/ic_launcher-round"
android:supportsRt. ="true"
android:theme="@style/ AppTheme"
tools :Ignore="AllowBackup.GoogleAppIndexingwarning">
<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>

33
c) Develop a program to send an email?
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"
tools:context="in.amitsin6h.sendemail.MainActivity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="20px"
android:paddingRight="20px"
android:orientation="horizontal" >
<EditText
android:id="@+id/etTo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="22dp"
android:layout_marginTop="16dp"
android:ems="10" />
<EditText
android:id="@+id/etSub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/etTo"
android:layout_below="@+id/etTo"
android:layout_marginTop="18dp"
android:ems="10" >
</EditText>

34
<EditText
android:id="@+id/etMsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/etSub"
android:layout_below="@+id/etSub"
android:layout_marginTop="28dp"
android:ems="10"
android:inputType="textMultiLine" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/etTo"
android:layout_alignBottom="@+id/etTo"
android:layout_alignParentLeft="true"
android:text="To:" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/etSub"
android:layout_alignBottom="@+id/etSub"
android:layout_alignParentLeft="true"
android:text="Subject:" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/etMsg"
android:layout_alignBottom="@+id/etMsg"

35
android:layout_alignParentLeft="true"
android:text="Message:" />
<Button
android:id="@+id/btSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/etMsg"
android:layout_below="@+id/etMsg"
android:layout_marginLeft="76dp"
android:layout_marginTop="20dp"
android:text="Send" />
</RelativeLayout>
MainActivity.java
package in.pratik.sendemail;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText etTo, etSub, etMsg;
Button btSend;
String to, subject, message;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etTo = (EditText) findViewById(R.id.etTo);
etSub = (EditText) findViewById(R.id.etSub);
etMsg = (EditText) findViewById(R.id.etMsg);

36
btSend = (Button) findViewById(R.id.btSend);
btSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
to = etTo.getText().toString();
subject = etSub.getText().toString();
message = etMsg.getText().toString();
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[]{ to});
email.putExtra(Intent.EXTRA_SUBJECT, subject);
email.putExtra(Intent.EXTRA_TEXT, message);
//need this to prompts email client only
email.setType("message/rfc822");
startActivity(Intent.createChooser(email, "Choose Email client :"));
}
});
}
}

37
Q.6) Attempt any TWO of the following. (12 Marks)
a) Develop an application to store student details like roll no, name, branch, marks,
percentage and retrieve student information using roll no. in SQLite databases.
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:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tv"
android:text="Insert Data"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/rn"
android:layout_below="@+id/tv"
android:hint="Roll Number"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/name"
android:layout_below="@+id/rn"
android:hint="Name"
/>

38
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/branch"
android:layout_below="@+id/name"
android:hint="Branch"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/marks"
android:layout_below="@+id/branch"
android:hint="Marks"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/percentage"
android:layout_below="@+id/marks"
android:hint="Percentage"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/insert"
android:layout_below="@+id/percentage"
android:text="Insert Data"
android:onClick="insert"
/>
<EditText
android:layout_width="match_parent"

39
android:layout_height="wrap_content"
android:id="@+id/rnView"
android:layout_below="@+id/insert"
android:hint="Roll Number"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/view"
android:layout_below="@+id/rnView"
android:text="View Data"
android:onClick="view"
/>
</RelativeLayout>
MainActivity.java
package com.example.q6_a_databasestudent;
import androidx.appcompat.app.AppCompatActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void insert(View view) {
EditText rn = findViewById(R.id.rn);
EditText name = findViewById(R.id.name);
EditText branch = findViewById(R.id.branch);

40
EditText marks = findViewById(R.id.marks);
EditText percentage = findViewById(R.id.percentage);
DatabaseHandler db = new DatabaseHandler(this);
if(db.addStudent(rn.getText().toString(), name.getText().toString(), branch.getText().toString(),
marks.getText().toString(), percentage.getText().toString())) {
Toast.makeText(getApplicationContext(), "Data Inserted!", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getApplicationContext(), "Student Exists", Toast.LENGTH_SHORT).show();
}
}
public void view(View view) {
EditText rn = findViewById(R.id.rnView);
DatabaseHandler db = new DatabaseHandler(this);
Cursor cursor = db.viewStudent(rn.getText().toString());
if(cursor.getCount() == 0) {
Toast.makeText(getApplicationContext(), "No Records", Toast.LENGTH_SHORT).show();
return;
}
cursor.moveToFirst();
Toast.makeText(getApplicationContext(), cursor.getString(0) + " " + cursor.getString(1) + " " +
cursor.getString(2) + " " + cursor.getString(3) + " " + cursor.getString(4) ,
Toast.LENGTH_SHORT).show();
}
}
DatabaseHandler.java
package com.example.q6_a_databasestudent;
import android.content.*;
import android.database.*;
import android.database.sqlite.*;
public class DatabaseHandler extends SQLiteOpenHelper {

41
DatabaseHandler(Context context) { super(context, "ct2_qb", null, 1); }
@Override
public void onCreate(SQLiteDatabase db) {
String query = "create table students(roll text primary key, name text, branch text, marks text,
percentage text)";
db.execSQL(query);
}
public Boolean addStudent(String rn, String name, String branch, String marks, String
percentage) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("roll", rn);
values.put("name", name);
values.put("branch", branch);
values.put("marks", marks);
values.put("percentage", percentage);
Cursor cursor = db.rawQuery("select * from students where roll = ?", new String[] { rn });
if(cursor.getCount() > 0) { return false; }
db.insert("students", null, values);
return true;
}
public Cursor viewStudent(String rn) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from students where roll = ?", new String[] { rn });
return cursor;
}
@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("drop table if exists student");
}
}

42
b) Write a program to locate user’s current location. (Write ONLY .java and
manifest file)
Ans:
MainActivity.java file
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Looper;
import android.provider.Settings;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
public class MainActivity extends AppCompatActivity {
// initializing
// FusedLocationProviderClient
// object
FusedLocationProviderClient mFusedLocationClient;
// Initializing other items
// from layout file
TextView latitudeTextView, longitTextView;
int PERMISSION_ID = 44;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

43
latitudeTextView = findViewById(R.id.latTextView);
longitTextView = findViewById(R.id.lonTextView);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
// method to get the location
getLastLocation();
}
@SuppressLint("MissingPermission")
private void getLastLocation() {
// check if permissions are given
if (checkPermissions()) {
// check if location is enabled
if (isLocationEnabled()) {
// getting last
// location from
// FusedLocationClient
// object
mFusedLocationClient.getLastLocation().addOnCompleteListener
(new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task)
{
Location location = task.getResult();
if (location == null) {
requestNewLocationData();
} else {

latitudeTextView.setText(location.getLatitude() + "");

longitTextView.setText(location.getLongitude() + "");
}
}
});
} else {
Toast.makeText(this, "Please turn on" + " your location...",
Toast.LENGTH_LONG).show();
Intent intent = new
Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
} else {

44
// if permissions aren't available,
// request for permissions
requestPermissions();
}
}
@SuppressLint("MissingPermission")
private void requestNewLocationData() {

// Initializing LocationRequest
// object with appropriate methods
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(5);
mLocationRequest.setFastestInterval(0);
mLocationRequest.setNumUpdates(1);
// setting LocationRequest
// on FusedLocationClient
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mFusedLocationClient.requestLocationUpdates(mLocationRequest,
mLocationCallback, Looper.myLooper());
}
private LocationCallback mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
Location mLastLocation = locationResult.getLastLocation();
latitudeTextView.setText("Latitude: " + mLastLocation.getLatitude() +
"");
longitTextView.setText("Longitude: " + mLastLocation.getLongitude() +
"");
}
};

// method to check for permissions


private boolean checkPermissions() {
return ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED;

45
// If we want background location
// on Android 10.0 and higher,
// use:
// ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_BACKGROUND_LOCATION) ==
PackageManager.PERMISSION_GRANTED
}
// method to request for permissions
private void requestPermissions() {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSION_ID);
}
// method to check
// if location is enabled
private boolean isLocationEnabled() {
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
|| locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
// If everything is alright then
@Override
public void
onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);

if (requestCode == PERMISSION_ID) {
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
getLastLocation();
}
}
}

@Override
public void onResume() {
super.onResume();

46
if (checkPermissions()) {
getLastLocation();
}
}
}
AndroidManifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.getuserlocation">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_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/Theme.GetUserLocation">
<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>
Output:

47
c) Develop a simple calculator using table layout.
Ans:
activity_main.xml file.
<?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"
android:background="#8BC34A"
android:backgroundTint="@android:color/darker_gray"
tools:context=".MainActivity">
<!-- Text View to display our basic heading of "calculator"-->
<TextView
android:layout_width="194dp"
android:layout_height="43dp"
android:layout_marginStart="114dp"
android:layout_marginLeft="114dp"
android:layout_marginTop="58dp"
android:layout_marginEnd="103dp"
android:layout_marginRight="103dp"
android:layout_marginBottom="502dp"
android:scrollbarSize="30dp"
android:text=" Calculator"
android:textAppearance="@style/TextAppearance.AppCompat.Body1"
android:textSize="30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

48
<!-- Edit Text View to input the values -->
<EditText
android:id="@+id/num1"
android:layout_width="364dp"
android:layout_height="28dp"
android:layout_marginStart="72dp"
android:layout_marginTop="70dp"
android:layout_marginEnd="71dp"
android:layout_marginBottom="416dp"
android:background="@android:color/white"
android:ems="10"
android:onClick="clearTextNum1"
android:inputType="number"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<!-- Edit Text View to input 2nd value-->
<EditText
android:id="@+id/num2"
android:layout_width="363dp"
android:layout_height="30dp"
android:layout_marginStart="72dp"
android:layout_marginTop="112dp"
android:layout_marginEnd="71dp"
android:layout_marginBottom="374dp"
android:background="@android:color/white"
android:ems="10"
android:onClick="clearTextNum2"
android:inputType="number"
app:layout_constraintBottom_toBottomOf="parent"

49
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<!-- Text View to display result -->
<TextView
android:id="@+id/result"
android:layout_width="356dp"
android:layout_height="71dp"
android:layout_marginStart="41dp"
android:layout_marginTop="151dp"
android:layout_marginEnd="48dp"
android:layout_marginBottom="287dp"
android:background="@android:color/white"
android:text="result"
android:textColorLink="#673AB7"
android:textSize="25sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<!-- A button to perform 'sum' operation -->
<Button
android:id="@+id/sum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="292dp"
android:layout_marginEnd="307dp"
android:layout_marginBottom="263dp"
android:backgroundTint="@android:color/holo_red_light"
android:onClick="doSum"

50
android:text="+"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<!-- A button to perform subtraction operation. -->
<!-- A button to perform division. -->
<Button
android:id="@+id/sub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="210dp"
android:layout_marginTop="292dp"
android:layout_marginEnd="113dp"
android:layout_marginBottom="263dp"
android:backgroundTint="@android:color/holo_red_light"
android:onClick="doSub"
android:text="-"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.507" />
<Button
android:id="@+id/div"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="307dp"
android:layout_marginTop="292dp"
android:layout_marginEnd="16dp"

51
android:layout_marginBottom="263dp"
android:backgroundTint="@android:color/holo_red_light"
android:onClick="doDiv"
android:text="/"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<!-- A button to perform multiplication. -->


<Button
android:id="@+id/mul"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="356dp"
android:layout_marginEnd="307dp"
android:layout_marginBottom="199dp"
android:backgroundTint="@android:color/holo_red_light"
android:onClick="doMul"
android:text="x"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<!-- A button to perform a modulus function. -->
<!-- A button to perform a power function. -->
<Button
android:id="@+id/button"
android:layout_width="103dp"

52
android:layout_height="46dp"
android:layout_marginStart="113dp"
android:layout_marginTop="356dp"
android:layout_marginEnd="206dp"
android:layout_marginBottom="199dp"
android:backgroundTint="@android:color/holo_red_light"
android:onClick="doMod"
android:text="%(mod)"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.515" />
<Button
android:id="@+id/pow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="113dp"
android:layout_marginTop="292dp"
android:layout_marginEnd="210dp"
android:layout_marginBottom="263dp"
android:backgroundTint="@android:color/holo_red_light"
android:onClick="doPow"
android:text="n1^n2"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.507" />
</androidx.constraintlayout.widget.ConstraintLayout>

53
MainActivity.java
package com.example.calculator2;
import android.os.Bundle;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.example.calculator2.databinding.ActivityMainBinding;
import android.view.Menu;
import android.view.MenuItem;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration appBarConfiguration;
private ActivityMainBinding binding;
public EditText e1, e2;
TextView t1;
int num1, num2;
public boolean getNumbers() {
//checkAndClear();
// defining the edit text 1 to e1
e1 = (EditText) findViewById(R.id.num1);
// defining the edit text 2 to e2
e2 = (EditText) findViewById(R.id.num2);
// defining the text view to t1
t1 = (TextView) findViewById(R.id.result);
// taking input from text box 1
String s1 = e1.getText().toString();
// taking input from text box 2

54
String s2 = e2.getText().toString();
if(s1.equals("Please enter value 1") && s2.equals(null))
{
String result = "Please enter value 2";
e2.setText(result);
return false;
}
if(s1.equals(null) && s2.equals("Please enter value 2"))
{
String result = "Please enter value 1";
e1.setText(result);
return false;
}
if(s1.equals("Please enter value 1") || s2.equals("Please enter value 2"))
{
return false;
}
if((!s1.equals(null) && s2.equals(null))|| (!s1.equals("") && s2.equals("")) ){

String result = "Please enter value 2";

e2.setText(result);
return false;
}
if((s1.equals(null) && !s2.equals(null))|| (s1.equals("") && !s2.equals("")) ){
//checkAndClear();
String result = "Please enter value 1";
e1.setText(result);
return false;
}
if((s1.equals(null) && s2.equals(null))|| (s1.equals("") && s2.equals("")) ){
//checkAndClear();
String result1 = "Please enter value 1";
e1.setText(result1);
String result2 = "Please enter value 2";
e2.setText(result2);
return false;
}
else {
// converting string to int.
num1 = Integer.parseInt(s1);

// converting string to int.


num2 = Integer.parseInt(s2);
}
return true;

55
}
public void doSum(View v) {
// get the input numbers
if (getNumbers()) {
int sum = num1 + num2;
t1.setText(Integer.toString(sum));
}
else
{
t1.setText("Error Please enter Required Values");
}

}
public void clearTextNum1(View v)
// get the input numbers
e1.getText().clear();
}
public void clearTextNum2(View v) {
// get the input numbers
e2.getText().clear();
}
public void doPow(View v) {
//checkAndClear();
// get the input numbers
if (getNumbers()) {
double sum = Math.pow(num1, num2);
t1.setText(Double.toString(sum));
}
else
{
t1.setText("Error Please enter Required Values");
}
}
// a public method to perform subtraction
public void doSub(View v) {
//checkAndClear();
// get the input numbers
if (getNumbers()) {
int sum = num1 - num2;
t1.setText(Integer.toString(sum));
}
else
{
t1.setText("Error Please enter Required Values");
}
}

56
// a public method to perform multiplication
public void doMul(View v) {
//checkAndClear();
// get the input numbers
if (getNumbers()) {
int sum = num1 * num2;
t1.setText(Integer.toString(sum));
}
else
{
t1.setText("Error Please enter Required Values");
}
}
// a public method to perform Division
public void doDiv(View v) {
//checkAndClear();
// get the input numbers
if (getNumbers()) {
// displaying the text in text view assigned as t1
double sum = num1 / (num2 * 1.0);
t1.setText(Double.toString(sum));
}
else
{
t1.setText("Error Please enter Required Values");
}
// a public method to perform modulus function
public void doMod(View v) {
//checkAndClear();
// get the input numbers
if (getNumbers()) {
double sum = num1 % num2;
t1.setText(Double.toString(sum));
}
else
{
t1.setText("Error Please enter Required Values");
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1 = (EditText) findViewById(R.id.num1);
// defining the edit text 2 to e2
e2 = (EditText) findViewById(R.id.num2);

57
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this,
R.id.nav_host_fragment_content_main);
return NavigationUI.navigateUp(navController, appBarConfiguration)
|| super.onSupportNavigateUp();
}
Output:

58
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
SUMMER – 2023 EXAMINATION
Model Answer – Only for the Use of RAC Assessors

Subject Name: Mobile Application Development Subject Code: 22617


Important Instructions to examiners: XXXXX
1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme.
2) The model answer and the answer written by candidate may vary but the examiner may try to assess the
understanding level of the candidate.
3) The language errors such as grammatical, spelling errors should not be given more Importance (Not applicable for
subject English and Communication Skills.
4) While assessing figures, examiner may give credit for principal components indicated in the figure. The figures
drawn by candidate and model answer may vary. The examiner may give credit for any equivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the assumed constant values may vary and
there may be some difference in the candidate’s answers and model answer.
6) In case of some questions credit may be given by judgement on part of examiner of relevant answer based on
candidate’s understanding.
7) For programming language papers, credit may be given to any other program based on equivalent concept.
8) As per the policy decision of Maharashtra State Government, teaching in English/Marathi and Bilingual (English +
Marathi) medium is introduced at first year of AICTE diploma Programme from academic year 2021-2022. Hence if
the students in first year (first and second semesters) write answers in Marathi or bilingual language (English
+Marathi), the Examiner shall consider the same and assess the answer based on matching of concepts with model
answer.

Q. Sub Answer Marking


No. Q. Scheme
N.

1 Attempt any FIVE of the following: 10 M

a) State Android ECO System. 2M

Ans Android Ecosystem Any 4


points
2M

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


and supply.

Page No: 1 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
• 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
▪ 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.

b) List various tools for android application development 2M

Ans • Android Studio Any


• ADB (Android Debug Bridge)
4 tools
• AVD Manager
• Eclipse 2M
• Fabric
• FlowUp
• GameMaker: Studio
• Genymotion
• Gradle IntelliJ IDEA
c) List various layouts used in android UI design. 2M

Ans • Linear Layout Any


• Absolute Layout
4 layouts
• Frame Layout
• Table Layout 2M
• Relative Layout
d) Name any four attributes of Edit Text control. 2M

Ans android:id Any


android: gravity
android: text 4 attributes
android: hint
2M
android: textColor
android: textSize
android: textStyle
android: background

e) State the use of fragments in android App development. 2M

Ans Android Fragment is the part of activity, it is also known as sub-activity. There can be more Explanation
2M
than one fragment in an activity.

Fragments represent multiple screen inside one activity.

Page No: 2 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
We can create Fragments by extending Fragment class or by inserting a Fragment into our
Activity layout by declaring the Fragment in the activity’s layout file, as
a <fragment> element.

Fragments were added in Honeycomb version of Android i.e API version 11. We can add,
replace or remove Fragment’s in an Activity while the activity is running.
Fragment can be used in multiple activities.
We can also combine multiple Fragments in a single activity to build a multi-plane UI.
We can only show a single Activity on the screen at one given point of time so we were not
able to divide the screen and control different parts separately. With the help of Fragment’s
we can divide the screens in different parts and controls different parts separately

f) Define SMS service in android application development. 2M

Ans SMS Any

• In Android, you can use SmsManager API or devices Built-in SMS application to 4 points
send SMS's
2M
• 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);
g) List different types of sensors used in android. 2M

Ans The android platform supports three broad categories of sensors. 2 M for List

• 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.

Page No: 3 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
2. Attempt any THREE of the following: 12 M

a) Describe android and importance of OHA. 4M

Ans Android Explain


android 2 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 Importance
unified approach to application development for mobile devices which means developers 2M
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.
• 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.

b) Explain Dalvik Virtual Machine and state its importance. 4M

Ans The Dalvik Virtual Machine (DVM) is an android virtual machine optimized for mobile Explain 2
devices. M

Dalvik VM is also a virtual machine that is highly optimized for mobile devices. Importance
2M
Thus, it provides all the three things, that are memory management, high performance as
well as battery life.

It is strictly developed for Android mobile phones.

Page No: 4 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________

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 file. It is a
platform-specific tool.

The Android Assets Packaging Tool (aapt) handles the packaging process.
c) Describe the process of getting the map API key. 4M

Ans Creating API keys Correct


Steps 4
The API key is a unique identifier that authenticates requests associated with your project marks
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

Click on the API key option to generate your API key. After clicking on this option your
API key will be generated
d) Explain multimedia framework in android. 4M

Page No: 5 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Ans Multimedia Framework Proper
Explanation
4 marks

• The android multimedia system includes multimedia applications, multimedia


framework, OpenCore engine and hardware abstract for audio/video input/output
devices.
• The goal of the android multimedia framework is to provide a consistent 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 communicates 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.
• In Media Server guard process, it calls OpenCore multimedia engine to realize the
specific multimedia processing functions. And the OpenCore engine refers to the
PVPlayer and PVAuthor.

3. Attempt any THREE of the following: 12 M

a) Describe various installation steps of android studio and its environment. 4M

Ans Step 1: Correct

Page No: 6 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Go to Android https://developer.android.com/studio to get the Android Studio executable or steps 4
zip file. marks

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 Dark
one. The light one is called the IntelliJ theme whereas the dark theme is called Dracula.
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.

b) Explain Gridview with its attributes with suitable example. 4M

Page No: 7 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Ans GridView : (1 M for
explanation
Android GridView shows items in two-dimensional scrolling grid (rows & columns) and the of
grid items are not necessarily predetermined but they automatically inserted to the layout GridView,1
using a ListAdapter. M for
explaining
GridView Attributes
attributes, 2
Following are the important attributes specific to GridView – M example)
[any two
attributes
Sr.No Attribute & Description should be
considered
1 android:id
for 1 M,
This is the ID which uniquely identifies the layout. any valid
example of
2 android:columnWidth GridView
for 2 M]
This specifies the fixed width for each column. This could be in px, dp,
sp, in, or mm.
3 android:gravity
Specifies the gravity within each cell. Possible values are top, bottom,
left, right, center, center_vertical, center_horizontal etc.
4 android:horizontalSpacing
Defines the default horizontal spacing between columns. This could be
in px, dp, sp, in, or mm.
5 android:numColumns
Defines how many columns to show. May be an integer value, such as
"100" or auto_fit which means display as many columns as possible to
fill the available space.
6 android:stretchMode
Defines how columns should stretch to fill the available empty space, if
any. This must be either of the values −
• none − Stretching is disabled.
• spacingWidth − The spacing between each column is stretched.
• columnWidth − Each column is stretched equally.
• spacingWidthUniform − The spacing between each column is
uniformly stretched..

Page No: 8 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
7 android:verticalSpacing
Defines the default vertical spacing between rows. This could be in px,
dp, sp, in, or mm.

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"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btn"
android:layout_width="fill_parent"

Page No: 9 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
android: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);
}
}

c) Explain text to speech conversion technique in android 4M

Ans Text to Speech converts the text written on the screen to speech like you have written “Hello Proper
World” on the screen and when you press the button it will speak “Hello World”. Text-to- explanation
speech is commonly used as an accessibility feature to help people who have trouble reading
Page No: 10 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
on-screen text, but it’s also convenient for those who want to be read too. This feature has 4 marks
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"/>

Page No: 11 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________

<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;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.Locale;

Page No: 12 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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_FLUSH,null);
}

Page No: 13 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
});

}
}

d) Describe steps for deploying android application on Google Play Store. 4M

Ans Step 1: Create a Developer Account Correct


Before you can publish any app on Google Play, you need to create a Developer Account. steps 4
You can easily sign up for one using your existing Google Account. You’ll need to pay a marks
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 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
Page No: 14 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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


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.

4. Attempt any THREE of the following: 12 M

a) Describe directory structure and its components. 4M

Ans The android project contains different types of app modules, source code files, and resource 1 M for
files. listing of
directory
1. Manifests Folder structure , 3
2. Java Folder M for
explanation
3. res (Resources) Folder )

Page No: 15 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
• Drawable Folder
• Layout Folder
• Mipmap Folder
• Values Folder
4. Gradle Scripts

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

Page No: 16 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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.
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.

b) Develop an android application for Date and Time Picker. 4M

Ans activity_main.xml (2M for


Date Picker
<?xml version="1.0" encoding="utf-8"?> and 2M for
<RelativeLayout Time
Picker)
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="200dp"
android:layout_height="wrap_content"
android:id="@+id/in_time"
android:layout_alignParentLeft="true"

Page No: 17 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SELECT TIME"
android:id="@+id/btn_time"
android:layout_below="@+id/in_time"/>
</RelativeLayout>

MainActivity.java
package com.example.myapplication.timepickerwithspinnermode;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TimePicker;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity implements
View.OnClickListener {
Button btnTimePicker;
EditText txtTime;
private int mHour, mMinute;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnTimePicker=(Button)findViewById(R.id.btn_time);

Page No: 18 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
txtTime=(EditText)findViewById(R.id.in_time);
btnTimePicker.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v == btnTimePicker) {
// Get Current Time
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
// Launch Time Picker Dialog
TimePickerDialog timePickerDialog = new TimePickerDialog(this,
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
txtTime.setText(hourOfDay + ":" + minute);
}
}, mHour, mMinute, false);
timePickerDialog.show();
}
}
}
c) Explain property animation method to animate the properties of view object with example. 4M

Ans A property animation changes a property's (a field in an object) value over a specified length (2 M for
of time. To animate something, you specify the object property that you want to animate, explaining
such as an object's position on the screen, how long you want to animate it for, and what property
values you want to animate between. animation
method, 2
The property animation system lets you define the following characteristics of an animation: M for
example )
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
Page No: 19 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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

Page No: 20 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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"
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" />

Page No: 21 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________

<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

Page No: 22 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
<?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
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">

Page No: 23 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________

<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);

Page No: 24 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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);
}
});

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);
}
});
}
}

Page No: 25 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
d) Describe permissions required for android application development. 4M

Ans The Android security model is primarily based on a sandbox and permission mechanism. (2 Marks
Each application is running in a specific Dalvik virtual machine with a unique user ID for two
assigned to it, which means the application code runs in isolation from the code of all other permission
applications. Therefore, one application has not granted access to other applications’ files. explanation
)
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 Cannot access /
compromise the data of the genuine application. It is mandatory for an application to list all
the resources it will Access during installation. Terms are required of an application, in the
installation process should be user-based or interactive Check with the signature of the
application.
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.
Permissions are divided into several protection levels. The protection level affects whether
runtime permission requests are required. There are three protection levels that affect third-
party apps: normal, signature, and dangerous permissions.
Normal permissions cover areas where your app needs to access data or resources outside
the app’s sandbox, but where there’s very little risk to the user’s privacy or the operation of
other apps. For example, permission to set the time zone is a normal permission. If an app
declares in its manifest that it needs a normal permission, the system automatically grants
the app that permission at install time. The system doesn’t prompt the user to grant normal
permissions, and users cannot revoke these permissions.
Signature permissions: The system grants these app permissions at install time, but only
when the app that attempts to use permission is signed by the same certificate as the app that
defines the permission.
Dangerous permissions: Dangerous permissions cover areas where the app wants data or
resources that involve the user’s private information, or could potentially affect the user’s
stored data or the operation of other apps. For example, the ability to read the user’s contacts
is a dangerous permission. If an app declares that it needs a dangerous permission, the user
must explicitly grant the permission to the app. Until the user approves the permission, your
app cannot provide functionality that depends on that permission. To use a dangerous
permission, your app must prompt the user to grant permission at runtime. For more details
about how the user is prompted, see Request prompt for dangerous permission.

Page No: 26 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________

e) Develop an android application to show current location of an user's car 4M

Ans activity_maps.xml (2 M for


xml code, 1
<fragment xmlns:android="http://schemas.android.com/apk/res/android" M java
xmlns:map="http://schemas.android.com/apk/res-auto" code,
1 M for
xmlns:tools="http://schemas.android.com/tools" permissions
)
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;
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;

Page No: 27 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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

Page No: 28 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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);
}

}
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();

Page No: 29 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);

mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY)
;

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));

Page No: 30 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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) {
}
}
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" />

Note: only the permission line can be written , no entire code is required for manifest file.

5. Attempt any TWO of the following: 12 M

a) Design a employee registration form using UI component. 6M

Ans activity_main.xml (Any


<?xml version="1.0" encoding="utf-8"?> Correct
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" Design -
XML file:
xmlns:tools="http://schemas.android.com/tools"
6M)
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
Page No: 31 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________

<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"
Page No: 32 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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"
android:layout_below="@+id/editpincode"
android:layout_centerHorizontal="true"
android:id="@+id/button" />
</RelativeLayout>

b) Develop an android application for taking student feedback with database 6M


connectivity.
Ans activity_main.xml (Any
correct code
<?xml version="1.0" encoding="utf-8"?> can be
consider
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" 3 Marks for
xmlns:tools="http://schemas.android.com/tools" XML file
android:layout_width="match_parent" and 3 marks
android:layout_height="match_parent" for Java
file)
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"
android:hint="Roll No."

Page No: 33 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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
Page No: 34 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
submitBtn = (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();
}
});

}
}

c) Explain Geocoding and Reverse Geocoding with suitable example. 6M

Ans Geocoding is the process of transforming a street address or other description of a (Geocoding ,
location into a (latitude, longitude) coordinate. Reverse
Geocoding
Reverse geocoding is the process of transforming a (latitude, longitude) coordinate into a Explanation :
(partial) address. 3 M,
Example :
The amount of detail in a reverse geocoded location description may vary, for example 3M)
one might contain the full street address of the closest building, while another might
contain only a city name and postal code.

Page No: 35 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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" />

MapsActivity.java
package example.com.mapexample;

import android.location.Address;
import android.location.Geocoder;
import android.os.Build;
import android.support.v4.app.FragmentActivity;
Page No: 36 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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);

Page No: 37 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________

@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);
}

}
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_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {

LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
}

@Override
public void onConnectionSuspended(int i) {

Page No: 38 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________

@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) {

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();
}

Page No: 39 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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();
}
}

6. Attempt any TWO of the following: 12 M

a) Design an android application to show the list of paired devices by Bluetooth. 6M

Ans activity_main.xml Layout file


<?xml version="1.0" encoding="utf-8"?> : 2M
<RelativeLayout Java File :
xmlns:android="http://schemas.android.com/apk/res/android" 3M
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" Manifest
file : 1M
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"
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"

Page No: 40 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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;
Page No: 41 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
import android.widget.ListView;

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);
}
}

b) Develop an android application for sending Short Message Service (SMS). 6M

Ans activity_main.xml (XML file 3


marks Java
<?xml version="1.0" encoding="utf-8"?> file 3
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" Marks)
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
Page No: 42 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
<TextView
android:id="@+id/fstTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="150dp"
android:text="Mobile No" />
<EditText
android:id="@+id/mblTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10"/>

<TextView
android:id="@+id/secTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Message"
android:layout_marginLeft="100dp" />
<EditText
android:id="@+id/msgTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10" />
<Button
android:id="@+id/btnSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Send SMS" />
</LinearLayout>

MainActivity.java

package in.org.msbte.sendsmsexample;
import android.content.Intent;
import android.net.Uri;
import android.provider.Telephony;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

Page No: 43 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
public class MainActivity extends AppCompatActivity {

private EditText txtMobile;


private EditText txtMessage;
private Button btnSms;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtMobile = (EditText)findViewById(R.id.mblTxt);
txtMessage = (EditText)findViewById(R.id.msgTxt);
btnSms = (Button)findViewById(R.id.btnSend);
btnSms.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try{
SmsManager smgr = SmsManager.getDefault();

smgr.sendTextMessage(txtMobile.getText().toString(),null,txtMessage.getText().toString(),null,null);
Toast.makeText(MainActivity.this, "SMS Sent Successfully",
Toast.LENGTH_SHORT).show();
}
catch (Exception e){
Toast.makeText(MainActivity.this, "SMS Failed to Send, Please try again",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
c) Explain how linear and frame layout is used to design an android application with 6M
suitable example.
Ans LinearLayout (2 M : For
each layout
• Android LinearLayout is a view group that aligns all children in either vertically explanation,
or horizontally. 1 M for
each layout
• Linear layout in Android allow us to arrange components horizontally in a single
example)
column or
vertically in a single row.
• 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
Page No: 44 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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
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.
Page No: 45 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
• 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

Page No: 46 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________

Page No: 47 | 47
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
SUMMER – 2022 EXAMINATION
Subject Name: Mobile Application Development Model Answer Subject Code: 22617
Important Instructions to examiners: XXXXX
1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme.
2) The model answer and the answer written by candidate may vary but the examiner may try to assess the
understanding level of the candidate.
3) The language errors such as grammatical, spelling errors should not be given more Importance (Not applicable for
subject English and Communication Skills.
4) While assessing figures, examiner may give credit for principal components indicated in the figure. The figures
drawn by candidate and model answer may vary. The examiner may give credit for any equivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the assumed constant values may vary and
there may be some difference in the candidate’s answers and model answer.
6) In case of some questions credit may be given by judgement on part of examiner of relevant answer based on
candidate’s understanding.
7) For programming language papers, credit may be given to any other program based on equivalent concept.
8) As per the policy decision of Maharashtra State Government, teaching in English/Marathi and Bilingual (English +
Marathi) medium is introduced at first year of AICTE diploma Programme from academic year 2021-2022. Hence if
the students in first year (first and second semesters) write answers in Marathi or bilingual language (English
+Marathi), the Examiner shall consider the same and assess the answer based on matching of concepts with
model answer.

Q. Sub Answer Marking


No. Q. N. Scheme
Note: As Android programs contain many of the generated code statements from IDE,
while assessing such answers correct logical steps taken to obtain the required output
can be considered.

1 Attempt any FIVE of the following: 10 M

a) List any four features of Android operating system. 2M

Ans Features of Android Operating System: (Any four, ½


1)Storage M for one
2)Multitasking feature)
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
b) Define Dalvik Virtual Machine (DVM). 2M

Page No: 1 | 39
for more study material visit www.diplomachakhazana.in
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Ans Dalvik Virtual Machine is a register-based machine that compiles byte code to get dex (Correct
code and that ensures that a device can run multiple instances efficiently. definition
2 M)
c) List any four folders from directory structure of Android project and 2M
elaborate in one line.
Ans Folders from directory structure: (List of
1)app: The App folder contains three subfolders (manifests, java and res) that make up names of any
our application. four folders :
They are divided so that it should be fairly easy to determine which resources go in which 1 M and
folder. elaboration
2)Manifest: This is where we would put our manifest files. Most Android apps have in one line
single manifest file. But an app may have several manifest files due to application
:1 M)
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 similar
resources 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.

d) List any four attributes of check box. 2M

Ans 1)id (Any four


2)checked attribute, ½
3)gravity M for each)
4)text
5)text color
6)text size
7)text style
8)background
9)padding
e) Draw diagram of activity life cycle. 2M

Page No: 2 | 39
www.diplomachakhazana.in
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Ans (2 M for
correct
diagram)

f) State syntax to display built in zoom control. 2M

Ans a) Built in Zoom control in Google map can be displayed with : Correct
Syntax : 2
UiSettings.setZoomControlsEnabled(true); M)
OR

b) In case, while display Google map by intent, default zoom level can be given in
the form of data as
geo:latitude,longitude?z=zoom
where lat and lag are for location and zoom level is to set initial zoom level which
Page No: 3 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
ranges from 0 to 21.

OR

c) In any normal activity, ZoomControl can be displayed as component by following


syntax :
ZoomControl zoomControls = (ZoomControls) findViewById(R.id.simpleZoomControl);
zoomControls.show()
g) Name two classes used to play audio and video in Android. 2M

Ans 1) MediaPlayer (Any two


class names
2) MediaController 1 M each)

3) AudioManager

2. Attempt any THREE of the following: 12 M

a) Describe Android architecture with diagram. 4M

www.diplomachakhazana.in

Page No: 4 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Ans Diagram: 2M
Explanation:
2M

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

Page No: 5 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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.

• 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.

(i) 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.

(ii) 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:

Page No: 6 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
• 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.

• 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 provides 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.

b) Differentiate between DVM and JVM. 4M

Ans Any 4 points


of
DVM (Dalvik Virtual Machine) JVM (Java Virtual Machine) differences :
It is Register based which is designed to run It is Stack based. 1 M each
on low memory.
DVM uses its own byte code and runs the JVM uses java byte code and runs
“.Dex” file. From Android 2.2 SDK Dalvik “.class” file having JIT (Just In Time).
has got a Just in Time compiler
DVM has been designed so that a device A single instance of JVM is shared
can run multiple instances of the VM with multiple applications.
efficiently. Applications are given their own
instance.
DVM supports the Android operating JVM supports multiple operating
system only. systems.
There is a constant pool for every It has a constant pool for every class.
application.
Here the executable is APK. Here the executable is JAR.

c) List and elaborate steps to deploy an Android application on Google play 4M


store.

Ans Steps to deploy and Android Application on Google Play Store: (List 1 M
and
Step 1: Make a Developer Account Elaboration 3
Step 2: Plan to Sell? Link Your Merchant Account M)
Step 3: Create an App
Step 4: Prepare Store Listing

Page No: 7 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Step 5: Upload APK to an App Release
Step 6: Provide an Appropriate Content Rating
Step 7: Set Up Pricing & Distribution
Step 8: Rollout Release to Publish Your App

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 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
Page No: 8 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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


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.
d) Describe with example, how to create a simple database in SQLite (Assume 4M
suitable data).
(Note : Any other method such as creating subclass of SQLiteOpenHelper class
and overriding and using required methods with relevant example can also be
considered)
Ans This procedure is by openOrCreateDatabase() Description 1
1. The package imported into the application is android.database.sqlite.SQLiteDatabase. M, 1 M for
2. Here the class used is SQLiteDatabase. XML file , 2
3. The method used to create the database or connect to the database is M for Java
openOrCreateDatabse() method. File)
Program:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
Page No: 9 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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) {
sqLiteDatabaseObj = openOrCreateDatabase("AndroidJSonDataBase",
Context.MODE_PRIVATE, null);
} });
}

3. Attempt any THREE of the following: 12 M

a) Write down the steps to install and configure Android studio. 4M

Ans Step 1: Go to https://developer.android.com/android-studio/download to get the Android (4 M for


Studio executable or zip file. appropriate
Page No: 10 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Step 2: steps)
● 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 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.

b) State syntax to create Text View and Image button with any two attributes of each. 4M

Ans Text View: (Syntax of


Syntax : TextView
<TextView and
android:id="@+id/textView1" ImageButton
android:layout_width="<width value>” : 1 M each
android:layout_height="<height_value>" Any two
android:text="<text to be displayed>"/> appropriate
Attributes/Properties of TextView: attributes of
● id: Supply an identifier name of this view, to later retrieve it with each : 1/2 M
View.findViewByID() or Activity.findViewById() each)
● 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
Page No: 11 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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).
● 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.

c) Describe Android service life cycle along with diagram. 4M

Ans ● A service is an application component which runs without direst interaction with (Explanation
the user in the background. 2 M,
● Services are used for repetitive and potentially long running operations, i.e., Diagram
Internet downloads, checking for new data, data processing, updating content 2M)
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”

Page No: 12 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________

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().
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

Page No: 13 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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.

d) State and elaborate the syntax of required class and methods for 4M
Geocoding.
Ans Geocoder: (2 M for
explanation
A class for handling geocoding and reverse geocoding.
and syntax of
Geocoding is the process of transforming a street address or other description of a class, 2 M
location into a (latitude, longitude) coordinate. for
explanation
Reverse geocoding is the process of transforming a (latitude, longitude) coordinate into a and syntax of
(partial) address. The amount of detail in a reverse geocoded location description may any two
vary, for example one might contain the full street address of the closest building, while methods)
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.

Page No: 14 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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)

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.

c. isPresent

Syntax

Page No: 15 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________

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.

4. Attempt any THREE of the following: 12 M

a) Explain with example, code to create GUI using absolute layout (Assume 4M
suitable data).

Ans ● AbsoluteLayout is based on the simple idea of placing each control at an absolute (Explanation
position. We specify the exact x and y coordinates on the screen for each control. 2 M,
This is not recommended for most UI development (in fact AbsoluteLayout is Example 2
currently deprecated) since absolutely positioning every element on the screen makes M)
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)

Page No: 16 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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"
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>

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


(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 activity_main.xml (2M for
<?xml version="1.0" encoding="utf-8"?> correct use
<androidx.constraintlayout.widget.ConstraintLayout of Date
xmlns:android="http://schemas.android.com/apk/res/android" picker
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" 2M for
android:layout_width="match_parent"
Page No: 17 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
android:layout_height="match_parent" correct use
tools:context=".MainActivity"> of
TimePicker)
<TextView
android:id="@+id/tvDate"
android:layout_width="149dp"
android:layout_height="46dp"
android:layout_marginEnd="224dp"
android:layout_marginBottom="312dp"
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"
Page No: 18 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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" />
</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
Page No: 19 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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());
}
});
}
}
c) Describe multimedia framework of Android with diagram. 4M

Ans ● The android multimedia system includes multimedia applications, multimedia (Explanation
frameworks, OpenCore engine and hardware abstract for audio/video input/output 2M,
devices. And the goal of the android multimedia framework is to provide a
reliable interface for java services. The multimedia framework consists of several Diagram 2
core dynamic libraries such as libmediajni, libmedia, libmediaplayservice and so M)
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

Android Multimedia Framework Architecture

Page No: 20 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
● 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.

d) Discuss developer console with at least four features 4M

Ans ● Google Play Developer Console is the platform that Google provides for Google (Any 4
Play and Android developers to publish their apps. relevant
● The Google Play Developer console allows app developers and marketers to features 1M
better understand how their apps are performing in terms of growth, technical each )
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.

e) Write a program to demonstrate declaring and using permissions with any 4M


relevant example.
Ans Permission declaring : 4 M for any
correct
The permissions are declared in AndroidManifest.xml file under Manifest folder. program
Permission can be set by <uses-permission> tag in AndroidManifest.xml.
demonstratin
Example:
Following example is to send SMS. g declaration
(Note: Any other relevant example which uses permissions can be considered) and use of
permissions
AndroidManifest.xml

Page No: 21 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
<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"
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"
Page No: 22 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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);
et2=findViewById(R.id.etmsg);
b1=findViewById(R.id.btnSms);
if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.SEN
D_SMS)!=
PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(MainActivity.this,new
String[]{Manifest.permission.SEND_SMS},100);
}
b1.setOnClickListener(new View.OnClickListener() {
Page No: 23 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
@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();
}
}
});
}
}
5. Attempt any TWO of the following: 12 M

a) Write a program to convert temperature from celcius to farenhite and vice versa 6M
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.)
Ans activity_main.xml XML file:
<?xml version="1.0" encoding="utf-8"?> 2M
<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"
Java Code:
android:layout_width="match_parent"
4M
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" />
Page No: 24 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________

<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);
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();
}
Page No: 25 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
}
});
}
}

b) Write a program to capture an image using camera and display it. 6M


(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 activity_main.xml XML file:
2M
<?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" Java Code:
android:layout_width="match_parent" 4M
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>

Page No: 26 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________

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);

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);
}
}
}

Page No: 27 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
c) Develop and application to send and receive SMS (Design minimal UI as per 6M
your choice. Write XML, java and manifest file)
(Note: Consider appropriate XML file. All attributes are not required. In java
file all imports are not expected. Different relevant login/code can be considered.
Statements showing permissions can be written under AndroidManifest.xml)
Ans Permissions and <receiver> tag required in AndroidManifest.xml XML file:
<uses-permission android:name="android.permission.RECEIVE_SMS" /> 1M
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/> Manifest
<uses-permission android:name="android.permission.WRITE_SMS"/> File:1M
Java Code:
<receiver
4M
android:name=".SmsReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>

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" />
Page No: 28 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________

<EditText
android:id="@+id/etPhno"
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;

Page No: 29 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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.SEN
D_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();
}
}
});
}
@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);
Page No: 30 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
}
}

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();
}
}
}
}

6. Attempt any TWO of the following: 12 M

a) Write a program to implement Android Activity Life Cycle. Use toast messages 6M
to display message through life cycle.
(Note: No XML code is required. In java file all imports are not expected.)
Ans package com.example.p1; Use of any 6
import androidx.appcompat.app.AppCompatActivity; methods of
import android.os.Bundle; Activity life
import android.widget.Toast; cycle : 1 M
public class MainActivity extends AppCompatActivity { each
@Override
Page No: 31 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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();

@Override
protected void onResume() {
super.onResume();
Toast.makeText(getApplicationContext(),"Activity
Resume",Toast.LENGTH_LONG).show();
}
}
b) Develop an application to display Google map with user's current location. 6M
(Note : Consider the appropriate XML file. All attributes are not required.
Page No: 32 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
In java file all imports are not expected. Different relevant logic/code can be
considered.)
Ans act ivity_main.xml XML file:
<?xml version="1.0" encoding="utf-8"?> 1M
<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" Java Code:
android:layout_width="match_parent" 5M
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

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;
Page No: 33 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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)
{
currentlocation=location;

Toast.makeText(getApplicationContext(),currentlocation.getLatitude()+""+current
location.getLongitude(), Toast.LENGTH_SHORT).show();
SupportMapFragment supportMapFragment =
(SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.go
ogle_map);
supportMapFragment.getMapAsync(MainActivity.this);
}
}
});
}
Page No: 34 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
@Override
public void onMapReady(@NonNull GoogleMap googleMap) {
LatLng latLng=new
LatLng(currentlocation.getLatitude(),currentlocation.getLongitude());
MarkerOptions markerOptions=new MarkerOptions().position(latLng)
.title("I am Here");
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,5));
googleMap.addMarker(markerOptions);

}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[]
permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
fetchLastLocation();
}
break;
}
}
}
c) Design UI using table layout to display buttons with 0 9 numbers on it. Even display 6M
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.)
Ans activity_main.xml XML file:
<?xml version="1.0" encoding="utf-8"?> 3M
<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"
Java Code:
android:layout_width="match_parent"
3M
android:layout_height="match_parent"
android:stretchColumns="*"
tools:context=".MainActivity">
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content">

<Button
Page No: 35 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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"
Page No: 36 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
android:id="@+id/button7"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
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);
Page No: 37 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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);
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();
Page No: 38 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
}
});
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
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(); }
});
}
}

Page No: 39 | 39
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
WINTER – 2022 EXAMINATION
Subject Name Mobile Application Development Model Answer Subject Code: 22617
Important Instructions to examiners: XXXXX
1) The answers should be examined by key words and not as word-to-word as given in the model answer
scheme.
2) The model answer and the answer written by candidate may vary but the examiner may try to assess the
understanding level of the candidate.
3) The language errors such as grammatical, spelling errors should not be given more Importance (Not
applicable for subject English and Communication Skills.
4) While assessing figures, examiner may give credit for principal components indicated in the figure. The
figures drawn by candidate and model answer may vary. The examiner may give credit for any equivalent
figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the assumed constant values may
vary and there may be some difference in the candidate’s answers and model answer.
6) In case of some questions credit may be given by judgement on part of examiner of relevant answer based
on candidate’s understanding.
7) For programming language papers, credit may be given to any other program based on equivalent concept.
8) As per the policy decision of Maharashtra State Government, teaching in English/Marathi and Bilingual
(English + Marathi) medium is introduced at first year of AICTE diploma Programme from academic year
2021-2022. Hence if the students in first year (first and second semesters) write answers in Marathi or
bilingual language (English +Marathi), the Examiner shall consider the same and assess the answer based
on matching of concepts with model answer.

Q. Sub Note: As Android programs contain many of the auto generated code statements from IDE, Marking
No. Q. while assessing such answers correct logical steps taken to obtain the required output can be Scheme
N. considered.
Answer

1 Attempt any FIVE of the following: 10 M

a) Define OHA and state goal of OHA. 2M

Ans The OHA is the group that is in charge of the Android smartphones operating system. It was (Define : 1
created by Google. The Open Handset Alliance (OHA) is consortium of multiple companies M, Stating
like Samsung, Sony, Intel and many more to provide services and deploy handsets using goal 1 M)
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.

b) Define Android Virtual Devices (AVD). 2M

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

Page No: 1 | 41
for more study material visit www.diplomachakhazana.in
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
c) State how the APK files are built? 2M

Ans  The javac compiler compiles the java source file into the class file. (For each
 The dx tool takes all the class files of your application and generates a single .dex file which step 1/2 M)
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.

d) Enlist the elements of UI. 2M

Ans Elements of UI. (1/2 mark


for each UI
 EditText element,
 TextView any 4 UI
elements
 ListView
expected)
 GridView
 ScrollView
 ImageView
 ToggleButton
 CheckBox
 RadioButton

OR
Components of UI
 Menu Bar
 Toolbar
 Navigation Bar
 Editor Tabs
 Editor
 Project Explorer
 Status Bar
 Tool Buttons
e) State the uses of Intent in Android. 2M

Ans An Intent is a messaging object you can use to request an action from another app component. (1 M for
Intents are used for facilitating communication between components like Activities, Services each use, 2
and Broadcast Receivers. uses
expected)

f) Name any four methods to get location data in android. 2M

Ans •float distanceTo(Location dest) (1/2 M for


•float getAccuracy() each
•float getBearing() method,
Page No: 2 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
•double getAltitude() any 4
•double getLatitude() methods
•float getSpeed() expected)
•boolean hasAccuracy()
•boolean hasAltitude()
•boolean hasBearing()
•boolean hasBearing()
•boolean hasSpeed()
•void reset()
•void setAccuracy(float accuracy)
•void setAltitude(double altitude)
g) Explain significance of content provider. 2M

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

2. Attempt any THREE of the following: 12 M

a) Describe the different features of Android. 4M

Ans User Interface: The user interface of the Android operating system is straight forward, and (1 M for
these features make it very user friendly. each
feature, 4
Multiple Language Support: Android supports multiple languages in its operating system and features
one can change the language very easily based on one’s requirement, the International expected)
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.
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.

b) Explain features of Android SDK. 4M

Ans Android SDK is a collection of libraries and Software Development tools that are essential for (1 M for
Developing Android Applications. Whenever Google releases a new version or update of each

Page No: 3 | 41
www.diplomachakhazana.in
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Android Software, a corresponding SDK also releases with it. In the updated or new version of feature, any
SDK, some more features are included which are not present in the previous version. Android 4 features
SDK consists of some tools which are very essential for the development of Android expected)
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.

c) Explain the Android security model. 4M

Ans The Android security model is primarily based on a sandbox and permission mechanism. Each 2 M for
application is running in a specific Dalvik virtual machine with a unique user ID assigned to it, explanation
which means the application code runs in isolation from the code of all other applications. , 2 M for
Therefore, one application has not granted access to other applications’ files. explaining
permissions
Android application has been signed with a certificate with a private key Know the owner of , any 2
the application is unique. This allows the author of the application will be identified if needed. permissions
When an application is installed in the phone is assigned a user ID, thus avoiding it from expected)
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 Cannot access / compromise the data of the
genuine application. It is mandatory for an application to list all the resources it will Access
during installation. Terms are required of an application, in the installation process should be
user-based or interactive Check with the signature of the application.
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.
Permissions are divided into several protection levels. The protection level affects whether
runtime permission requests are required. There are three protection levels that affect third-
party apps: normal, signature, and dangerous permissions.
Normal permissions: Normal permissions cover areas where your app needs to access data or
resources outside the app’s sandbox, but where there’s very little risk to the user’s privacy or

Page No: 4 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
the operation of other apps. For example, permission to set the time zone is a normal
permission. If an app declares in its manifest that it needs a normal permission, the system
automatically grants the app that permission at install time. The system doesn’t prompt the user
to grant normal permissions, and users cannot revoke these permissions.
Signature permissions: The system grants these app permissions at install time, but only when
the app that attempts to use permission is signed by the same certificate as the app that defines
the permission.
Dangerous permissions: Dangerous permissions cover areas where the app wants data or
resources that involve the user’s private information, or could potentially affect the user’s
stored data or the operation of other apps. For example, the ability to read the user’s contacts is
a dangerous permission. If an app declares that it needs a dangerous permission, the user must
explicitly grant the permission to the app. Until the user approves the permission, your app
cannot provide functionality that depends on that permission. To use a dangerous permission,
your app must prompt the user to grant permission at runtime. For more details about how the
user is prompted, see Request prompt for dangerous permission.
d) Elaborate the need of permissions in Android. Explain the permissions to set 4M
system functionalitics like SEND-SMS, bluetooth.

Ans The purpose of a permission is to protect the privacy of an Android user. Android apps must(2 M for
request permission to access sensitive user data (such as contacts and SMS), as well as certain
explanation
system features (such as camera and internet). Depending on the feature, the system might grant
of need, 1
the permission automatically or might prompt the user to approve the request. M each for
explaining
 android. permission. SEND_SMS permissions
Allows the app to send SMS messages. This may result in unexpected charges. of Sms and
Malicious apps may cost you money by sending messages without your confirmation. bluetooth)

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" />

3. Attempt any THREE of the following: 12 M

a) Explain data and time picker with its method. 4M

Ans Date Picker: Date picker


In Android, DatePicker is a widget used to select a date. It allows to select date by day, month (any two
and year in our custom UI (user interface). If we need to show this view as a dialog then we methods) 2
have to use a DatePickerDialog class. M and time
Methods of DatePicker:
picker (any
Page No: 5 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
1. setSpinnersShown(boolean shown): This method is used to set whether the spinner of the two
date picker in shown or not. In this method you have to set a Boolean value either true or false. methods) 2
True indicates spinner is shown, false value indicates spinner is not shown. Default value for M
this function is true.
Syntax:
DatePicker simpleDatePicker = (DatePicker)findViewById(R.id.simpleDatePicker);
simpleDatePicker.setSpinnersShown(false);
2. getDayOfMonth(): This method is used to get the selected day of the month from a date
picker.
This method returns an integer value.
DatePicker simpleDatePicker = (DatePicker) findViewById(R.id.simpleDatePicker);
int day = simpleDatePicker.getDayOfMonth();
3. getMonth(): This method is used to get the selected month from a date picker. This method
returns an integer value.
DatePicker simpleDatePicker = (DatePicker)findViewById(R.id.simpleDatePicker);
int month = simpleDatePicker.getMonth();
4. getYear(): This method is used to get the selected year from a date picker. This method
returns an integer value.
DatePicker simpleDatePicker = (DatePicker)findViewById(R.id.simpleDatePicker);
int year = simpleDatePicker.getYear();
5. getFirstDayOfWeek(): This method is used to get the first day of the week. This method
returns an integer value.
DatePicker simpleDatePicker = (DatePicker)findViewById(R.id.simpleDatePicker);
int firstDay=simpleDatePicker.getFirstDayOfWeek();
TimePicker:
In Android, TimePicker is a widget used for selecting the time of the day in either AM/PM
mode or 24 hours mode. The displayed time consist of hours, minutes and clock format. If we
need to show this view as a Dialog then we have to use a TimePickerDialog class.
Methods of TimePicker:
1. setCurrentHour(Integer currentHour): This method is used to set the current hours in a
time picker.
setHour(Integer hour): setCurrentHour() method was deprecated in API level 23. From api
level 23 we have to use setHour(Integer hour). In this method there is only one parameter of
integer type which is used to set the value for hours.
TimePicker simpleTimePicker=(TimePicker)findViewById(R.id.simpleTimePicker);
simpleTimePicker.setCurrentHour(5);
simpleTimePicker.setHour(5);
2. setCurrentMinute(Integer currentMinute): This method is used to set the current minutes
in a time picker. setMinute(Integer minute): setCurrentMinute() method was deprecated in API
level 23. From api level 23 we have to use setMinute(Integer minute). In this method there is
only one parameter of integer type which set the value for minutes.
TimePicker simpleTimePicker=(TimePicker)findViewById(R.id.simpleTimePicker);
simpleTimePicker.setCurrentMinute(35);
simpleTimePicker.setMinute(35);
4. getCurrentMinute(): This method is used to get the current minutes from a time picker.

www.diplomachakhazana.in Page No: 6 | 41


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
getMinute(): getCurrentMinute() method was deprecated in API level 23. From api level 23
we have to use getMinute(). This method returns an integer value.
TimePicker simpleTimePicker = (TimePicker)findViewById(R.id.simpleTimePicker);
int minutes = simpleTimePicker.getCurrentMinute();
int minutes = simpleTimePicker.getMinute();
5. setIs24HourView(Boolean is24HourView): This method is used to set the mode of the
Time picker either 24 hour mode or AM/PM mode. In this method we set a Boolean value
either true or false. True value indicate 24 hour mode and false value indicate AM/PM mode.
TimePicker simpleTimePicker = (TimePicker)findViewById(R.id.simpleTimePicker);
simpleTimePicker.setIs24HourView(true);
6. is24HourView(): This method is used to check the current mode of the time picker. This
method returns true if its 24 hour mode or false if AM/PM mode is set.
TimePicker simpleTimePicker = (TimePicker)findViewById(R.id.simpleTimePicker);
Boolean mode=simpleTimePicker.is24HourView();
7.setOnTimeChangedListener(TimePicker.OnTimeChangedListener
onTimeChanged(): This method is used to set the callback that indicates the time has been
adjusted by the user.
onTimeChanged(TimePicker view, int hourOfDay, int minute) is an override function of this
listener in which we have three parameters first is for TimePicker, second for getting hour of
the day and last is for getting the minutes after changing the time of the time picker.
TimePicker simpleTimePicker = (TimePicker)findViewById(R.id.simpleTimePicker);
simpleTimePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
}
});
b) Explain the steps to install and configure Android studio and SDK. 4M

Ans  Download the latest version of Android Studio from above URL and launch Android 4 M for
Studio.exe file by double clicking on it. steps
 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 selected all 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

Page No: 7 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
settings from previous version of studio. In case 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
 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
c) Explain the activity life cycle. 4M

Ans Diagram 2
M
explanation
2M

Activities have a predefined life-cycle methods as follows:

Page No: 8 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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.

d) Explain the steps to deploy app on Google Play Store. 4M

Ans Step 1: Create a Developer Account 4 M for all


Before you can publish any app on Google Play, you need to create a Developer Account. You steps
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


After creating application by clicking on ‘Create Application'. Here you have to select your
app’s default language from the drop-down menu and 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.
Page No: 9 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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


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.

Page No: 10 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________

4. Attempt any THREE of the following: 12 M

a) Explain the fundamentals of Ul design in detail. 4M

Ans 1. Views: 1 M for


• The basic building block for user interface in Android is a View, which is created from the each
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
b) Write a program to display a rectangular progress bar. 4M

Ans Xml File: xml file


<?xml version="1.0" encoding="utf-8"?> 2M,
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" java file 2
android:layout_width="match_parent" M
android:layout_height="match_parent"
tools:context=".MainActivity">
Page No: 11 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________

<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) {
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() {

Page No: 12 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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();
}
}
c) Explain Android system architecture in detail. 4M

Ans Diagram

2 M,

Explanation
2M

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.
Page No: 13 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
• 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.
• 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.
(i) 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.
(ii) 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.
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.
• Linux Kernel is responsible for 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.
d) Explain the procedure of Geo-coding and reverse Geo-coding. 4M

Ans Geo-Coding: geocoding 2


• If we know the latitude and longitude of a location, we can find out its address using a process M
known as Geocoding. Google Maps in Android supports this via the Geocoder class.

Page No: 14 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
• The following code shows how we can find out the address of a location we have just touched and
using the getFromLocation() method: reverse
classMapOverlay extends com.google.android.maps.Overlay geocoding 2
M
{
@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;
}
}

Page No: 15 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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 {
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.
e) Develop an application to send and receive SMS (Write only Java and 4M
permission tag in manifest file).
Ans Permissions and <receiver> tag required in AndroidManifest.xml Manifest
<uses-permission android:name="android.permission.RECEIVE_SMS" /> File:1M
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/> Java Code:
<uses-permission android:name="android.permission.WRITE_SMS"/> 3M

<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
(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;

Page No: 16 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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_S
MS)!=
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();
}
}
});
}
@Override
Page No: 17 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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();
}
}
}
}

5. Attempt any TWO of the following: 12 M

Page No: 18 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
a) Develop a program to send and receive an Email. 6M

Ans Program to send Email Any correct


activity_main.xml logic
<?xml version="1.0" encoding="utf-8"?> program
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" should be
xmlns:tools="http://schemas.android.com/tools" considered,
android:layout_width="match_parent" 3M for
android:layout_height="match_parent" send logic,
tools:context=".MainActivity"> 3M for
receive
<EditText logic
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"
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"
Page No: 19 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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);

Page No: 20 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
// attach setOnClickListener to button with Intent object define in it
button.setOnClickListener(view -> {
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();

Page No: 21 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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;
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" />
Page No: 22 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
</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>
b) Develop a program for providing bluetooth connectivity. 6M

Ans activity_main.xml Layout file


<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android" : 2M
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" Java File :
android:layout_height="match_parent" 3M
tools:context=".MainActivity" >
Manifest
file : 1M
<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" />

Page No: 23 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________

<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"
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;
Page No: 24 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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);
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 DISCOVERA
BLE",
Toast.LENGTH_LONG);

Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVER


ABLE);
startActivityForResult(enableBtIntent, REQUEST_DISCOVERABLE_BT);

}
}
});
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Page No: 25 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
mBluetoothAdapter.disable();
//out.append("TURN_OFF BLUETOOTH");
Toast.makeText(getApplicationContext(), "TURNING_OFF BLUETOOTH", Toast.LENGT
H_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;
}

}
c) Develop a program to implement 6M

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"?> Correct


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" Logics for
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" ListView :
android:layout_width="match_parent" 2M
android:layout_height="match_parent"
GridView :
android:orientation="vertical"
2M
tools:context=".MainActivity">
ImageView
<ListView : 2M
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"

Page No: 26 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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;

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);

}
}
6. Attempt any TWO of the following: 12 M

Page No: 27 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
a) Develop an application to store customer's details like, customer-id, customer-name, 6M
mobile number, address, pin-code and retrieve customer information using customer-id
in SQLite databases.
(Any other relevant logic can be considered)
Ans activity_main.xml Layout File
<?xml version="1.0" encoding="utf-8"?> : 1M
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" Java File :
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" Correct
android:layout_height="match_parent" Logics for
tools:context=".MainActivity">
Create
table : 1M
<TextView Insertion of
android:text="Insert Customer Details" record : 2M
android:layout_width="wrap_content" Retrival of
android:layout_height="wrap_content" data : 2M
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"/>
Page No: 28 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________

<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="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"/>

Page No: 29 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
<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;
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
Page No: 30 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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);
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();
} }); } }
b) Write a program to find the direction from user's current location to MSBTE, 6M
Bandra. (Write only Java and manitest file).
(Note : Any other relevant logic to get the required output can also be considered.)

Page No: 31 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Ans AndroidManifest.xml Manifest
file :2M
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" Java File :
package="com.example.msbte.google_map_currentlocationroute"> 4M

<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;

Page No: 32 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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;
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 */
Page No: 33 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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();

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";
Page No: 34 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
// 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() {
@Override
public void onError(DexterError error) {
Toast.makeText(getApplicationContext(), "Some Error! ",
Toast.LENGTH_SHORT).show();
}
})
Page No: 35 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
.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()));
Page No: 36 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
} 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()) + "," +
Page No: 37 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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);
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;
} }}
c) Develop a simple calculator using relative layout. 6M

Ans activity_main.xml Use of


<?xml version="1.0" encoding="utf-8"?> Relative
<RelativeLayout Layout
xmlns:android="http://schemas.android.com/apk/res/android" with
appropriate
xmlns:app="http://schemas.android.com/apk/res-auto" attributes :
xmlns:tools="http://schemas.android.com/tools" 3M
android:layout_width="match_parent"
android:layout_height="match_parent" Logic for
simple
tools:context=".MainActivity">
calculator
with basic
<TextView arithmetic
android:id="@+id/heading" operations :
android:layout_width="wrap_content" 3M
android:layout_height="wrap_content"
android:text=" Calculator"
android:layout_centerHorizontal="true"
android:textSize="30dp" />

Page No: 38 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
<EditText
android:id="@+id/num1"
android:layout_below="@+id/heading"
android:layout_width="match_parent"
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
Page No: 39 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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>

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() {
Page No: 40 | 41
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
@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() {
@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));
}
});
}
}

Page No: 41 | 41
Sample Question Paper:
Scheme – I
Programme Name: Computer/Information Technology Engineering
Programmecode:CO/IF
Semester:VI Sem
22619
Course Title: Web Based Application development with PHP
Marks :70 Time:3Hrs.

Instructions:
(1)All questions are compulsory.
(2) Illustrate your answers with neat sketches wherever necessary.
(3) Figures to the right indicate full marks.
(4) Assume suitable data if necessary.
(5) Preferably, write the answers in sequential order.

Q.1) Attempt anyFIVEof the following. (10 Marks)


a) List any four advantages of PHP?
b) State the use of str_word_count along with its syntax.
c) Define serialization.
d) Write the syntax for creating Cookie.
e) Write syntax of Connecting PHP Webpage with MySQL`
f) Define GET and POST methods.
g) State the use of “$” sign in PHP.

Q.2) Attempt any THREE of the following. (12 Marks)


a) Write a program using foreach loop.
b) Explain Indexed and Associative arrays with suitable example.
c) Define Introspection and explain it with suitable example.
d) Differentiate between Session and Cookies.

Q.3) Attempt any THREE of the following. (12 Marks)


a) Differentiate between implode and explode functions.
b) Write a program for cloning of an object.
c) Define session and explain how it works.
d) Write Update and Delete operations on table data.

Q.4) Attempt any THREE of the following. (12 Marks)


a) State the variable function.Explain it with example.
b) Explain the concept of Serialization with example.
c) Answer the following:
i) Get session variables ii) Destroy session

d) ExplainInserting and Retrieving the query result operations.


e) Create a web page using GUI components.
Q.5) Attempt any TWO of the following. (12 Marks)
a) Explain any three data types used in PHP.
b) Write a program to connect PHP with MySQL.
c) Explain the concept of overriding in detail.

1
Q.6) Attempt any TWO of the following. (12 Marks)
a) Explain web page validation with example.
b) Write a program to create PDF document in PHP.
c) Elaborate the following:
i) __call() ii) mysqli_connect()

2
Sample Test Paper I
MSBTE Outcome based Curriculum
Scheme – I

Programme Name: ComputerEngineering/Information Technology


Programme Code: CO/IF 22619
Semester: Sixth
Course: Web Based Application development with PHP
Marks: 20 Time: 1 hour
Instructions:All questions are compulsory
1. Illustrate your answers with neat sketches wherever necessary
2. Figures to the right indicate full marks
3. Assume suitable data if necessary
4. Preferably, write the answers in sequential order

Q1. Attempt Any FOUR (08 Marks)


a) Define the use of foreach loop in php.
b) Differentiate between Implode and Explode functions.
c) Write the use of array_flip()
d) Define ImageColorAllocate() function along with itssyntax
e) List out the advantages of PHP.

Q2. Attempt any THREE (12 Marks)


a) Describe the creation of PDF document in PHP.
b) Explain the following string functions with example.
i) str_replace() ii) ucwords() iii) strlen() iv) strtoupper()
c) Explain the concept of anonymous function in detail.
d) Write a program to create a filled rectangle.

3
Sample Test Paper II
MSBTE Outcome based Curriculum
Scheme – I

Programme Name: ComputerEngineering/Information Technology


Programme Code: CO/IF 22619
Semester: Sixth
Course: Web Based Application development with PHP
Marks: 20 Time:1 hour
Instructions:All questions are compulsory
1. Illustrate your answers with neat sketches wherever necessary
2. Figures to the right indicate full marks
3. Assume suitable data if necessary
4. Preferably, write the answers in sequential order.

Q1. Attempt Any FOUR (08 Marks)


a) Define the uses of serialize() and unserialize().
b) State the use of cloning of an object.
c) Define theGET and POST methods.
d) Define the following terms:
i) Start a session ii) Destroy a session
e) List out the database operations.

Q2. Attempt any THREE (12 Marks)


a) Describe the Introspection method in detail
b) Answer the following
i)Use of cookies ii) how to set the cookie iii) how to modify iv) how to delete the cookies.
c) Describe the web page validation with suitable example.
d) Write a program by using mysqli_connect().

4
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

Important Instructions to examiners:


1) The answers should be examined by key words and not as word-to-word as given in the
model answer scheme.
2) The model answer and the answer written by candidate may vary but the examiner may try
to assess the understanding level of the candidate.
3) The language errors such as grammatical, spelling errors should not be given more
Importance (Not applicable for subject English and Communication Skills.
4) While assessing figures, examiner may give credit for principal components indicated in the
figure. The figures drawn by candidate and model answer may vary. The examiner may give
credit for anyequivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the assumed
constant values may vary and there may be some difference in the candidate’s answers and
model answer.
6) In case of some questions credit may be given by judgement on part of examiner of relevant
answer based on candidate’s understanding.
7) For programming language papers, credit may be given to any other program based on
equivalent concept.
8) As per the policy decision of Maharashtra State Government, teaching in English/Marathi
and Bilingual (English + Marathi) medium is introduced at first year of AICTE diploma
Programme from academic year 2021-2022. Hence if the students in first year (first and
second semesters) write answers in Marathi or bilingual language (English +Marathi), the
Examiner shall consider the same and assess the answer based on matching of concepts
with model answer.

Q.No Sub Answer Marking


Q.N. Scheme
1. Attempt any FIVE of the following: 10
a) Describe advantages of PHP. 2M
Ans.  Easy to Learn ½ M each,
 Familiarity with Syntax any four
 PHP is an open-source web development language, it‟s advantages
completely free of cost.
 PHP is one of the best user-friendly programming languages in
the industry.
 PHP supports all of the leading databases, including MySQL,
ODBC, SQLite and more
 effective and efficient programming language
 Platform Independent
 PHP uses its own memory space, so the workload of the server
and loading time will reduce automatically, which results into
the faster processing speed.

www.diplomachakhazana.in Page 1 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

 PHP is one of the most secure ways of developing websites and


dynamic web applications. PHP has multiple layers of security
to prevent threats and malicious attacks.
b) What is array? How to store data in array? 2M
Ans. 1. An array in PHP is an ordered map where a map is a type that
associates values to keys.
1M for
2. Ways to store an array. definition
Using array variable 1M to store
<?php data
$array_fruits= array('Apple', 'Orange', 'Watermelon', 'Mango');
?>
OR
Using array indices
<?php
$array= [];// initializing an array
$array[] = 'Apple';
$array[] = 'Orange';
$array[] = 'Watermelon;
$array[] = „Mango;
print_r($array);
?>

c) List types of inheritance. 2M


Ans. 1. Single Level Inheritance 2M for any
2. Multiple Inheritance four
3. Multiple Inheritance (Interfaces) correct
4. Hierarchical Inheritance names of
inheritance

d) How can we destroy cookies? 2M


Ans. We can destroy the cookie just by updating the expire-time value 1M for
of the cookie by setting it to a past time using the explanatio
setcookie() function. n
1M for
Syntax: setcookie(name, time() - 3600); syntax/
example
e) List any four data types in MYSQL 2M

Page 2 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

Ans. (Any correct data types can also be considered)


Data Type Size Description

CHAR(size) Maximum 255 characters Fixed-length 2M for


Character strings. any four
VARCHAR Maximum 255 characters Variable length correct
(size) string types
TEXT(size) Maximum size of 65,535 Here size is the
characters. number of
characters to
store.
INT(m)/ Signed values range from - Standard integer
INTEGER( 2147483648 to value.
m) 2147483647. Unsigned
values range from 0 to
4294967295. (4 bytes)
DATE() (3 bytes) Displayed as Displayed as
'yyyy-mm-dd'. 'yyyy-mm-dd'
DATETIM Values range from '1000- (8 bytes)
E() 01-01 00:00:00' to '9999- Displayed as
12-31 23:59:59'. 'yyyy-mm-
ddhh:mm:ss'.
f) Write syntax of PHP. 2M
Ans. A PHP script starts with the tag <?php and end with tag ?>. 2M for
The PHP delimiter in the following example simply tells the PHP correct
engine to treat the enclosed code block as PHP code, rather than syntax
simple HTML
Syntax:
<?php
echo „Hello World‟;
?>
g) How to create session variable in PHP? 2M
Ans.  Session variable can be set with a help of a PHP global variable: 1M for
$_SESSION. explanatio
 Data in the session is stored in the form of keys and values pair. n
 We can store any type of data on the server, which include 1M for
arrays and objects. correct
 For example, we want to store username in the session so it can syntax /
be assessed whenever it is required throughout the session. example

www.diplomachakhazana.in Page 3 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

<?php
session_start();
$_SESSION["username"] = "abc";
?>
2. Attempt any THREE of the following: 12
a) Write down rules for declaring PHP variable 4M
Ans. a. A variable starts with the $ sign, followed by the name of the 1M for
variable. each
b. A variable name must start with a letter or the underscore correct
character. rule, any
c. A variable name should not contain spaces. If a variable name is four rules
more than one word, it should be separated with an underscore can be
($first_name), or with capitalisation ($firstName). considered
d. Variables used before they are assigned have default values.
e. A variable name cannot start with a number.
f. A variable name can only contain alpha-numeric characters (A-
Z, a-z) and underscores.
g. Variable names are case-sensitive ($name and $NAME are two
different variables)
h. Variables can, but do not need, to be declared before
assignment. PHP automatically converts the variable to the
correct data type, depending on its value.
i. Variables in PHP do not have intrinsic types - a variable does
not know in advance whether it will be used to store a number
or a string of characters
b) Write a program to create associative array in PHP. 4M
Ans. <?php 4M for any
$a = array("sub1"=>23,"sub2"=>23,"sub3"=>12,"sub4"=>13); correct
var_dump($a); code for
echo "<br>"; associative
foreach ($a as $x) array
echo "$x<br>";
echo "using for loop<br>";
$aLength= count($a);
echo "Count of elements=$aLength<br>";
for ($i=0;$i<$aLength;$i++)
echo "$a[$i]<br>";
echo "array function extract<br>";
extract($a);

Page 4 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

echo $a1."<br>".$a2."<br>".$a3."<br>".$a4."<br>";
?>
c) Define Introspection and explain it with suitable example. 4M
Ans.  Introspection in PHP offers the useful ability to examine an 1M for
object's characteristics, such as its name, parent class (if any) definition
properties, classes, interfaces and methods. 1M for
 PHP offers a large number functions that can be used to explanatio
accomplish the above task. n
 Following are the functions to extract basic information about 2M for any
classes such as their name, the name of their parent class etc. correct
example

Example:
<?php
class Test
{
function testing_one()
{
return(true);
}
function testing_two()
{
return(true);
}
function testing_three()

Page 5 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

{
return(true);
}
//Class "Test" exist or not
if (class_exists('Test'))
{
$t = new Test();
echo "The class is exist. <br>";
}
else
{
echo "Class does not exist. <br>";
}
//Access name of the class
$p= new Test();
echo "Its class name is " ,get_class($p) , "<br>";
//Aceess name of the methods/functions
$method = get_class_methods(new Test());
echo "<b>List of Methods:</b><br>";
foreach ($method as $method_name)
{
echo "$method_name<br>";
}
?>
Output :
The class is exist.
Its class name is Test
List of Methods:
testing_one
testing_two
testing_three
d) Write difference between get() and post() method of form (Any 4M
four points)
Ans. HTTP GET HTTP POST 1M for
In GET method we cannot send In POST method large each
large amount of data rather amount of data can be correct
limited data is sent because the sent because the request differentiat
request parameter is appended parameter is appended ion, any
into the URL. into the body. four points

Page 6 / 29

www.diplomachakhazana.in
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

GET request is comparatively POST request is to be


better than Post so it is used comparatively less better considered
more than the Post request. than Get so it is used less
than the Get request.
GET request is comparatively POST request is
less secure because the data is comparatively more
exposed in the URL bar. secure because the data is
not exposed in the URL
bar.
Request made through GET Request made through
method are stored in Browser POST method is not
history. stored in Browser history.
GET method request can be POST method request
saved as bookmark in browser. cannot be saved as
bookmark in browser.
Request made through GET Request made through
method are stored in cache POST method are not
memory of Browser. stored in cache memory
of Browser.
Data passed through GET Data passed through
method can be easily stolen by POST method cannot be
attackers. easily stolen by attackers.
In GET method only ASCII In POST method all types
characters are allowed. of data is allowed.
3. Attempt any THREE of the following: 12
a) Define function. How to define user defined function in PHP? 4M
Give example. 1M for
Ans. Definition: -A function is a block of code written in a program to definition
perform some specific task.
They take information as parameters, execute a block of statements 1M for
or perform operations on these parameters and return the result. A syntax
function will be executed by a call to the function. 2M for
any
Define User Defined Function in PHP: A user-defined function relevant
declaration starts with the keyword function. example

Syntax
function functionName() {
code to be executed;

Page 7 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

}
Example
<?php
function writeMsg() {
echo "Welcome to PHP world!";
}
writeMsg(); // call the function
?>
(Any other example can be considered)
b) Explain method overloading with example. 4M
Ans. Function overloading or method overloading is the ability to create 2M for
multiple functions of the same name with different implementations explanatio
depending on the type of their arguments. n
In PHP overloading means the behavior of a method changes 2M for
dynamically according to the input parameter. example
__call() is triggered when invoking inaccessible methods in an
object context.
__callStatic() is triggered when invoking inaccessible methods in a
static context.

__call():
If a class execute __call(), then if an object of that class is called
with a method that doesn't exist then__call() is called instead of that
method.

example:-
<?php
// PHP program to explain function
// overloading in PHP
// Creating a class of type shape
class shape {
// __call is magic function which accepts
// function name and arguments

function __call($name_of_function, $arguments) {


// It will match the function name
if($name_of_function == 'area') {
switch (count($arguments)) {
// If there is only one argument

Page 8 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

// area of circle
case 1:
return 3.14 * $arguments[0];

// IF two arguments then area is rectangle;


case 2:
return $arguments[0]*$arguments[1];
}
}
}
}

// Declaring a shape type object


$s = new Shape;

// Function call
echo($s->area(2));
echo "<br>";

// calling area method for rectangle


echo ($s->area(4, 2));
?>
Output:
9.426
48

Here the area() method is created dynamically and executed with


the help of magic method __call() and its behavior changes
according to the pass of parameters as object.
(Any other example can be considered)
c) Define session and cookie. Explain use of session start. 4M
Ans. Session 1M for
Session is a way to store information to be used across multiple each
pages, and session stores the variables until the browser is closed. definition
To start a session, the session_start() function is used and to destroy 2M for use
a session, the session_unset() and the session_destroy() functions of session
are used. start
The session variables of a session can be accessed by using the
$_SESSION super-global variable.

Page 9 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

Cookie
Cookie is a small piece of information stored as a file in the user's
browser by the web server. A cookie stores some data temporarily
(until the expiration date has passed).There is no Unique ID
allocated for a Cookie. The cookie data can be accessed using the
$_COOKIE super-global variable. A cookie can be set using the
setcookie() function.

Use of Session start


PHP session_start() function is used to start the session. It starts a
new or resumes an existing session. It returns an existing session if
the session is created already. If a session is not available, it creates
and returns a new session.
session_start() creates a session or resumes the current one based
on a session identifier passed via a GET or POST request, or passed
via a cookie.

Example optional:-
<?php
session_start();
?>
<html>
<body>
<?php
$_SESSION["uname"]="Customer1";
$_SESSION["fcolor"]="RED";
echo "The session variable are set with values";
?>
</body>
</html>
d) Explain delete operation of PHP on table data. 4M
Ans. Delete command is used to delete rows that are no longer required 2M for
from the database tables. It deletes the whole row from the table. explanatio
n
The DELETE statement is used to delete records from a table: 2M for
DELETE FROM table_name WHERE some_column = program /
some_value Example

Page 10 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

[WHERE condition] is optional. The WHERE clause specifies


which record or records that should be deleted. If the WHERE
clause is not used, all records will be deleted.
Below is a simple example to delete records into the student.pridata
table. To delete a record in any table it is required to locate that
record by using a conditional clause. Below example uses name to
match a record in student.pridata table.
Example:-
Assume Following Table
Database Name-student
Table name - pridata

<?php
$server='localhost';
$username='root';
$password='';
$con=mysqli_connect($server,$username,$password);
if(!$con){
die("Connection to this database failed due to"
.mysqli_connect_error($mysqli));
}
$sql="DELETE FROM student.pridataWHERE name='amit'";
if($con->query($sql)==true){
echo "Record deleted successfully";
}
else{
"ERROR:error".$con->error();
}
$con->close();
?>

Output:-

Page 11 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

Table after Deletion

(Any other example can be considered)

4. Attempt any THREE of the following: 12


a) Write PHP script to sort any five numbers using array 4M
function. 4M for
Ans. <?php correct and
$a = array(1, 8, 9, 4, 5); equivalent
sort($a); code
foreach($a as $i) {
echo $i.' ';
}
?>

OR

<!DOCTYPE html>
<html>
<body>
<H1>Enter five numbers </H1>
<form action = 'sort.php' method = 'post'>
<input type = 'number' name = 'n1' placeholder = 'Number
1...'><br><br>
<input type = 'number' name = 'n2' placeholder = 'Number
2...'><br><br>
<input type = 'number' name = 'n3' placeholder = 'Number
3...'><br><br>
<input type = 'number' name = 'n4' placeholder = 'Number
4...'><br><br>
<input type = 'number' name = 'n5' placeholder = 'Number
5...'><br><br>
<input type = 'submit' value = 'Submit'>
</form>
</body>
</html>

Page 12 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

sort.php
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$a = array($_POST['n1'], $_POST['n2'], $_POST['n3'],
$_POST['n4'], $_POST['n5']);
sort($a);
}
foreach($a as $i) {
echo $i.' ';
}
?>
(Any other example can be considered)
b) Write PHP program for cloning of an object 4M
Ans. (Any other correct program can be considered) 4M for
Code:- correct
<!DOCTYPE html> program
<html>
<body>

<?php
class car {
public $color;
public $price;
function __construct()
{
$this->color = 'red';
$this->price = 200000;
}
}
$mycar = new car();
$mycar->color = 'blue';
$mycar->price = 500000;
$newcar = clone $mycar;
print_r($newcar);
?>
</body>
</html>

Page 13 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

Explanation
The above code creates a car with a constructor which initializes its
member variable named color and price.
An object of the variable is created, and it is cloned to demonstrate
deep cloning.
c) Create customer form like customer name, address, mobile no, 4M
date of birth using different form of input elements & display
user inserted values in new PHP form.
Ans. <!DOCTYPE html>
<html> 4M for
<body> correct and
<form action = 'data..php' method = 'post'> equivalent
<input type = 'text' name = 'name' placeholder = 'Customer code
Name...'><br><br>
<input type = 'text' name = 'address' placeholder =
'Address...'><br><br>
<input type = 'text' name = 'number' placeholder = 'Mobile
Number...'><br><br>
<label> Date of Birth: </label>
<input type = 'date' name = 'dob'><br><br>
<input type = 'submit' value = 'Submit'><br>
</form>
</body>
</html>

data.php
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
echo '<html><body><form>
Customer Name: '.$_POST['name'].'<br>
Address: '.$_POST['address'].'<br>
Mobile Number: '.$_POST['number'].'<br>
Date of Birth: '.$_POST['dob'];
}
?>
(Any other correct program logic can be considered)
d) Inserting and retrieving the query result operations 4M
Ans. <?php 2M for
$con = mysqli_connect('localhost', 'root', '', 'class'); inserting

Page 14 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

# Connecting to Database 2M for


$query = "insert into user values(1, 'Amit')"; retrieving
# Inserting Values the query
$result = mysqli_query($con, $query); result
if($result) { operations
echo 'Insertion Successful <br>';
}
else {
echo 'Insertion Unsuccessful <br>';
}

$query = "select * from user";


# Retrieving Values
$result = mysqli_query($con, $query);

foreach($result as $r) {
echo $r['roll_number'].' '.$r['name'];
}
?>
Output
Insertion Successful
1 Amit
Explanation
The above code connects with a database named „class‟‟.
The exam database has a table named „user‟ with 2 columns
roll_number and name.
It executes an insert query on the user and checks whether the
insertion was successful or not.
It executes a select query on the user and displays the information
retrieved.
(Any other example can be considered)

e) How do you validate user inputs in PHP. 4M


Ans. Invalid user input can make errors in processing. Therefore, 2M for
validating inputs is a must. explanatio
1. Required field will check whether the field is filled or not in the n
proper way. Most of cases we will use the * symbol for required 2M for
field. program
2. Validation means check the input submitted by the user.

Page 15 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

There are two types of validation available in PHP.


Client-Side Validation − Validation is performed on the client
machine web browsers.
Server Side Validation − After submitted by data, The data is sent
to a server and performs validation checks in the server machine.

Some of Validation rules for field


Field Validation Rules
Name Should required letters and white-spaces
Email Should be required @ and .
Website Should required a valid URL
Radio Must be selectable at least once
Check Box Must be checkable at least once
Drop Down menu Must be selectable at least once

The preg_match() function searches a string for pattern, returning


true if the pattern exists, and false otherwise.

To check whether an email address is well-formed is to use PHP's


filter_var() function.

empty() function will ensure that text field is not blank it is with
some data, function accepts a variable as an argument and returns
TRUE when the text field is submitted with empty string, zero,
NULL or FALSE value.
Is_numeric() function will ensure that data entered in a text field is
a numeric value, the function accepts a variable as an argument and
returns TRUE when the text field is submitted with numeric value.

Example:-
Validations for: - name, email, phone no, website url
<!DOCTYPE html>
<body>
<?php
$nerror = $merror = $perror = $werror = $cerror = "";
$name = $email = $phone = $website = $comment = "";
$pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)* @[a-z0-9-]+(\.[a-z0-9-
]+)*(\.[a-z]{2,3})$^";

Page 16 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

if($_SERVER["REQUEST_METHOD"]=="POST") {
if(empty($_POST["name"])) {
$nerror = "Name cannot be empty!";
}
else {
$name = test_input($_POST["name"]);
if(!preg_match("/^[a-zA-Z-']*$/",$name))
{
$nerror = "Only characters and white spaces allowed";
}
}
if(empty($_POST["email"])) {
$merror = "Email cannot be empty!";
}
else
{
$email = test_input($_POST["email"]);
if(!preg_match($pattern, $email)) {
$merror = "Email is not valid";
}
}
if(empty($_POST["phone"])) {
$perror = "Phone no cannot be empty!";
}
else {
$phone = test_input($_POST["phone"]);
if (!preg_match ('/^[0-9]{10}+$/', $phone)) {
$perror = "Phn no is not valid";
}
}
if(empty($_POST["website"])) {
$werror = "This field cannot be empty!";
}
else {
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-
9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$werror = "URL is not valid";
}

Page 17 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

}
if (empty($_POST["comment"])) {
$cerror = "";
}
else {
$comment = test_input($_POST["comment"]);
}}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<p><span class="error">* required field </span></p>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nerror;?></span><br/><br/>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $merror;?></span><br/><br/>
Phone no: <input type="text" name="phone">
<span class="error">* <?php echo $perror;?></span><br/><br/>
Website: <input type="text" name="website">
<span class="error">* <?php echo $werror;?></span><br/><br/>
Comment: <textarea name="comment" rows="5"
cols="40"></textarea><br/><br/>
<input type="submit" name="submit" value="Submit"></form>
<?php
echo "<h2>Your Input:</h2>";
echo $name; echo "<br>";
echo $email; echo "<br>";
echo $phone; echo "<br>";
echo $website; echo "<br>";
echo $comment;
?>
</body>
</html>

Page 18 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

(Any other correct example can be consider and consider any


two user input validation)
5. Attempt any TWO of the following 12
a) Explain different loops in PHP with example. 6M
Ans. while loop: If the expression/condition specified with while 1M for
evaluates to true then the statements inside loop executes and explanatio
control is transferred back to expression/condition. The process of n and
evaluation and execution 1M for
Example: example
<?php of each
$a=1;
while($a<=5) Any three
{ can be
echo " Iteration $a"; considered
$a++;
}
?>

OR
Example:
<?php
$a=1;
while($a<=5):
echo " Iteration $a";
$a++;
endwhile;
?>

do-while loop:All the statements inside the loop executes for the
first time without checking any condition. The keyword „do‟ passes
the flow of control inside loop. After executing loop for the first
time, expression / condition is evaluated. If it evaluates to true then
all statements inside loop again executes and if it evaluates to false
then loop exits and flow of control passes to the next statement
placed outside the loop. The process of execution and evaluation
continues till expression / condition evaluates to true.
Example:
<?php
$a=1;

Page 19 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

do
{
print("Iteration 1");
$a++;
}while($a<=0);
?>

for loop:It is used to execute same set of statements multiple times.


In for loop variable initialization, condition and increment /
decrement is placed in a single statement. Before starting first
iteration a variable is initialized to specified value. Then condition
is checked. If condition is true then statements inside the loop
executes and variable is incremented or decremented. Control then
passes to condition. If condition is false then control passes to the
statement placed outside the loop. The process of condition
checking, loop statement execution and increment /decrement
continues till condition is true.
Example :
<?php
for ($a=1;$a<=5;$a++)
{
echo("Iteration $a");
}
?>

for each loop: This loop works with arrays and is used to traverse
through values in an array. For each loop iteration, the value of the
current array element is assigned to $value and the array pointer is
moved by one, until it reaches the last array element.
Example :
<?php
$arr=array("Apple","Banana","Orange");
foreach($arr as $fruit)
{
echo("$fruit");
}
?>
b) How do you connect MYSQL database with PHP. 6M
Ans. Using MySQLi Object Interface: 3M for

Page 20 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

<?php Any
$servername = "localhost"; relevant
$username = "root";
$password = "";
statement
$conn = new mysqli($servername, $username, $password); s for
if ($conn->connect_error) { connecti
die("Connection failed: " . $conn->connect_error); ng PHP
} with
echo "Connected successfully"; MySQL
mysqli_close($conn);
database
?>
Explanation:
The first part of the script is three variables (server name,
username, and password) and their respective values. These values 3M for
should correspond to your connection details. explanati
Next is the main PHP function mysqli_connect(). It establishes a
on
connection with the specified database.
When the connection fails, it gives the message Connection failed.
The die function prints the message and then exits out of the script

If the connection is successful, it displays “Connected


successfully.” When the script ends, the connection with the
database also closes. If you want to end the code manually, use
the mysqli_close function.

OR
using MySQLi Procedural interface:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$conn = mysqli_connect($servername, $username, $password);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {

Page 21 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

echo "Database created successfully";


} else {
echo "Error creating database: " ;
mysqli_error($conn);
}
mysqli_close($conn);
?>

Explanation:
The first part of the script is three variables (server name,
username, and password) and their respective values. These values
should correspond to your connection details.
Next is the main PHP function mysqli_connect(). It establishes a
connection with the specified database.
When the connection fails, it gives the message Connection failed.
The die function prints the message and then exits out of the script
If the connection is successful, it displays “Connected
successfully.”
Next, write a sql statement to create a database. If connection
established successfully then echo "Database created successfully";
else echo "Error creating database: "
When the script ends, the connection with the database also closes.
If you want to end the code manually, use
the mysqli_close function.

OR
using PDO - PHP Data Object
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try
{
$conn = new PDO("mysql:host=$servername;dbname=myDB",
$username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}

Page 22 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
Explanation:
The first part of the script is three variables (server name,
username, and password) and their respective values. These values
should correspond to your connection details.
If a problem arises while trying to connect, it stops running and
attempts to catch and solve the issue. Catch blocks can be set to
show error messages or run an alternative code.
Following is the setAttribute method adding two parameters to the
PDO:
1. PDO::ATTR_ERRMODE
2. PDO::ERRMODE_EXCEPTION
This method instructs the PDO to run an exception in case a query
fails.
Add the echo “Connected successfully.” to confirm a connection is
established.
Define the PDOException in the catch block by instructing it to
display a message when the connection fails.
c) Create a class as “Percentage” with two properties length & 6M
width. Calculate area of rectangle for two objects.
Ans <?php 3M for
class Percentage correct
{ syntax
public $length; 3M for
public $width; correct
public $a; logic
function area($l,$w)
{
$this->length=$l;
$this->width=$w;
$this->a=$this->length*$this->width;
echo "Area of rectangle = " . $this->a;
}
}
$p1=new Percentage();

Page 23 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

$p1->area(2,3);
$p2=new Percentage();
$p2->area(5,6);
?>
(Any other relevant logic can be considered)
6. Attempt any TWO of the following: 12
a) Write a PHP program to demonstrate use of cookies. 6M
Ans. Cookies can be used to identify user, managing session, etc. 6M for
Setting cookies for human identification: Any PHP
In the code below, two fields name and year are set as cookies on program
user's machine. From the two fields, name field can be used to
identify the user's revisit to the web site.
with
<?php correct
setcookie("name", "WBP", time()+3600, "/","", 0); demonstr
setcookie("Year", "3", time()+3600, "/", "", 0); ation for
?> use of
For the first time when user visits the web site, cookies are stored cookies
on user's machine. Next time when user visits the same page,
cookies from the user's machine are retrieved.
In the code below isset() function is used to check if a cookie is set
or not on the user's machine.
<html>
<body>
<?php
if( isset($_COOKIE["name"]))
echo "Welcome " . $_COOKIE["name"] . " Thanks for
Revisiting"."<br />";
else
echo "First Time Visitor". "<br />";
?>
</body>
</html>
b) Explain any four string functions in PHP with example. 6M
Ans. 1. str_word_count() function: This function is used to count the
number of words in a string. 1M for
syntax : str_word_count(string,return,char); explanati
string : It indicates string to be checked.
return :It is optional. It specifies the return value of the
on &
function. 1/2 M for
correct
Page 24 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

0- default. Returns the number of words found. example


1- returns an array with the words from the string. of each
2- returns an array where the key is the position of
the word in the string, and value is the actual Any four
word. functions
char : Optional. It specifies special characters to be to be
considered as words. considered
Example:

<?php
$str1="Welcome to WBP Theory & practical";
echo " <br> Total words in string str1=
".str_word_count($str1,0,"&");
?>
2. strlen() function : This function is used to find number of
characters in a string . While counting number characters from
string, function also considers spaces between words.
syntax : strlen(string);
- string specify name of the string from which characters
have to be counted.
Example :
<?php
$str3="Hello,welcome to WBP";
echo "<br> Number of characters in a string '$str3' = "
.strlen($str3);
?>

3. strrev() function : This function accepts string as an argument


and returns a reversed copy of it.
Syntax : $strname=strrev($string variable/String );
Example :
<?php
$str4="Polytechnic";
$str5=strrev($str4);
echo "Orginal string is '$str4' and reverse of it is '$str5'";
?>

4. strcmp() function : This function is used to compare two strings

Page 25 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

with each other . It is a case sensitive comparison.


Syntax : $result= strcmp(string1,string2);
- string1 and string2 indicates strings to be compared with
each other.
-This function returns 0 if both the strings are equal. It
returns a value <0 if string1 is less than string2 and >0 if
string 1 is greater than string2
Example 1 :
<?php
$str6="Welcome";
$str7="Welcome";
echo strcmp($str7,$str6);
?>
5. strpos() function : This function is used to find the position of
the first occurrence of specified word inside another string. It
returns False if word is not present in string. It is a case sensitive
function. by default, search starts with 0th position in a string.
Syntax : strpos(String,findstring,start);
- string specify string to be searched to find another word
- findstring specify word to be searched in specified first
parameter.
- start is optional . It specifies where to start the search in a
string. If start is a negative number then it counts from the
end of the string.
Example:
<?php
$str8="Welcome to Polytechnic";
$result=strpos($str8,"Poly",0);
echo $result;
?>
6. str_replace() function : This function is used to replace some
characters with some other characters in a string.
Syntax : str_replace(findword,replace,string,count);
- Find word specify the value to find
- replace specify characters to be replaced with search
characters.
- string specify name of the string on which find and replace
has to be performed.

Page 26 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

- count is optional . It indicates number of occurrences


replaced from a string.

Example 1:
$str10="Welcome to poly";
$str11=str_replace("poly","msbte",$str10);
echo $str11;

7. ucwords() function: This function is used to convert first


character of each word from the string into uppercase.
Syntax : $variable=ucwords($Stringvar);
Example :
<?php
$str9="welcome to poly for web based development";
echo ucwords($str9);
?>

8. strtoupper() function :This function is used to convert any


character of string into uppercase.
Syntax : $variable=strtoupper($stringvar);
Example:
<?php
$str9="POLYtechniC";
echo strtoupper($str9);
?>

9. strtolower() function : This function is used to convert any


character of string into lowercase.
Syntax: $variable=strtolower($stringvar);
Example :
<?php
$str9="POLYtechniC";
echo strtolower($str9);
?>

c) i) What is inheritance? 6M
ii) Write update operation on table data.
Ans. Inheritance: It is the process of inheriting (sharing) properties 3M for
and methods of base class in its child class. Inheritance provides re- explanatio

Page 27 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

usability of code in a program. PHP uses extends keyword to n of


establish relationship between two classes. inheritance
Syntax : class derived_class_name extends base_class_name
{
Class body
}
- derived_class_name is the name of new class which is also
known as child class.
- base_class_name is the name of existing class which is
also known as parent class.

A derived class can access properties of base class and also can
have its own properties. Properties defined as public in base class
can be accessed inside as well as outside of the class but properties
defined as protected in base class can be accessed only inside its
derived class. Private members of class cannot be inherited.

Example :
<?php
class college
{
public $name="ABC College";
protected $code=7;
}
class student extends college 3M for
{ update
public $sname="s-xyz"; operation
public function display()
{
echo "College name=" .$this->name;
echo "<br>College code=" .$this->code;
echo "<br>Student name=" .$this->sname;
}
}
$s1=new student();
$s1->display();
?>

ii) Any correct statements for connecting database and

Page 28 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web based Application Development using PHP Subject Code: 22619

updating data in database table


(Any data can be considered for updation)
Update data :
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ifdept";
$conn = new mysqli($servername, $username, $password,
$dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE student SET rollno=4 WHERE
name='abc'";
if ($conn->query($sql) === TRUE)
{
echo "Record updated successfully";
} else
{
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>

Page 29 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

Important Instructions to examiners:


1) The answers should be examined by key words and not as word-to-word as given
in the model answer scheme.
2) The model answer and the answer written by candidate may vary but the examiner
may try to assess the understanding level of the candidate.
3) The language errors such as grammatical, spelling errors should not be given more
Importance (Not applicable for subject English and Communication Skills.
4) While assessing figures, examiner may give credit for principal components
indicated in the figure. The figures drawn by candidate and model answer may
vary. The examiner may give credit for anyequivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the
assumed constant values may vary and there may be some difference in the
candidate’s answers and model answer.
6) In case of some questions credit may be given by judgement on part of examiner
of relevant answer based on candidate’s understanding.
7) For programming language papers, credit may be given to any other program
based on equivalent concept.
8) As per the policy decision of Maharashtra State Government, teaching in
English/Marathi and Bilingual (English + Marathi) medium is introduced at first year
of AICTE diploma Programme from academic year 2021-2022. Hence if the
students in first year (first and second semesters) write answers in Marathi or
bilingual language (English +Marathi), the Examiner shall consider the same and
assess the answer based on matching of concepts with model answer.

Q. Sub Answer Marking


No Q.N. Scheme
1. Attempt any FIVE of the following: 10
a) List any four data types of PHP. 2M
Ans.  boolean Any four
 integer types ½ M
each
 float
 string
 array
 object
 resource
 NULL
b) Define Array. State its example. 2M
Ans. Definition:An array is a special variable, which can hold more than Definition
one value at a time. 1M

Page 1 / 22
www.diplomachakhazana.in
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

Example:
1)Indexed array: Any one
example 1M
$colors = array("Red", "Green", "Blue");

2)Associative array:
$student_one = array("Maths"=>95, "Physics"=>90,
"Chemistry"=>96, "English"=>93,
"Computer"=>98);

3)Multidimensional array
$movies =array(
"comedy" =>array("Pink Panther", "John English", "See no evil hear
no evil"),
"action" =>array("Die Hard", "Expendables","Inception"),
"epic" =>array("The Lord of the rings")
);
c) State the role of constructor. 2M
Ans. The constructor is an essential part of object-oriented programming. Correct
It is a method of a class that is called automatically when an object of answer 2M
that class is declared. The main purpose of this method is to initialize
the object.
d) State the use of cookies. 2M
Ans. Cookie is used to keep track of information such as a username that Correct use
the site can retrieve to personalize the page when the user visits the 2M
website next time.
e) List two database operations. 2M
Ans. 1.mysqli_affected_rows() Any two
operations
2. mysqli_close() 1M each
3. mysqli_connect()
4. mysqli_fetch_array()
5.mysqli_fetch_assoc()
6.mysqli_affected_rows()
7. mysqli_error()
f) Write syntax of for each loop 2M
Ans. foreach ($array as $value) { Correct
code to be executed; syntax 2M
}

Page 2 / 22
www.diplomachakhazana.in
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

g) State role of GET and POST methods 2M


Ans. i)Get method:
It processes the client request which is sent by the client, using the 1M for each
HTTP get method.Browser uses get method to send request. method

ii)Post method
It Handles request in servlet which is sent by the client. If a client is
entering registration data in an html form, the data can be sent using
post method.
2. Attempt any THREE of the following: 12
a) Explain the use of break and continue statements. 4M
Ans. Break statement:-break keyword is used to terminate and transfer
the control to the next statement when encountered inside a loop or
switch case statement.
Syntax:
if (condition) Use and
{ break; } relevant
Example: example of
each - 2M
<?php

for ($a = 0; $a < 10; $a++)


{
if ($a == 7)
{
break; /* Break the loop when condition is true. */
}
echo "Number: $a <br>";
}
echo " Terminate the loop at $a number";
?>

ii)Continue Statement
It is used to skip the execution of a particular statement inside the
loops.
if (condition)
{ continue; }
Example:
<?php
for ($i = 0; $i< 10; $i++)

Page 3 / 22
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

{
if ($i == 5)continue;
{
echo " $i<br>";
}}
echo "end";
?>
b) Explain Indexed array and associative arrays with suitable 4M
examples.
Ans.  In indexed arrays the value is accessed using indexes 0,1,2 etc.
 These types of arrays can be used to store any type of elements,
but an index is always a number. By default, the index starts at Explanation
zero. These arrays can be created in two different ways as shown of each array
in the following with suitable
 Array initialization example -2M
First method
$colors = array("Red", "Green", "Blue");

Second method
$colors[0] = "Red";
$colors[1] = "Green";
$colors[2] = "Blue";

Example:-initialize an array elements and display the same


<?php
$name_one = array("Zack", "Anthony", "Ram", "Salim", "Raghav");
// Accessing the elements directly
echo "Accessing the 1st array elements directly:\n";
echo $name_one[2], "\n";
echo $name_one[0], "\n";
echo $name_one[4], "\n";
?>

ii)Associative array
Associative arrays are used to store key value pairs.
Associative arrays have strings as keys and behave more liketwo-
column tables. The first column is the key, which is used to access the
value.

Page 4 / 22
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

Here array() function is used to create associative array.


<?php
/* First method to create an associate array. */
$student_one = array("Maths"=>95, "Physics"=>90,
"Chemistry"=>96, "English"=>93,
"Computer"=>98);
Second method to create an associate array.
$student_two["Maths"] = 95;
$student_two["Physics"] = 90;
$student_two["Chemistry"] = 96;
$student_two["English"] = 93;
$student_two["Computer"] = 98;

Example
<?php
$student_two["Maths"] = 95;
$student_two["Physics"] = 90;
$student_two["Chemistry"] = 96;
$student_two["English"] = 93;
$student_two["Computer"] = 98;
echo "Marks for student one is:\n";
echo "Maths:" . $student_two["Maths"], "\n";
echo "Physics:" . $student_two["Physics"], "\n";
echo "Chemistry:" . $student_two["Chemistry"], "\n";
echo "English:" . $student_two["English"], "\n";
echo "Computer:" . $student_two["Computer"], "\n";
?>
c) Define Introspection. Explain it with suitable example 4M
Ans. Introspection is the ability of a program to examine an object's
characteristics, such as its name, parent class (if any), properties, and Definition
1M
methods. With introspection, we can write code that operates on any
class or object. We don't need to know which methods or properties
are defined when we write code; instead, we can discover that
informationat runtime, which makes it possible for us to write generic
debuggers, serializers, profilers, etc.
Example:-
<?php Any relevant
class parentclass Program /
Example -
{ 3M

Page 5 / 22
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

public $roll;
public function par_function()
{}}
class childclass extends parentclass
{public $name;
public function child_fun()
{}}
$obj=new childclass();
//class introspection
print_r("parent class exists:".class_exists('parentclass'));
echo"<br> child class methods: ";
print_r(get_class_methods('childclass'));
echo"<br> child class variables: ";
print_r(get_class_vars('childclass'));
echo"<br> parent class variables: ";
print_r(get_class_vars('parentclass'));
echo"<br> parent class: ";
print_r(get_parent_class('childclass'));
//object introspection;
echo"<br> is object: ";
print_r(is_object($obj));
echo"<br> object of a class: ";
print_r(get_class($obj));
echo"<br> object variables: ";
print_r(get_object_vars($obj));
echo"<br> methods exists: ";
print_r(method_exists($obj,'child_fun'));
?>

d) Describe 4M
i) Start session
ii) Get session variables
Ans. PHP session_start() function is used to start the session. It starts a
new or resumes existing session. It returns existing session if session
is created already. If session is not available, it creates and returns Description
of Start
new session session 2M
Syntax 1.
boolsession_start( void )

Page 6 / 22
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

Example 1.session_start();
PHP $_SESSION is an associative array that contains all session
variables. It is used to set and get session variable values.
Example: Store information
2. $_SESSION["CLASS"] = "TYIF STUDENTS“
Example: Program to set the session variable (demo_session1.php)
<?php
session_start();
?>
<html>
<body>
<?php
$_SESSION["CLASS"] = "TYIF STUDDENTS";
echo "Session information are set successfully.<br/>";
?>
</body>
</html>

ii)Get Session variables


We create another page called "demo_session2.php". From this page,
we will access the session information we set on the first page Description
("demo_session1.php"). of
Get session
2M
Notice that session variables are not passed individually to each new
page, instead they are retrieved from the session we open at the
beginning of each page (session_start()).

Also notice that all session variable values are stored in the global
$_SESSION variable:

Example:- program to get the session variable


values(demo_session2.php)
<?php
session_start();
?>
<html>
<body>
<?php
echo "CLASS is: ".$_SESSION["CLASS"];

Page 7 / 22
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

?>
</body>
</html>
3. Attempt any THREE of the following: 12
a) Explain two functions to scale the given image. 4M
Ans. imagecopyresized() function : It is an inbuilt function in PHP which
is used to copy a rectangular portion of one image to another image
and resize it. dst_image is the destination image, src_image is the Explanation
source image identifier. of two
functions -
Syntax: 2M each
imagecopyresized(dst_image, src_image, dst_x, dst_y,src_x, src_y,
dst_w,dst_h,src_w, src_h)
dst_image: It specifies the destination image resource.
src_image: It specifies the source image resource.
dst_x: It specifies the x-coordinate of destination point.
dst_y: It specifies the y-coordinate of destination point.
src_x: It specifies the x-coordinate of source point.
src_y: It specifies the y-coordinate of source point.
dst_w: It specifies the destination width.
dst_h: It specifies the destination height.
src_w: It specifies the source width.
src_h: It specifies the source height.
Example:
imagecopyresized($d_image,$s_image,0,0,50,50,200,200,$s_width,
$s_height);

imagecopyresampled() function : It is used to copy a rectangular


portion of one image to another image, smoothly interpolating pixel
values thatresize an image.
Syntax:
imagecopyresampled(dst_image, src_image, dst_x, dst_y,src_x,
src_y, dst_w,dst_h,src_w, src_h)
dst_image: It specifies the destination image resource.
src_image: It specifies the source image resource.
dst_x: It specifies the x-coordinate of destination point.
dst_y: It specifies the y-coordinate of destination point.
ṇsrc_x: It specifies the x-coordinate of source point.
src_y: It specifies the y-coordinate of source point.
dst_w: It specifies the destination width.

www.diplomachakhazana.in Page 8 / 22
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

dst_h: It specifies the destination height.


src_w: It specifies the source width.
src_h: It specifies the source height.

Example:
imagecopyresampled($d_image,$s_image,0,0,50,50,200,200,$s_widt
h,$s_height);
b) Write syntax to create class and object in PHP. 4M
Ans. A class is defined by using the class keyword, followed by the name
of the class and a pair of curly braces ({}). All its properties and
Correct
methods go inside the curly brackets. syntax for
Syntax : creating
<?php class-2M,
class classname [extends baseclass][implements
interfacename,[interfacename,…]] Object-2M
{ (Example is
[visibility $property [=value];…] optional)
[functionfunctionname(args) { code }…] // method declaration &
definition
}
?>
In the above syntax, terms in squarebrackets are optional.

Object : An object is an instance of class. The data associated with an


object are called its properties. The functions associated with an
object are called its methods. Object of a class is created by using the
new keyword followed by classname.
Syntax : $object = new Classname( );
Example:
<?php
class student
{
public $name;
public $rollno;

function accept($name,$rollno)
{
$this->name=$name;
$this->rollno=$rollno;

Page 9 / 22
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

}
}
?>
$s1=new student( );
c) State any four form controls to get user’s input in PHP. 4M
Ans. 1. Textbox control:It is used to enter data. It is a single line input on a
web page.
Tag :<input type=“text”> Any four
form controls
2. Password control:It is used to enter data that appears in the form of 1M each
special characters on a web page inside box. Password box looks
like a text box on a wab page.
Tag:<input type=“password”>
3. Textarea : It is used to display a textbox that allow user to enter
multiple lines of text.
Tag :<textarea> … </textarea>
4. Checkbox:It is used to display multiple options from which user
can select one or more options.
Tag: <input type=“checkbox”>
5. Radio / option button :These are used to display multiple options
from which user can select only one option.
Tag :<input type=“radio”>
6. Select element (list) / Combo box / list box:
<select> … </select> : This tag is used to create a drop-down list
box or scrolling list box from which user can select one or more
options.
<option> … </option> tag is used to insert item in a list.
d) Write steps to create database using PHP 4M
Ans. Steps using PHP Code:Creating database: With CREATE Correct steps
DATABASE query 4M
Step 1: Set variables with values for servername, username,
password.
Step 2: Set connection object by passing servername, username,
password as parameters.
Step 3: Set query object with the query as "CREATE DATABASE
dept";
Step 4: Execute query with connection object.
Code (Optional)-
<?php

Page 10 / 22
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

$servername = "localhost";
$username = "root";
$password = "";
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "CREATE DATABASE ifdept";
if ($conn->query($sql) === TRUE)
{
echo "Database created successfully";
}
else
{
echo "Error creating database: " . $conn->error;
}
$conn->close ();
?>

OR

Steps using phpMyAdmin


Step 1: Click on Start and select XAMPP from the list. Open Xampp
control panel by clicking on the option from the list. The Control
Panel is now visible and can be used to initiate or halt the working of
any module.
Step2: Click on the "Start" button corresponding
to Apache and MySQL modules. Once it starts working, the user can
see the following screen:
Step 3: Now click on the "Admin" button corresponding to
the MySQL module. This automatically redirects the user to a web
browser to the following address - http://localhost/phpmyadmin

Step 4: Screen with multiple tabs such as Database, SQL, User


Accounts, Export, Import, Settings, etc. Will appear. Click on
the "Database" tab. Give an appropriate name for the Database in the
first textbox and click on create option.

Page 11 / 22
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

Step 5 : In the created Database, click on the 'Structure' tab. Towards


the end of the tables list, the user will see a 'Create Table' option.
Give appropriate "Name" and "Number of Columns" for table and
click on 'Go' button.

Step 6 : Give details of columns based on their type. Enter the names
for each column, select the type, and the maximum length allowed for
the input field. Click on "Save" in the bottom right corner. The table
with the initialized columns will be created.

4. Attempt any THREE of the following: 12


a) Define user defined function with example. 4M
Ans. A function is a named block of code written in a program to perform
some specific tasks. They take information as parameters, execute a
Description
block of statements or perform operations on these parameters and 2M, Example
return the result. A function will be executed by a call to the function. 2M
The function name can be any string that starts with a letter or
underscore followed by zero or more letters, underscores, and digits.

Syntax:
function function_name([parameters if any])
{
Function body / statements to be executed
}

Example:
<?php
function display() // declare and define a function
{
echo "Hello,Welcome to function";
}
display(); // function call
?>

When a function is defined in a script, to execute thefunction,


programmer have to call it with its name and parameters if required.

Page 12 / 22
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

b) Write a program for cloning of an object. 4M


Ans. (Any other correct program shall be considered)
Correct
program 4M
<?php
class student
{
function getdata($nm,$rn)
{
$this->name=$nm;
$this->rollno=$rn;
}
function display()
{
echo "<br>name = ".$this->name;
echo "<Br>rollno = ".$this->rollno;
}
}
$s1 = new student();
$s1->getdata("abc",1);
$s1->display();
$s2 = clone $s1;
echo "<br> Cloned object data ";
$s2->display();
?>

c) Write steps to create webpage using GUI components. 4M


Ans. Following are the GUI components to design web page:
 Button - has a textual label and is designed to invoke an action Correct
when pushed. steps-4M
 Checkbox - has textual label that can be toggled on and off.
 Option - is a component that provides a pop-up menu of choices.
 Label - is a component that displays a single line of read-only,
non-selectable text.
 Scrollbar - is a slider to denote a position or a value.
 TextField - is a component that implements a single line of text.
 TextArea - is a component that implements multiple lines of text.
To design web pages in PHP:
Step 1) start with <html>

Page 13 / 22
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

Step 2) If user required to add CSS in <head> section.


<head> (any other
<style> relevant steps
.error {color: #FF0000;} to design web
page shall be
</style> considered)
</head>
Step 3) In <body> section design form with all mentioned
components.
Step 4) using <?php
Write script for validation for all required input field.
Save the file with php extension to htdocs (C:/Program
Files/XAMPP/htdocs)
Note: You can also create any folders inside ‘htdocs’ folder and
save our codes over there.
Step 5) Using XAMPP server, start the service ‘Apache’.
Step 6)Now to run your code, open localhost/abc.php on any web
browser then it gets executed.
d) Explain queries to update and delete data in the database. 4M
Ans. Update data : UPDATE query
Update command is used to change / update new value for field in Explanation
row of table. It updates the value in row that satisfy the criteria given of Update
query 2M
in query.

The UPDATE query syntax:


UPDATE Table_name SET field_name=New_value WHERE
field_name=existing_value
Example :
UPDATE student SET rollno=4 WHERE name='abc'
In the above query, a value from rollno field from student table is
updated with new value as 4 if its name field contains name as ‘abc’.

Delete data: DELETE query Explanation


Delete command is used to delete rows that are no longer required of
from the database tables. It deletes the whole row from the table. Delete query
The DELETE query syntax: 2M
DELETE FROM table_name WHERE some_column =
some_value

Page 14 / 22
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

[WHERE condition] is optional. The WHERE clause specifies which


record or records that should be deleted. If the WHERE clause is not
used, all records will be deleted.
Example :-
$sql = "DELETE FROM student WHERE rollno=2";

In the above query, a row from student table is deleted if rollno field
contains 2 in that row.
e) Describe the syntax of if-else control statement with example in 4M
PHP.
Ans. if-else control statement is used to check whether the
Description
condition/expression is true or false. Ifthe expression / condition of if-else
evaluates to true then true block code associated with the if statement control
is executed otherwise if it evaluates to false then false block of code statement
associated with else is executed. 2M,
Syntax:
Syntax1M,
if (expression/condition)
{ Example1M
True code block;
}
else
{
False code block;
}

Example:
<?php
$a=30;
if ($a<20)
echo "variable value a is less than 20";
else
echo "variable value a is greater than 20";
?>
In the above example, variable a holds value as 30. Condition checks
whether the value of a is less than 20. It evaluates to false so the
output displays the text as ‘variable value a is greater than 20’.
5. Attempt any TWO of the following: 12
a) Write a PHP program to display numbers from 1-10 in a 6M
sequence using for loop.

Page 15 / 22
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

Ans. PHP Code-


<?php For loop
syntax 2M
echo "Output<br>";
for($i=1;$i<=10;$i++) Correct
{ syntax 2M
echo "$i<br/>";
} Correct logic
2M
?>
Output
(Output is
1
optional)
2
3
4
5
6
7
8
9
10
b) Write a program to connect PHP with MYSQL. 6M
Ans. Solution1:
<?php
$servername = "localhost"; Correct
$username = "root"; syntax 2M
$password = "";
// Connection Correct code
$conn = new mysqli($servername,$username, $password); 4M
// For checking if connection issuccessful or not
if ($conn->connect_error)
{
die("Connection failed: ". $conn->connect_error);
}
Writing
echo "Connected successfully"; Output is
?> optional
Output:
Connected successfully
OR

Page 16 / 22
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

Solution2:
Create login.php
<?php
$hostname = 'localhost';
$username = 'root';
$password = '';
?>

Create db2.php file


<?php
require_once 'login.php';
$conn = new mysqli($hostname, $username, $password);
//if ($conn->connect_error) die($conn->connect_error);
if ($conn->connect_error) {
die("Connection failed: "
. $conn->connect_error);
}
echo "Connected successfully";
?>
Output:
Connected successfully

c) Illustrate class inheritance in PHP with example. 6M


Ans.  Inheritance is a mechanism of extending an existing class where
a newly created or derived class have all functionalities of
Definition /
existing class along with its own properties and methods. Explanation
 The parent class is also called a base class or super class. And the and
child class is also known as a derived class or a subclass. Types of
 Inheritance allows a class to reuse the code from another class Inheritance-
2M
without duplicating it.
 Reusing existing codes serves various advantages. It saves time, Any Correct
cost, effort, and increases a program’s reliability. Program /
 To define a class inherits from another class, you use the extends example- 4M
keyword.
 Types of Inheritance:
Single Inheritance
Multilevel Inheritance
Multiple Inheritance
Hierarchical Inheritance

Page 17 / 22
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

Example:
(Any type of inheritance example shall be considered)
<?php
class student {
var $var = "This is first var";
protected $fist_name;
protected $last_name;

// simple class method


function returnVar() {
echo $this->fist_name;
}
function set_fist_name($fname,$lname){
$this->fist_name = $fname;
$this->last_name = $lname;
}
}
class result extends student {
public $percentage;

function set_Percentage($p){
$this->percentage = $p;
}
function getVal(){
echo "Name:$this->fist_name $this->last_name";
echo "<br/>";
echo "Result: $this->percentage %";
}
}
$res1 = new result();
$res1->set_fist_name("Rita","Patel");
$res1->set_Percentage(95);
$res1->getVal();
?>
Output:
Name:Rita Patel
Result: 95 %

Page 18 / 22
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

6. Attempt any TWO of the following: 12


a) Write a PHP program to set and modify cookies. 6M
Ans. PHP program to set cookies
<html> Correct Code
to set cookie -
<body> 3M
<?php
$cookie_name = "username";
$cookie_value = "abc";
setcookie($cookie_name, $cookie_value, time() +
(86400 * 30), "/"); // 86400 = 1 day
if(!isset($_COOKIE[$cookie_name])) { Correct Code
echo "Cookie name '" . $cookie_name . "' is not to modify
set!"; cookies- 3M
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Output:
Cookie 'username' is set!
Value is: abc

PHP program to modify cookies

<?php
setcookie("user", "xyz");
?>
<html>
<body>
<?php
if(!isset($_COOKIE["user"]))
{
echo "Sorry, cookie is not found!";
} else {
echo "<br/>Cookie Value: " .
$_COOKIE["user"];
}

Page 19 / 22
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

?>
</body>
</html>

Output:
Cookie Value: xyz
b) Write a PHP program to 6M
i) Calculate length of string Program to
ii) Count number of words in string calculate
length of
Ans. string 3M
i) Calculate length of string
<?php
$str = 'Have a nice day ahead!';
echo "Input String is:".$str;
echo "<br>";
echo "Length of String str:".strlen($str);
// output =12 [including whitespace]
?>

ii) Count number of words in string Program to


count
Solution1- number of
<?php words in
// PHP program to count number of string 3M
// words in a string

$str = " This is a string ";

// Using str_word_count() function to count number of words in a


string
$len = str_word_count($str);

// Printing the result


echo "Number of words in string : $len";
?>
Output:
Number of words in string : 4

OR

Page 20 / 22
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

Solution 2:
<?php
// PHP program to count number of
// words in a string
$string = " This is a string ";
$str = trim($string);
while (substr_count($str, " ") > 0) {
$str = str_replace(" ", " ", $str);
}
$len = substr_count($str, " ")+1;
// Printing the result
echo "Number of words in string: $len";
?>

Output:
Number of words in string: 4
c) i) State the use of serialization. 6M
ii) State the query to insert data in the database.
Ans. i) Use of serialization. Serialization
Serializing an object means converting it to a bytestream explanation
representation that can be stored in a file. Serialization in PHP is with
mostly automatic, it requires little extra work from you, beyond example- 3M
calling the serialize () and unserialize( ) functions.

Serialize() :
 The serialize() converts a storable representation of a value.
 The serialize() function accepts a single parameter which is the
data we want to serialize and returns a serialized string.
 A serialize data means a sequence of bits so that it can be stored
in a file, a memory buffer or transmittedacross a network
connection link. It is useful for storing or passing PHP values
around without losing their type and structure.

Example:
<?php
$s_data= serialize(array('Welcome', 'to', 'PHP'));
print_r($s_data . "<br>");
$us_data=unserialize($s_data);

Page 21 / 22
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER – 2022 EXAMINATION


MODEL ANSWER
Subject: Web Based Application Development Using PHP (Elect-II) Subject Code: 22619

print_r($us_data);
?>

Output:a:3:{i:0;s:7:"Welcome";i:1;s:2:"to";i:2;s:3:"PHP";} Correct
Array ( [0] => Welcome [1] => to [2] => PHP ) example of
insert query-
3M
ii) Query to insert data in the database
<?php
require_once 'login.php';
$conn = newmysqli($hostname,$username, $password,$dbname);
$query = "INSERT INTO studentinfo(rollno,name,percentage)
VALUES
('CO103','Yogita Khandagale',98.45)";
$result = $conn->query($query);
if (!$result)
die ("Database access failed: " . $conn->error);
else
echo "record inserted successfully";
?>

Output:
record inserted successfully

Page 22 / 22

You might also like