100% found this document useful (1 vote)
76 views

AADK_answers

The document provides an overview of Kotlin programming concepts, including the creation of an Employee class, the use of getters and setters, interfaces, data classes, null safety, and the use of constructors. It explains the differences between interfaces and classes, the types of variables in Kotlin, and features such as immutability and extension functions. Additionally, it covers the 'when' keyword as a control structure for conditional logic.

Uploaded by

NIRANJAN BEHERA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
76 views

AADK_answers

The document provides an overview of Kotlin programming concepts, including the creation of an Employee class, the use of getters and setters, interfaces, data classes, null safety, and the use of constructors. It explains the differences between interfaces and classes, the types of variables in Kotlin, and features such as immutability and extension functions. Additionally, it covers the 'when' keyword as a control structure for conditional logic.

Uploaded by

NIRANJAN BEHERA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

UNIT – 1

1. (a) Create a class for Employee, write a user defined function to accept the attributes
of employee and display the attribute in kotlin.
// Define the Employee class

class Employee(

var name: String,

var id: Int,

var department: String,

var position: String,

var salary: Double

){

// Function to display employee attributes

fun displayInfo() {

println("Name: $name")

println("ID: $id")

println("Department: $department")

println("Position: $position")

println("Salary: $salary")

// Function to accept attributes and display employee information

fun main() {

// Create an instance of the Employee class

val emp = Employee("John Doe", 12345, "IT", "Software Developer", 75000.0)


// Display employee information

emp.displayInfo()

(b) Explain setter and getter function with suitable example in Kotlin. What do you
mean by ternary operator? Explain how if statement is used as ternary operator in
Kotlin? (imp)

Getter and Setter in Kotlin:


In Kotlin, getter and setter methods are auto-generated for mutable properties. You can also
define custom accessors, if needed. Here’s an example:
class Employee {
var name: String = "Default"
get() = field
set(value) {
field = value
}
}
fun main() {
val employee = Employee()
employee.name = "John Doe" // Calls the setter
println(employee.name) // Calls the getter
}

In this code, name is a property of the Employee class. The get() and set(value) functions are the
getter and setter for this property, respectively. The field keyword is a special keyword that
refers to the property itself.

Ternary Operator: A ternary operator is a shorthand way of writing an if-else statement. It’s
called “ternary” because it takes three operands: a condition, a result for true, and a result
for false.
However, Kotlin does not have a traditional ternary operator like condition ? true : false.
Instead, you can use the if statement as an expression, which serves a similar purpose.
Here’s an example:
fun main() {
val number = 10
val result = if (number > 0) "Positive" else "Non-positive"
println(result) // Prints "Positive"
}
In this code, if (number > 0) "Positive" else "Non-positive" is similar to a ternary operation.
If the condition number > 0 is true, it returns "Positive"; otherwise, it returns "Non-
positive". The result is then stored in the result variable. This is how you can use if as a
ternary operator in Kotlin.
2. (a) Explain with suitable example interface in Kotlin?
In Kotlin, an interface is a common aspect that classes can choose to implement. An interface
can contain declarations of abstract methods and properties as well as method implementations.
Here’s an example:

interface Drivable {

fun drive()

class Car : Drivable {

override fun drive() {

println("Driving a car.")

class Bike : Drivable {

override fun drive() {

println("Riding a bike.")
}

fun main() {

val car: Drivable = Car()

car.drive() // Prints "Driving a car."

val bike: Drivable = Bike()

bike.drive() // Prints "Riding a bike."

In this code:

Drivable is an interface with a single abstract method drive().

Car and Bike are classes that implement the Drivable interface, meaning they provide their own
implementations of the drive() method.

In the main() function, we create instances of Car and Bike, both referred to by the Drivable
interface type. When we call drive() on these instances, the appropriate method is called based
on the actual type of the object.

This is a basic example. In real-world applications, interfaces can be used to achieve complex
functionality and enable polymorphism.

(b) Write the features of Kotlin?

Kotlin is a statically typed programming language developed by JetBrains. It is designed to


interoperate fully with Java, and the JVM version of Kotlin’s standard library depends on the
Java Class Library. Here are some key features of Kotlin:

Interoperability with Java: Kotlin is fully interoperable with Java, which means that you can
use all existing Java libraries and frameworks, and your Kotlin code can coexist with Java code
in the same project.
Null Safety: Kotlin aims to eliminate the risk of null references from code, also known as the
the Billion Dollar Mistake. Kotlin’s type system is designed to eliminate
NullPointerException’s from our code.

Extension Functions: Kotlin provides the ability to extend a class with new functionality
without having to inherit from the class. This is done via special declarations called extensions.

Coroutines: Kotlin has built-in support for coroutines, which makes asynchronous
programming easier and more intuitive.

Smart Casts: The Kotlin compiler tracks your logic and auto-casts types if possible, which
eliminates the need for explicit casting.

Default Arguments and Named Parameters: Kotlin allows you to specify default values for
function parameters and also lets you call functions using named arguments for better
readability.

Data Classes: Kotlin provides a concise syntax for creating classes used to hold data/state,
known as data classes.

Immutability: Kotlin encourages the use of immutable data which makes your code more
predictable and easier to reason about.

Functional Programming: Kotlin has many features of functional programming languages


like lambda expressions, higher-order functions, operator overloading, lazy evaluation, and
collection operators like map, filter, and reduce.

Scripting: Besides being an object-oriented language, Kotlin also supports scripting. You can
write scripts in Kotlin and execute them directly without any boilerplate code.

3. (a) Write a Kotlin function to display all the prime numbers between 1 to 100.

fun main() {

for (i in 2..100) {

var isPrime = true

for (j in 2 until i) {

if (i % j == 0) {
isPrime = false

break

if (isPrime) {

println(i)

(b) Explain with suitable example interface in Kotlin?


Above

4. (a) Write the difference between interface and class in kotlin.

In Kotlin, interfaces and classes serve different purposes and have distinct characteristics. Here
are the key differences between interfaces and classes:

Purpose:
Interface: An interface in Kotlin defines a set of methods and properties that a class must
implement. It specifies a contract that classes can adhere to, without providing the
implementation details.
Class: A class in Kotlin is a blueprint for creating objects. It can contain properties,
methods, constructors, and other members that define the behavior and state of objects.

Implementation:
Interface: Interfaces only declare method signatures and properties without providing the
implementation. Classes that implement an interface must provide concrete implementations for
all the methods and properties defined in the interface.
Class: Classes can provide concrete implementations for methods and properties. They
can also inherit from other classes or implement interfaces.

Inheritance:
Interface: Interfaces can inherit from other interfaces using the : symbol. A class can
implement multiple interfaces, allowing for multiple inheritance of behavior.
Class: Classes can inherit from other classes using the : symbol. However, Kotlin does
not support multiple inheritance for classes (except for inheriting from multiple interfaces),
meaning a class can only inherit from one superclass.

Usage:
Interface: Interfaces are often used to define contracts for implementing classes,
especially in cases where multiple classes need to exhibit similar behavior but may have
different implementations.
Class: Classes are used to create objects and define their behavior. They encapsulate data
and behavior into a single unit, providing a way to model real-world entities and concepts.

Abstract Members:
Interface: All members (methods and properties) of an interface are abstract by default.
They do not have a body and must be implemented by classes that implement the interface.
Class: Classes can have both abstract and concrete members. Abstract members in a class
are declared using the abstract keyword and must be implemented by subclasses.

(b) What are the different types of variables in Kotlin? Explain with examples.

In Kotlin, variables can be classified into different types based on their mutability, scope, and
initialization. Here are the main types of variables in Kotlin:

Immutable Variables (val):

Declared using the val keyword.

Immutable variables cannot be reassigned once they are initialized.

They are read-only and hold a constant value.

Example:

val pi = 3.14

val name = "John Doe"

Mutable Variables (var):

Declared using the var keyword.

Mutable variables can be reassigned after they are initialized.

They can change their value during the program execution.

Example:
var count = 0

count = 5 // Valid reassignment

Nullable Variables:

Variables that can hold a null value in addition to their regular type.

Declared using the nullable type syntax with ? after the type.

Example:

var nullableName: String? = null

Late-Initialized Variables (lateinit):

Used for non-null mutable variables that are initialized later, typically in the constructor or a
setup method.

Declared using the lateinit modifier.

They must be initialized before being accessed to avoid lateinit property not initialized errors.

Example:

lateinit var lateInitVariable: String

// Initialize later in the code

lateInitVariable = "Initialized value"

Constants (const):

Variables whose values are known at compile time and cannot be changed during runtime.

Declared using the const modifier at the top level or inside an object.

Only applicable to top-level or object-level variables and not local variables.

Example:

const val PI = 3.14

Local Variables:

Variables declared inside a function or a code block with limited scope.

Their visibility is limited to the block where they are defined.


Example:

fun calculateSum(a: Int, b: Int): Int {

val sum = a + b // Local variable sum

return sum

5. (a) What are data classes in Kotlin? Explain with a proper example.

In Kotlin, data classes are a concise way to declare classes that are primarily used for holding
data. These classes automatically generate several standard methods such as equals(),
hashCode(), toString(), and copy() based on the properties defined in the class. Data classes can
significantly reduce boilerplate code when working with classes that primarily serve as data
containers. Here's an example to illustrate data classes in Kotlin:

// Define a data class Person with properties


data class Person(val name: String, val age: Int)

fun main() {
// Create an instance of Person using the data class constructor
val person1 = Person("John Doe", 30)
val person2 = Person("Jane Smith", 25)

// Access properties of data class instances


println("Person 1: ${person1.name}, ${person1.age} years old")
println("Person 2: ${person2.name}, ${person2.age} years old")

// Compare instances using == (calls the generated equals() method)


val isEqual = person1 == person2
println("Are the persons equal? $isEqual")

// Create a copy of a data class instance with modified properties


val modifiedPerson = person1.copy(name = "John Smith")
println("Modified Person: ${modifiedPerson.name}, ${modifiedPerson.age} years old")

// Automatically generated toString() method


println("Person 1 details: $person1")
}
In this example:
We define a data class Person with two properties: name of type String and age of type Int.
We create instances of the Person class using the data class constructor, providing values for
the properties.
We access the properties of the data class instances using dot notation (person1.name,
person1.age, etc.).
We compare instances using the == operator, which calls the generated equals() method to
compare property values.
We create a copy of a data class instance using the copy() method, with modified properties (in
this case, modifying the name property).
We demonstrate the automatically generated toString() method by printing the details of a
Person instance directly.

(b) Explain the concept of null safety in Kotlin with suitable example.
In Kotlin, null safety is a built-in feature that helps eliminate the risk of null references, also
known as the “The Billion Dollar Mistake”. Kotlin’s type system is designed to distinguish
nullable references from non-nullable ones.

Here’s how it works:

Non-Nullable Types: By default, all types are non-nullable, which means you cannot assign
null to a variable of a non-nullable type. For example:

var nonNullableString: String = "Hello, World!"

nonNullableString = null // This will cause a compile error

In this code, nonNullableString is a non-nullable String, so trying to assign null to it will cause a
compile error.

Nullable Types: If you want to allow null values, you can declare a variable as nullable by
appending a ? to the type. For example:

var nullableString: String? = "Hello, World!"

nullableString = null // This is allowed

In this code, nullableString is a nullable String, so you can assign null to it without any issues.

Safe Calls (?.) and the Elvis Operator (?:): When you’re dealing with nullable types, you
need to handle the possibility of null values. You can use safe calls (?.) to only call a method or
access a property if the receiver is non-null. If the receiver is null, the whole expression will be
null. You can also use the Elvis operator (?:) to provide a default value when the receiver is null.
For example:

val length: Int? = nullableString?.length // This will be null if nullableString is null

val safeLength: Int = nullableString?.length ?: 0 // This will be 0 if nullableString is null

In this code, length will be null if nullableString is null, and safeLength will be 0 if
nullableString is null.

6. (a) Write in detail with example about construct in kotlin.

In Kotlin, constructors are used to initialize the properties of a class when an instance of the
class is created. There are two types of constructors in Kotlin: primary constructors and
secondary constructors.

1. Primary Constructor:
The primary constructor is declared in the class header as part of the class declaration. It is
responsible for initializing the properties of the class. Here's an example of a class with a
primary constructor:

class Person(val name: String, var age: Int) {


// Initialization block executed during object creation
init {
println("Person $name created with age $age")
}

// Member function to display information


fun displayInfo() {
println("Name: $name, Age: $age")
}
}

fun main() {
// Creating an instance of Person using the primary constructor
val person = Person("John Doe", 30)

// Accessing properties and calling member functions


person.displayInfo()
}
2. Secondary Constructor:
In Kotlin, a class can have one or more secondary constructors in addition to the primary
constructor. Secondary constructors are defined using the constructor keyword. Here's an
example of a class with a secondary constructor:
class Person {
var name: String
var age: Int

// Secondary constructor with parameters


constructor(name: String, age: Int) {
this.name = name
this.age = age
println("Person $name created with age $age")
}

// Member function to display information


fun displayInfo() {
println("Name: $name, Age: $age")
}
}

fun main() {
// Creating an instance of Person using the secondary constructor
val person = Person("Jane Smith", 25)

// Accessing properties and calling member functions


person.displayInfo()
}

(b) Explain about the “when” keyword in the context of Kotlin.

The when keyword in Kotlin is a powerful replacement for the traditional switch statement
found in many other programming languages. It provides a concise and expressive way to write
conditional branches based on the value of an expression. Here's how when works in Kotlin:

Basic Syntax:
The basic syntax of when is as follows:

when (expression) {
value1 -> action1
value2 -> action2
...
else -> defaultAction
}
expression: The value or expression to be evaluated.
value1, value2, etc.: Possible values or conditions that expression can match.
action1, action2, etc.: Actions to be performed if the corresponding value matches expression.
else: Optional, provides a default action if none of the values match.
Example:
Here's an example of using when to check the value of a variable and perform different actions
based on its value:
fun describeNumber(number: Int) {
when (number) {
1 -> println("One")
2 -> println("Two")
3 -> println("Three")
else -> println("Other")
}
}

fun main() {
describeNumber(2) // Outputs: Two
describeNumber(5) // Outputs: Other
}
In this example:

The describeNumber function takes an integer number as a parameter.


The when expression checks the value of number and executes the corresponding branch.
If number is 1, it prints "One". If number is 2, it prints "Two". If number is 3, it prints "Three".
Otherwise, it prints "Other".

Additional Features:

Multiple Conditions:

when (number) {
1, 2 -> println("One or Two")
3, 4 -> println("Three or Four")
else -> println("Other")
}
Ranges:

when (number) {
in 1..5 -> println("Number is between 1 and 5")
!in 10..20 -> println("Number is not between 10 and 20")
else -> println("Other")
}
Type Checks:

when (obj) {
is String -> println("Object is a String")
is Int -> println("Object is an Int")
else -> println("Other")
}
Smart Casts:

when (obj) {
is String -> println(obj.length) // obj is automatically cast to String
is Int -> println(obj * 2) // obj is automatically cast to Int
else -> println("Other")
}

when in Kotlin is versatile and can handle a wide range of conditions and scenarios, making it
a flexible and powerful tool for writing conditional logic in a concise and readable manner.
UNIT – 2
1. (a) Explain the activity life cycle and callback functions in Android Application.

1. onCreate(): Called when the activity is first created. It is used for initialization, such as
setting up UI components and data structures.
2. onStart(): Called when the activity becomes visible to the user. This is where you can
start animations or perform UI updates.
3. onResume(): Called when the activity is ready to interact with the user. You can start
tasks that should continue while the activity is in the foreground.
4. onPause(): Called when the activity is partially obscured by another activity. Use this
method to pause ongoing tasks or save user data.
5. onStop(): Called when the activity is no longer visible to the user. Release resources or
stop processes that are no longer needed.
6. onDestroy(): Called when the activity is about to be destroyed. Clean up any resources or
unregister listeners.

(b)With neat diagram explain the framework architecture of Android?

The main components of android architecture


are following:-
 Applications
 Application Framework
 Android Runtime
 Platform Libraries
 Linux Kernel
Applications –
Applications is the top layer of android
architecture. The pre-installed applications like
home, contacts, camera, gallery etc and third
party applications downloaded from the play
store like chat applications, games etc. will be
installed on this layer only.
It runs within the Android run time with the help of the classes and services provided by the
application framework.
Application framework –
Application Framework provides several important classes which are used to create an Android
application. It provides a generic abstraction for hardware access and also helps in managing the
user interface with application resources. Generally, it provides the services with the help of
which we can create a particular class and make that class helpful for the Applications creation.
It includes different types of services activity manager, notification manager, view system,
package manager etc. which are helpful for the development of our application according to the
prerequisite.
Application runtime –
Android Runtime environment is one of the most important part of Android. It contains
components like core libraries and the Dalvik virtual machine(DVM). Mainly, it provides the
base for the application framework and powers our application with the help of the core
libraries.
Like Java Virtual Machine (JVM), Dalvik Virtual Machine (DVM) is a register-based virtual
machine and specially designed and optimized for android to ensure that a device can run
multiple instances efficiently. It depends on the layer Linux kernel for threading and low-level
memory management. The core libraries enable us to implement android applications using the
standard JAVA or Kotlin programming languages.
Platform libraries –
The Platform Libraries includes various C/C++ core libraries and Java based libraries such as
Media, Graphics, Surface Manager, OpenGL etc. to provide a support for android development.
 Media library provides support to play and record an audio and video formats.
 Surface manager responsible for managing access to the display subsystem.
 SGL and OpenGL both cross-language, cross-platform application program interface
(API) are used for 2D and 3D computer graphics.
 SQLite provides database support and FreeType provides font support.
 Web-Kit This open source web browser engine provides all the functionality to display
web content and to simplify page loading.
 SSL (Secure Sockets Layer) is security technology to establish an encrypted link
between a web server and a web browser.
Linux Kernel –
Linux Kernel is heart of the android architecture. It manages all the available drivers such as
display drivers, camera drivers, Bluetooth drivers, audio drivers, memory drivers, etc. which are
required during the runtime.
The Linux Kernel will provide an abstraction layer between the device hardware and the other
components of android architecture. It is responsible for management of memory, power,
devices etc.
The features of Linux kernel are:
 Security: The Linux kernel handles the security between the application and the system.
 Memory Management: It efficiently handles the memory management thereby
providing the freedom to develop our apps.
 Process Management: It manages the process well, allocates resources to processes
whenever they need them.
 Network Stack: It effectively handles the network communication.
 Driver Model: It ensures that the application works properly on the device and hardware
manufacturers responsible for building their drivers into the Linux build.

2. (a) Explain core building blocks of Android application?

The core building blocks of an Android application are fundamental components that work
together to create a functional and interactive user experience. These building blocks include:
1. Activities: Activities represent the UI (User Interface) of an application. Each screen in
an Android app is typically represented by an activity. Activities can contain layouts, user
interface elements, and respond to user interactions.
2. Services: Services are components that run in the background to perform long-running
operations or handle tasks without a user interface. They can play music, download files,
or perform other tasks that don't require user interaction.
3. Broadcast Receivers: Broadcast Receivers respond to system-wide broadcast
announcements, such as when the device's battery is low or when a message is received.
They can perform actions based on these broadcasts, such as displaying a notification.
4. Content Providers: Content Providers manage access to a structured set of data. They
allow applications to share data with other apps or access data from other apps. Content
Providers are often used to access data from the device's built-in databases or other
external sources.
5. Fragments: Fragments represent reusable portions of a UI in an activity. They allow for
more modular and flexible UI designs, especially for larger screens like tablets where
multiple UI components may be displayed simultaneously.
6. Intents: Intents are messages that allow components to request functionality from other
components within the application or even from external applications. They can be used
to start activities, services, or broadcast actions.
7. Manifest File: The AndroidManifest.xml file describes essential information about the
application to the Android system. It includes details such as the app's package name,
permissions required, declared components (activities, services, etc.), and other
configuration settings.

(b) Write the code for dynamics textview and provide action to the textview in android?

MainActivity.kt
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// Create a TextView dynamically


val dynamicTextView = TextView(this)
dynamicTextView.text = "Click me!"
dynamicTextView.textSize = 18f
dynamicTextView.setOnClickListener {
// Action to perform when TextView is clicked
dynamicTextView.text = "TextView clicked!"
}

// Add the dynamic TextView to a layout (e.g., LinearLayout)


val linearLayout = findViewById<View>(R.id.linearLayout)
linearLayout.addView(dynamicTextView)
}
}

3. Write an android programming to change the layout background color using radio
button(use minimum 3 buttons).

Activity_main.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">

<RadioButton
android:id="@+id/radioButtonRed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Red" />

<RadioButton
android:id="@+id/radioButtonGreen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Green" />

<RadioButton
android:id="@+id/radioButtonBlue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Blue" />

<Button
android:id="@+id/buttonApply"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Apply Color" />

</LinearLayout>
MainActivity.kt

import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.RadioButton
import android.widget.RadioGroup

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val radioButtonRed = findViewById<RadioButton>(R.id.radioButtonRed)


val radioButtonGreen = findViewById<RadioButton>(R.id.radioButtonGreen)
val radioButtonBlue = findViewById<RadioButton>(R.id.radioButtonBlue)
val buttonApply = findViewById<Button>(R.id.buttonApply)

buttonApply.setOnClickListener {
when {
radioButtonRed.isChecked -> changeBackgroundColor(Color.RED)
radioButtonGreen.isChecked -> changeBackgroundColor(Color.GREEN)
radioButtonBlue.isChecked -> changeBackgroundColor(Color.BLUE)
}
}
}

private fun changeBackgroundColor(color: Int) {


val layout = findViewById<LinearLayout>(R.id.linearLayout)
layout.setBackgroundColor(color)
}
}
4. Create an android application with a login page and a profile page, Perform the
following validation :
If username should be giet@gmail.com HYPERLINK "mailto:giet@gmail.com" and
password is giet@123, Username and password should not be blank and On successful
validation, the profile page will open with a message “Welcome : GIET”

Login.kt
package com.example.sectionb

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.example.sectionb.databinding.ActivityLoginBinding

class Login : AppCompatActivity() {


lateinit var binding: ActivityLoginBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding=ActivityLoginBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.btnLogin.setOnClickListener {
val email:String=binding.editEmail.text.toString()
val password:String=binding.editPw.text.toString()
if(!email.isEmpty() && !password.isEmpty())
{
if(email.equals("giet@gmail.com") && password.equals("giet@123"))
{
val intent= Intent(this,Home::class.java)
intent.putExtra("myemail",email)
startActivity(intent)
}
else
{
Toast.makeText(this,"Invalid Userid or password",Toast.LENGTH_LONG).show()
}
}
else
{
Toast.makeText(this,"Blank userid or password",Toast.LENGTH_LONG).show()
}
}
}
}
activity_login.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=".Login">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="120dp"
android:layout_marginEnd="55dp"
android:text="Enter User Id"
app:layout_constraintEnd_toStartOf="@+id/editEmail"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<EditText
android:id="@+id/editEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="112dp"
android:layout_marginEnd="13dp"
android:ems="10"
android:inputType="textEmailAddress"
android:minHeight="48dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/textView"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="SpeakableTextPresentCheck" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="47dp"
android:layout_marginEnd="50dp"
android:text="Enter Password"
app:layout_constraintEnd_toStartOf="@+id/editPw"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />

<EditText
android:id="@+id/editPw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="13dp"
android:layout_marginEnd="16dp"
android:ems="10"
android:inputType="textPassword"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/textView2"
app:layout_constraintTop_toBottomOf="@+id/editEmail"
tools:ignore="SpeakableTextPresentCheck,TouchTargetSizeCheck" />

<Button
android:id="@+id/btnLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="72dp"
android:layout_marginEnd="162dp"
android:text="Login"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editPw" />
</androidx.constraintlayout.widget.ConstraintLayout>

Home.kt

package com.example.sectionb
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.sectionb.databinding.ActivityHomeBinding
import com.example.sectionb.databinding.ActivityLoginBinding

class Home : AppCompatActivity() {


lateinit var binding: ActivityHomeBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding=ActivityHomeBinding.inflate(layoutInflater)
setContentView(binding.root)
val email=intent.getStringExtra("myemail")
binding.tvHome.text="Welcome $email"
}
}
activity_home.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=".Home">

<TextView
android:id="@+id/tvHome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="128dp"
android:layout_marginTop="161dp"
android:layout_marginEnd="226dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

5. Illustrate in detailed about dynamic view in android programming.

Dynamic views in Android are used when you want to create UI elements on the fly or modify
the properties of UI elements after they’ve been drawn on the screen. They are particularly
useful when you don’t want to have repeating XML code.

Here’s a detailed explanation:

RecyclerView: It’s a ViewGroup that contains the views corresponding to your data. It’s a view
itself, so you add RecyclerView to your layout the way you would add any other UI element.
ViewHolder: Each individual element in the list is defined by a view holder object. When the
view holder is created, it doesn’t have any data associated with it. After the view holder is
created, the RecyclerView binds it to its data. You define the view holder by extending
RecyclerView.ViewHolder.

Adapter: The RecyclerView requests views, and binds the views to their data, by calling
methods in the adapter. You define the adapter by extending RecyclerView.Adapter.

LayoutManager: The layout manager arranges the individual elements in your list. You can use
one of the layout managers provided by the RecyclerView library, or you can define your own.

Adding Views Dynamically: Dynamic Views are created when we don’t want to have repeating
XML code. In this case, we create a separate layout and inflate them inside a LinearLayout.

Storing Data: After creating the views, we can store the user data in an ArrayList and then
display them.

Animations: To move, reveal, or hide views within the current layout, you can use the property
animation system provided by the android.animation package.
UNIT – 3

1. Create an android application to create 3 buttons with label red,green and blue. On
clicking any button, a textview “Welcome” will be displayed in the specified colour.

MainActivity.kt

import android.graphics.Color import android.os.Bundle


import android.view.View import
androidx.appcompat.app.AppCompatActivity import
kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() { override fun


onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

btnRed.setOnClickListener { changeTextColor(Color.RED) }
btnGreen.setOnClickListener { changeTextColor(Color.GREEN) }
btnBlue.setOnClickListener { changeTextColor(Color.BLUE) }

private fun changeTextColor(color: Int) {


textViewWelcome.setTextColor(color)

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

<Button android:id="@+id/btnRed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Red" />

<Button android:id="@+id/btnGreen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Green" />

<Button android:id="@+id/btnBlue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Blue" />

<TextView
android:id="@+id/textViewWelcome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome" android:textSize="24sp"
/>

</LinearLayout>

2.DIffereence between linear layout and relative layout and example

LinearLayout RelativeLayout

We can adjust views and widgets


linearly i.e. Horizontally and We can adjust views and widgets
vertically. according to one’s satisfaction.

layout_weight attribute in the


linear layout is used to specify
the equal or specific size to the Various attributes
like: layout_toRightOf,
particular widget and view by
layout_toLeftOf,
using the following attribute.
layout_below, layout_alignParentTop,
android:layout_weight = ‘0’
layout_top, layout_alignParentLeft,
Here Weight is specified as 0 in
layout_alignParentRight are used to
order to give equal size or space
specify the position of each view and
to each view or widget.
widget.

It is useful when we arrange It is useful when we arrange views in a


views in a linear fashion relative fashion.

Syntax: Syntax:
<LinearLayout> <RelativeLayout>
<!–Views, widgets–> <!–Views, Widgets–>
</LinearLayout> </RelativeLayout>
Example: In various Apps,
LinearLayout is mainly
applicable in the SignUp screen Example: In Google Play Store, when we
where Name, Email, Phone open the app, the games, books, movies,
Number, Submit, etc. are and App’s sections all are arranges in
arranged in a linear fashion. Relative Layout Fashion.

LinearLayout RelativeLayout

LinearLayout is less used as RelativeLayout is used more in


compared to RelativeLayout. applications.

We can use LinearLayout inside We can also use RelativeLayout as a Child


RelativeLayout. of LinearLayout.

### LinearLayout:

**Example:**

```xml

<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="First Text" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Second Text" />

</LinearLayout>

```

In this example, the TextViews are arranged vertically one below the other within the
LinearLayout.

### RelativeLayout:

**Example:**

```xml

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<Button android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 1"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true" />
<Button android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 2"
android:layout_below="@id/button1"
android:layout_alignParentRight="true" />

</RelativeLayout>

```

In this example, Button 1 is positioned at the top-left corner of the RelativeLayout, and Button 2
is positioned below Button 1 and aligned to the parent's right edge.
UNIT – 4

1.Describe how to use shared preference with an example

Creating Shared Preferences:

First, create a shared preferences file for your app. Name it uniquely using your app’s package
name (e.g., com.example.myapp_preferences).

To get the shared preferences, call the getSharedPreferences() method:

SharedPreferences sharedPreferences =
getSharedPreferences("com.example.myapp_preferences", Context.MODE_PRIVATE);

Storing Data:

You can save data using the SharedPreferences.Editor class. For example, let’s save a user’s
username:

SharedPreferences.Editor editor = sharedPreferences.edit();

editor.putString("username", "myuser123");

editor.apply(); // Commit the changes

Retrieving Data:

To retrieve the stored data, use the getString() method:

String savedUsername = sharedPreferences.getString("username", "default_username");

Use Cases:

Shared Preferences are suitable for:

Saving user settings (e.g., theme preference).

Data that should be remembered across sessions (e.g., user preferences).

Storing simple data types (e.g., strings, integers, booleans).

2. Explain various classes and functions required for SQLite connection

SQLiteOpenHelper:
This class helps in managing database creation and version management.

It provides methods to create, upgrade, and downgrade the database schema.

You need to subclass SQLiteOpenHelper and implement the onCreate() and onUpgrade()
methods.

I.SQLiteDatabase:

This class represents a connection to the SQLite database.

It provides methods for executing SQL statements, such as query(), insert(), update(), and
delete().

You can obtain an instance of SQLiteDatabase from SQLiteOpenHelper.

II.SQLiteOpenHelper Subclass:

Create a subclass of SQLiteOpenHelper and implement its methods:

onCreate(): Called when the database is created for the first time. You should create your
database

tables here.

onUpgrade(): Called when the database needs to be upgraded. You should handle schema
changes here.

III.Context:

You need a Context object to create an instance of SQLiteOpenHelper.

Typically, you pass the application context to the SQLiteOpenHelper constructor.

IV.Cursor:

A Cursor object allows you to retrieve data from a query result.

It provides methods to move through the result set and retrieve data from each row.

V.ContentValues:

ContentValues is a key-value pair container used to insert or update values into the database.

You populate ContentValues with column-value pairs and pass it to SQLiteDatabase insert() or
update() methods.

VI.SQL Statements:

You use SQL statements to interact with the database, such as CREATE TABLE, SELECT,
INSERT,

UPDATE, and DELETE.

You can execute raw SQL statements using SQLiteDatabase's execSQL() method.

VII.Error Handling:

Handle exceptions that may occur during database operations, such as SQLiteException.

Implement error handling to gracefully manage database-related errors.

3. Explain the process of storing and retrieve data from SQLite database.

### Storing Data:

1. **Create a Database Helper Class**:

- Create a subclass of SQLiteOpenHelper to manage database creation and version


management.

- Override the onCreate() method to create database tables and the onUpgrade() method to
handle

schema changes.

2. **Open or Create Database**:

- Obtain an instance of SQLiteDatabase from your database helper class.

- If the database does not exist, SQLiteOpenHelper's onCreate() method will be called to
create it.

3. **Prepare Data**:

- Prepare the data you want to store in the database.

- Data can be organized in ContentValues objects, where each key-value pair represents a
columnvalue mapping.
4. **Insert Data**:

- Use SQLiteDatabase's insert() method to insert data into the database.

- Pass the table name, nullColumnHack (optional), and ContentValues object to the insert()

method.

### Retrieving Data:

1. **Query Data**:

- Use SQLiteDatabase's query() method to retrieve data from the database.

- Specify the table name, columns to retrieve, selection criteria (optional), selection arguments

(optional), group by clause (optional), having clause (optional), order by clause (optional), and
limit

clause (optional).

2. **Process Cursor**:

- The query() method returns a Cursor object that points to the result set.

- Use methods like moveToFirst(), moveToNext(), and getColumnIndex() to iterate through


the

result set and extract data.

3. **Retrieve Data**:

- Use Cursor's getter methods (e.g., getInt(), getString()) to retrieve data from each row of the

result set.

- Extract data based on column indexes or column names.

4. **Close Cursor and Database**:

- Close the Cursor when you're done processing data to release associated resources.

- Close the database connection using SQLiteDatabase's close() method when it's no longer

needed.

4. Describe the way to persist information in an android device


In Android development, there are several ways to persist information on an Android device,

depending on the type of data and the requirements of your application. Here are some
common

methods:

1. **Shared Preferences**:

- Shared Preferences is a simple key-value pair storage mechanism provided by Android.

- It's suitable for storing small amounts of primitive data types like integers, booleans, floats,
and

strings.

- SharedPreferences provides a way to save and retrieve data across app launches.

- This method is commonly used for storing user preferences, settings, and other lightweight

data.

2. **Internal Storage**:

- Internal Storage is private storage space allocated to each app by the Android system.

- You can write data to files in internal storage using FileOutputStream or other file I/O
classes.

- This method is suitable for storing sensitive data or files that are only accessible to your app.

- Internal storage is not accessible to users or other apps unless the device is rooted.\

3. **External Storage**:

- External Storage provides a shared storage space that's accessible by all apps and users.

- You can write data to external storage using standard file I/O operations.

- External storage includes the device's external storage (e.g., SD card) and any USB mass
storage

devices connected to the device.

- Access to external storage requires the WRITE_EXTERNAL_STORAGE permission.


4. **SQLite Database**:

- SQLite is a lightweight relational database management system included with Android.

- It provides a structured and efficient way to store and retrieve structured data.

- SQLite databases are suitable for storing larger amounts of structured data, such as user

profiles, app data, or cached data.

- You can interact with SQLite databases using the SQLiteDatabase class provided by the
Android

SDK.

5. **Room Persistence Library**:

- Room is a persistence library provided by the Android Jetpack components.

- It provides an abstraction layer over SQLite databases, making it easier to work with
databases

in Android apps.

- Room simplifies tasks like defining database schemas, executing queries, and observing

database changes.

- It's suitable for apps that require complex data models or need to perform advanced database

operations.

6. **Network Storage**:

- You can also persist data on remote servers or cloud storage services.

- This method allows you to synchronize data across multiple devices and provides scalability
and

accessibility.

- Common approaches include using RESTful APIs, Firebase Realtime Database, Google
Cloud

Storage, or other cloud services.


5. Explain the process of storing and retrieve data from Firebase database.

Storing and retrieving data from a Firebase Realtime Database in an Android application
involves

several steps. Here's a breakdown of the process:

### Storing Data:

1. **Set Up Firebase**:

- Add the Firebase SDK to your Android project by following the setup instructions provided
by

Firebase.

- Configure your Android app to use Firebase services by adding the necessary configuration
files.

2. **Get a Reference to the Database**:

- Obtain a reference to your Firebase Realtime Database using the

FirebaseDatabase.getInstance().getReference() method.

3. **Prepare Data**:

- Prepare the data you want to store in the database.

- Data can be organized as a Java object or as a key-value pair (HashMap).

4. **Write Data**:

- Use the DatabaseReference object obtained in step 2 to write data to the database.

- Call methods like setValue() or updateChildren() to store data at the desired location in the

database.

### Retrieving Data:

1. **Read Data**:

- Use ValueEventListener or ChildEventListener to read data from the database.


- ValueEventListener provides a snapshot of the entire data at a given path, while

ChildEventListener listens for changes to the child nodes of a specific path.

2. **Handle Data Changes**:

- Implement the onDataChange() method of ValueEventListener or ChildEventListener to


handle

changes to the data.

- Update your UI or perform other actions based on the retrieved data.

5. Explain with suitable example for navigation using map API.

Step 1: Set Up Google Maps API

Add the Google Maps API key to your Android project by following the setup instructions
provided by

Google.

Enable the necessary permissions and dependencies in your app's manifest file.

Step 2: Design UI Layout

Design the user interface layout for your app, including text fields for entering source and
destination

addresses, and a button to initiate navigation.

Step 3: Implement Navigation Logic

Use the Places API to enable autocomplete functionality for the source and destination text
fields.

Implement logic to fetch latitude and longitude coordinates for the entered source and
destination

addresses using Geocoding API.

Use the Directions API to request navigation directions between the source and destination

coordinates.
Parse the response from the Directions API to extract the route details (such as polyline points).

Display the navigation route on a Google Map using PolylineOptions to draw polylines
between the

source and destination coordinates.

Step 4: Example Code Snippet

Here's a simplified example code snippet to demonstrate how you can implement navigation
using

the Google Maps API:

// Get source and destination addresses from text fields

val sourceAddress = editTextSource.text.toString()

val destinationAddress = editTextDestination.text.toString()

// Use Places API to fetch place IDs for source and destination

val sourcePlaceId = getPlaceId(sourceAddress)

val destinationPlaceId = getPlaceId(destinationAddress)

// Use Geocoding API to fetch latitude and longitude coordinates for source and destination

val sourceLatLng = getLatLng(sourcePlaceId)

val destinationLatLng = getLatLng(destinationPlaceId)

// Use Directions API to fetch navigation route between source and destination

val route = getNavigationRoute(sourceLatLng, destinationLatLng)

// Draw navigation route on Google Map

drawRouteOnMap(route)

From Haan Haan

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy