0% found this document useful (0 votes)
102 views

Android App Development: Six Weeks Summer Training On

The document is a six-week summer training report submitted by Tarun Sharma, a student in the electronics and communications department at UIET(KUK). It includes an acknowledgement thanking the internship program and tutors for providing guidance. The report then covers topics on Kotlin programming language including what Kotlin is, why use Kotlin, Kotlin syntax, output functions, comments, variables, and data types.

Uploaded by

Tarun Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
102 views

Android App Development: Six Weeks Summer Training On

The document is a six-week summer training report submitted by Tarun Sharma, a student in the electronics and communications department at UIET(KUK). It includes an acknowledgement thanking the internship program and tutors for providing guidance. The report then covers topics on Kotlin programming language including what Kotlin is, why use Kotlin, Kotlin syntax, output functions, comments, variables, and data types.

Uploaded by

Tarun Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 71

SIX WEEKS SUMMER TRAINING

REPORT

On

Android App Development

Submitted by:

TARUN SHARMA
Roll no. : 252001003
Department : ECE A

Submitted to:

Mr. Nafeesh Ahmad sir


Electronics and Communications Department
UIET(KUK)

1
Certificate

2
ACKNOWLEDGEMENT

I wish to express my gratitude to, my tutor at


Internshala for providing me an opportunity to do my
internship and project work in “Android App
Development”. Under their guidance I have completed
my project and tried my best to implement what I had
learnt till now. I sincerely thank Mr. Nikhil Marriwala
sir, our T&P head and
Mr. Nasheef Ahmad for their guidance and
encouragement to do my Internship. He also helped me
by updating us about the information of what to do and
not to do during our internship and help us with all. I
also thanks my friend for helping me with my problem
that I faced in my project.

What is Kotlin?
Kotlin is a modern, trending programming language that was released
in 2016 by JetBrains.

3
It has become very popular since it is compatible with J (one of the
most popular programming languages out there), which means that
Java code (and libraries) can be used in Kotlin programs.

Kotlin is used for:

 Mobile applications (specially Android apps)


 Web development
 Server side applications
 Data science
 And much, much more!

Why Use Kotlin?


 Kotlin is fully compatible with Java
 Kotlin works on different platforms (Windows, Mac, Linux,
Raspberry Pi, etc.)
 Kotlin is concise and safe
 Kotlin is easy to learn, especially if We already know Java
 Kotlin is free to use
 Big community/support

Kotlin Syntax
In the previous chapter, we created a Kotlin file called Main.kt, and we
used the following code to print "Hello World" to the screen:

Example
fun main() {
  println("Hello World")
}

4
Example explained

The fun keyword is used to declare a function. A function is a block of


code designed to perform a particular task. In the example above, it
declares the main() function.

The main() function is something We will see in every Kotlin program.


This function is used to execute code. Any code inside the main()
function's curly brackets {} will be executed.

For example, the println() function is inside the main() function, meaning
that this will be executed. The println() function is used to output/print
text, and in our example it will output "Hello World".

Good To Know: In Kotlin, code statements do not have to end with a


semicolon (;) (which is often required for other programming
languages, such as Java, C++, C#, etc.).

Main Parameters
Before Kotlin version 1.3, it was required to use the main() function
with parameters, like: fun main(args : Array<String>). The example above
had to be written like this to work:

Example
fun main(args : Array<String>) {
  println("Hello World")
}
Note: This is no longer required, and the program will run fine without it.
However, it will not do any harm if We have been using it in the past, and will
continue to use it.

5
Kotlin Output (Print)
The println() function is used to output values/print text:

Example
fun main() {
  println("Hello World")
}

We can add as many println() functions as We want. Note that it will


add a new line for each function:

Example
fun main() {
  println("Hello World!")
  println("I am learning Kotlin.")
  println("It is awesome!")
}

We can also print numbers, and perform mathematical calculations:

Example
fun main() {
  println(3 + 3)
}

The print() function


There is also a print() function, which is similar to println(). The only
difference is that it does not insert a new line at the end of the output:

Example
fun main() {
  print("Hello World! ")
  print("I am learning Kotlin. ")

6
  print("It is awesome!")
}

Note that we have added a space character to create a space between


the sentences.

Kotlin Comments
Comments can be used to explain Kotlin code, and to make it more
readable. It can also be used to prevent execution when testing
alternative code.

Single-line Comments
Single-line comments starts with two forward slashes (//).

Any text between // and the end of the line is ignored by Kotlin (will
not be executed).

This example uses a single-line comment before a line of code:

Example
// This is a comment
println("Hello World")

This example uses a single-line comment at the end of a line of code:

Example
println("Hello World")  // This is a comment

7
Multi-line Comments
Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by Kotlin.

This example uses a multi-line comment (a comment block) to


explain the code:

Example
/* The code below will print the words Hello World
to the screen, and it is amazing */
println("Hello World") 

Kotlin Variables
Variables are containers for storing data values.

To create a variable, use var or val, and assign a value to it with the
equal sign (=):

Syntax
var variableName = value
val variableName = value
Example
var name = "John"
val birthyear = 1975

println(name)          // Print the value of name


println(birthyear)     // Print the value of birthyear

The difference between var and val is that variables declared with the
var keyword can be changed/modified, while val variables cannot.

8
Variable Type
Unlike many other programming languages, variables in Kotlin do not
need to be declared with a specified type (like "String" for text or
"Int" for numbers, if We are familiar with those).

To create a variable in Kotlin that should store text and another that
should store a number, look at the following example:

Example
var name = "John"      // String (text)
val birthyear = 1975   // Int (number)

println(name)          // Print the value of name


println(birthyear)     // Print the value of birthyear

Kotlin is smart enough to understand that "John" is a String (text), and


that 1975 is an Int (number) variable.

However, it is possible to specify the type if We insist:

Example
var name: String = "John" // String
val birthyear: Int = 1975 // Int

println(name)
println(birthyear)

We can also declare a variable without assigning the value, and


assign the value later. However, this is only possible when We
specify the type:

Example

This works fine:

9
var name: String
name = "John"
println(name)
Example

This will generate an error:


var name
name = "John"
println(name)

Note: We will learn more about Data Types in the next chapter.

Notes on val
When We create a variable with the val keyword, the value cannot be
changed/reassigned.

The following example will generate an error:

Example
val name = "John"
name = "Robert"  // Error (Val cannot be reassigned)
println(name)

When using var, We can change the value whenever We want:

Example
var name = "John"
name = "Robert"
println(name)
So When To Use val?

The val keyword is useful when We want a variable to always store


the same value, like PI (3.14159...):

10
Example
val pi = 3.14159265359
println(pi)

Display Variables
Like We have seen with the examples above, the println() method is
often used to display variables.

To combine both text and a variable, use the + character:

Example
val name = "John"
println("Hello " + name)

We can also use the + character to add a variable to another variable:

Example
val firstName = "John "
val lastName = "Doe"
val fullName = firstName + lastName
println(fullName)

For numeric values, the + character works as a mathematical operator:

Example
val x = 5
val y = 6
println(x + y) // Print the value of x + y

From the example above, We can expect:


 x stores the value 5
 y stores the value 6
 Then we use the println() method to display the value of x + y, which is 11

11
Variable Names
A variable can have a short name (like x and y) or more descriptive
names (age, sum, totalVolume).

The general rule for Kotlin variables are:


 Names can contain letters, digits, underscores, and dollar signs
 Names should start with a letter
 Names can also begin with $ and _ (but we will not use it in this tutorial)
 Names are case sensitive ("myVar" and "myvar" are different variables)
 Names should start with a loourcase letter and it cannot contain
whitespace
 Reserved words (like Kotlin keywords, such as var or String) cannot be
used as names

camelCase variables

We might notice that we used firstName and lastName as variable


names in the example above, instead of firstname and lastname. This
is called "camelCase", and it is considered as good practice as it
makes it easier to read when We have a variable name with different
words in it, for example "myFavoriteFood", "rateActionMovies" etc.

Kotlin Data Types


In Kotlin, the type of a variable is decided by its value:

Example
val myNum = 5             // Int
val myDoubleNum = 5.99    // Double
val myLetter = 'D'        // Char

12
val myBoolean = true      // Boolean
val myText = "Hello"      // String

However, We learned from the previous chapter that it is possible to


specify the type if We want:

Example
val myNum: Int = 5                // Int
val myDoubleNum: Double = 5.99    // Double
val myLetter: Char = 'D'          // Char
val myBoolean: Boolean = true     // Boolean
val myText: String = "Hello"      // String

Sometimes We have to specify the type, and often We don't.


Anyhow, it is good to know what the different types represent.

We will learn more about when We need to specify the type later.

Data types are divided into different groups:


 Numbers
 Characters
 Booleans
 Strings
 Arrays

Numbers
Number types are divided into two groups:

Integer types store whole numbers, positive or negative (such as 123


or -456), without decimals. Valid types are Byte, Short, Int and Long.

Floating point types represent numbers with a fractional part,


containing one or more decimals. There are two types: Float and Double.

13
If We don't specify the type for a numeric variable, it is most often
returned as Int for whole numbers and Double for floating point
numbers.

Integer Types
Byte

The Byte data type can store whole numbers from -128 to 127. This
can be used instead of Int or other integer types to save memory when
We are certain that the value will be within -128 and 127:

Example
val myNum: Byte = 100
println(myNum)
Short

The Short data type can store whole numbers from -32768 to 32767:

Example
val myNum: Short = 5000
println(myNum)
Int

The Int data type can store whole numbers from -2147483648 to
2147483647:

Example
val myNum: Int = 100000
println(myNum)
Long

The Long data type can store whole numbers from


-9223372036854775808 to 9223372036854775808. This is used

14
when Int is not large enough to store the value. Optionally, We can
end the value with an "L":

Example
val myNum: Long = 15000000000L
println(myNum)

Difference Between Int and Long


A whole number is an Int as long as it is up to 2147483647. If it goes
beyond that, it is defined as Long:

Example
val myNum1 = 2147483647  // Int
val myNum2 = 2147483648  // Long

Floating Point Types


Floating point types represent numbers with a decimal, such as 9.99
or 3.14515.

Float

The Float data type can store fractional numbers from 3.4e−038 to
3.4e+038. Note that We should end the value with an "F":

Example
val myNum: Float = 5.75F
println(myNum)
Double

The Double data type can store fractional numbers from 1.7e−308 to
1.7e+038:

15
Example
val myNum: Double = 19.99
println(myNum)

Use Float or Double?

The precision of a floating point value indicates how many digits the
value can have after the decimal point. The precision of Float is only
six or seven decimal digits, while Double variables have a precision of
about 15 digits. Therefore it is safer to use Double for most
calculations.

Scientific Numbers

A floating point number can also be a scientific number with an "e" or


"E" to indicate the poour of 10:

Example
val myNum1: Float = 35E3F
val myNum2: Double = 12E4
println(myNum1)
println(myNum2)

Booleans
The Boolean data type and can only take the values true or false:

Example
val isKotlinFun: Boolean = true
val isFishTasty: Boolean = false
println(isKotlinFun)   // Outputs true
println(isFishTasty)   // Outputs false

Boolean values are mostly used for conditional testing, which We


will learn more about in a later chapter.

16
Characters
The Char data type is used to store a single character. A char value
must be surrounded by single quotes, like 'A' or 'c':

Example
val myGrade: Char = 'B'
println(myGrade)

Unlike Java, We cannot use ASCII values to display certain


characters. The value 66 would output a "B" in Java, but will generate
an error in Kotlin:

Example
val myLetter: Char = 66
println(myLetter) // Error

Strings
The String data type is used to store a sequence of characters (text).
String values must be surrounded by double quotes:

Example
val myText: String = "Hello World"
println(myText)

We will learn more about strings in the Strings chapter.

Arrays
Arrays are used to store multiple values in a single variable, instead of
declaring separate variables for each value.

We will learn more about arrays in the Arrays chapter.

17
Type Conversion
Type conversion is when We convert the value of one data type to
another type.

In Kotlin, numeric type conversion is different from Java. For


example, it is not possible to convert an Int type to a Long type with the
following code:

Example
val x: Int = 5
val y: Long = x
println(y) // Error: Type mismatch

To convert a numeric data type to another type, We must use one of


the following functions: toByte(), toShort(), toInt(), toLong(), toFloat(), toDouble()
or toChar():

Example
val x: Int = 5
val y: Long = x.toLong()
println(y)

Kotlin Operators
Operators are used to perform operations on variables and values.

The value is called an operand, while the operation (to be performed


between the two operands) is defined by an operator:

18
Operand Operator Operand
100 + 50

In the example below, the numbers 100 and 50 are operands, and the
+ sign is an operator:

Example
var x = 100 + 50

Although the + operator is often used to add together two values, like
in the example above, it can also be used to add together a variable
and a value, or a variable and a variable:

Example
var sum1 = 100 + 50       // 150 (100 + 50)
var sum2 = sum1 + 250     // 400 (150 + 250)
var sum3 = sum2 + sum2    // 800 (400 + 400)

Kotlin divides the operators into the following groups:


 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators

Arithmetic Operators
Arithmetic operators are used to perform common mathematical
operations.
Operator Name Description Example
+ Addition Adds together two values x+y
- Subtraction Subtracts one value from another x - y
* Multiplication Multiplies two values x*y

19
/ Division Divides one value from another x/y
% Modulus Returns the division remainder x%y
++ Increment Increases the value by 1 ++x
-- Decrement Decreases the value by 1 --x

Kotlin Assignment Operators


Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator (=) to assign


the value 10 to a variable called x:

Example
var x = 10

The addition assignment operator (+=) adds a value to a variable:

Example
var x = 10
x += 5

A list of all assignment operators:


Operator Example
= x=5
+= x += 3 X=x+3
-= x -= 3 X=x-3
*= x *= 3 X=x*3
/= x /= 3 X=x/3
%= x %= 3 X=x%3

20
Kotlin Comparison Operators
Comparison operators are used to compare two values, and returns a
Boolean value: either true or false.

Operator Name Example


== Equal to x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

We will learn much more about Booleans in the Boolean chapter and
Conditions.

Kotlin Logical Operators


Logical operators are used to determine the logic between variables or
values:

Kotlin Strings
Strings are used for storing text.

A string contains a collection of characters surrounded by double


quotes:

Example
var greeting = "Hello"

21
Unlike Java, We do not have to specify that the variable should be a
String. Kotlin is smart enough to understand that the greeting variable
in the example above is a String because of the double quotes.

However, just like with other data types, We can specify the type if
We insist:

Example
var greeting: String = "Hello"

Note: If We want to create a String without assigning the value (and


assign the value later), We must specify the type while declaring the
variable:

Example

This works fine:


var name: String
name = "John"
println(name)
Example

This will generate an error:


var name
name = "John"
println(name)

Access a String
To access the characters (elements) of a string, We must refer to the
index number inside square brackets.

String indexes start with 0. In the example below, we access the first
and third element in txt:

22
Example
var txt = "Hello World"
println(txt[0]) // first element (H)
println(txt[2]) // third element (l)

[0] is the first element. [1] is the second element, [2] is the third
element, etc.

String Length
A String in Kotlin is an object, which contain properties and functions
that can perform certain operations on strings, by writing a dot
character (.) after the specific string variable. For example, the length
of a string can be found with the length property:

Example
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
println("The length of the txt string is: " + txt.length)

String Functions
There are many string functions available, for example toUpperCase()
and toLoourCase():

Example
var txt = "Hello World"
println(txt.toUpperCase())   // Outputs "HELLO WORLD"
println(txt.toLoourCase())   // Outputs "hello world"

Comparing Strings
The compareTo(string) function compares two strings and returns 0 if both
are equal:
23
Example
var txt1 = "Hello World"
var txt2 = "Hello World"
println(txt1.compareTo(txt2))  // Outputs 0 (they are equal)

Finding a String in a String


The indexOf() function returns the index (the position) of the first
occurrence of a specified text in a string (including whitespace):

Example
var txt = "Please locate where 'locate' occurs!"
println(txt.indexOf("locate"))  // Outputs 7

Remember that Kotlin counts positions from zero.


0 is the first position in a string, 1 is the second, 2 is the third ...

Quotes Inside a String


To use quotes inside a string, use single quotes ('):

Example
var txt1 = "It's alright"
var txt2 = "That's great"

String Concatenation
The + operator can be used between strings to add them together to
make a new string. This is called concatenation:

24
Example
var firstName = "John"
var lastName = "Doe"
println(firstName + " " + lastName)

Note that we have added an empty text (" ") to create a space between
firstName and lastName on print.

We can also use the plus() function to concatenate two strings:

Example
var firstName = "John "
var lastName = "Doe"
println(firstName.plus(lastName))

String Templates/Interpolation
Instead of concatenation, We can also use "string templates", which
is an easy way to add variables and expressions inside a string.

Just refer to the variable with the $ symbol:

Example
var firstName = "John"
var lastName = "Doe"
println("My name is $firstName $lastName")

"String Templates" is a popular feature of Kotlin, as it reduces the


amount of code. For example, We do not have to specify a
whitespace between firstName and lastName, like we did in the
concatenation example.

Kotlin Booleans
25
Very often, in programming, We will need a data type that can only
have one of two values, like:
 YES / NO
 ON / OFF
 TRUE / FALSE

For this, Kotlin has a Boolean data type, which can take the values true
or false.

Boolean Values
A boolean type can be declared with the Boolean keyword and can only
take the values true or false:

Example
val isKotlinFun: Boolean = true
val isFishTasty: Boolean = false
println(isKotlinFun)   // Outputs true
println(isFishTasty)   // Outputs false

Just like We have learned with other data types in the previous
chapters, the example above can also be written without specifying
the type, as Kotlin is smart enough to understand that the variables are
Booleans:

Example
val isKotlinFun = true
val isFishTasty = false
println(isKotlinFun)   // Outputs true
println(isFishTasty)   // Outputs false

Boolean Expression
A Boolean expression returns a Boolean value: true or false.
26
We can use a comparison operator, such as the greater than (>)
operator to find out if an expression (or a variable) is true:

Example
val x = 10
val y = 9
println(x > y) // Returns true, because 10 is greater than 9

Or even easier:

Example
println(10 > 9) // Returns true, because 10 is greater than 9

In the examples below, we use the equal to (==) operator to evaluate


an expression:

Example
val x = 10;
println(x == 10); // Returns true, because the value of x is equal to 10
Example
println(10 == 15); // Returns false, because 10 is not equal to 15

The Boolean value of an expression is the basis for all Kotlin


comparisons and conditions.

We will learn more about conditions in the next chapter.

Kotlin Conditions and If..Else


Kotlin supports the usual logical conditions from mathematics:

27
 Less than: a < b
 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b
 Equal to a == b
 Not Equal to: a != b

We can use these conditions to perform different actions for different


decisions.

Kotlin has the following conditionals:


 Use if to specify a block of code to be executed, if a specified condition is
true
 Use else to specify a block of code to be executed, if the same condition is
false
 Use else if to specify a new condition to test, if the first condition is false
 Use when to specify many alternative blocks of code to be executed

Note: Unlike Java, if..else can be used as a statement or as an


expression (to assign a value to a variable) in Kotlin. See an example
at the bottom of the page to better understand it.

Kotlin if
Use if to specify a block of code to be executed if a condition is true.

Syntax
if (condition) {
  // block of code to be executed if the condition is true
}

Note that if is in loourcase letters. Uppercase letters (If or IF) will


generate an error.

In the example below, we test two values to find out if 20 is greater


than 18. If the condition is true, print some text:
28
Example
if (20 > 18) {
  println("20 is greater than 18")
}

We can also test variables:

Example
val x = 20
val y = 18
if (x > y) {
  println("x is greater than y")
}
Example explained

In the example above we use two variables, x and y, to test whether x


is greater than y (using the > operator). As x is 20, and y is 18, and we
know that 20 is greater than 18, we print to the screen that "x is
greater than y".

Kotlin else
Use else to specify a block of code to be executed if the condition is
false.

Syntax
if (condition) {
  // block of code to be executed if the condition is true
} else {
  // block of code to be executed if the condition is false
}
Example
val time = 20
if (time < 18) {
  println("Good day.")

29
} else {
  println("Good evening.")
}
// Outputs "Good evening."
Example explained

In the example above, time (20) is greater than 18, so the condition is
false, so we move on to the else condition and print to the screen "Good
evening". If the time was less than 18, the program would print "Good
day".

Kotlin else if
Use else if to specify a new condition if the first condition is false.

Syntax
if (condition1) {
  // block of code to be executed if condition1 is true
} else if (condition2) {
  // block of code to be executed if the condition1 is false and condition2 is true
} else {
  // block of code to be executed if the condition1 is false and condition2 is false
}
Example
val time = 22
if (time < 10) {
  println("Good morning.")
} else if (time < 20) {
  println("Good day.")
} else {
  println("Good evening.")
}
// Outputs "Good evening."

30
Example explained

In the example above, time (22) is greater than 10, so the first
condition is false. The next condition, in the else if statement, is also
false, so we move on to the else condition since condition1 and
condition2 is both false - and print to the screen "Good evening".

However, if the time was 14, our program would print "Good day."

Kotlin If..Else Expressions


In Kotlin, We can also use if..else statements as expressions (assign a
value to a variable and return it):

Example
val time = 20
val greeting = if (time < 18) {
  "Good day."
} else {
  "Good evening."
}
println(greeting)

When using if as an expression, We must also include else (required).

Note: We can ommit the curly braces {} when if has only one
statement:

Example
fun main() {
  val time = 20
  val greeting = if (time < 18) "Good day." else "Good evening."
  println(greeting)
}
Tip: This example is similar to the "ternary operator" (short hand if...else) in
Java.

31
Kotlin when
Instead of writing many if..else expressions, We can use the when
expression, which is much easier to read.

It is used to select one of many code blocks to be executed:

Example

Use the weekday number to calculate the weekday name:


val day = 4

val result = when (day) {


  1 -> "Monday"
  2 -> "Tuesday"
  3 -> "Wednesday"
  4 -> "Thursday"
  5 -> "Friday"
  6 -> "Saturday"
  7 -> "Sunday"
  else -> "Invalid day."
}
println(result)

// Outputs "Thursday" (day 4)

The when expression is similar to the switch statement in Java.

This is how it works:


 The when variable (day) is evaluated once
 The value of the day variable is compared with the values of each
"branch"
 Each branch starts with a value, followed by an arrow (->) and a result
32
 If there is a match, the associated block of code is executed
 else is used to specify some code to run if there is no match
 In the example above, the value of day is 4, meaning "Thursday" will be
printed

Loops
Loops can execute a block of code as long as a specified condition is
reached.

Loops are handy because they save time, reduce errors, and they make
code more readable.

Kotlin While Loop


The while loop loops through a block of code as long as a specified
condition is true:

Syntax
while (condition) {
  // code block to be executed
}

In the example below, the code in the loop will run, over and over
again, as long as the counter variable (i) is less than 5:

33
Example
var i = 0
while (i < 5) {
  println(i)
  i++
}

Note: Do not forget to increase the variable used in the condition,


otherwise the loop will never end.

The Do..While Loop


The do..while loop is a variant of the while loop. This loop will execute
the code block once, before checking if the condition is true, then it
will repeat the loop as long as the condition is true.

Syntax
do {
  // code block to be executed
}
while (condition);

The example below uses a do/while loop. The loop will always be
executed at least once, even if the condition is false, because the code
block is executed before the condition is tested:

Example
var i = 0
do {
  println(i)
  i++
}
while (i < 5)

Do not forget to increase the variable used in the condition, otherwise


the loop will never end!
34
Kotlin Break
The break statement is used to jump out of a loop.

This example jumps out of the loop when i is equal to 4:

Example
var i = 0
while (i < 10) {
  println(i)
  i++
  if (i == 4) {
    break
 }
}

Kotlin Continue
The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.

This example skips the value of 4:


35
Example
var i = 0
while (i < 10) {
  if (i == 4) {
    i++
    continue
 }
  println(i);   i++
}

Kotlin Arrays
Arrays are used to store multiple values in a single variable, instead of
creating separate variables for each value.

To create an array, use the arrayOf() function, and place the values in a
comma-separated list inside it:
val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")

Access the Elements of an Array


We can access an array element by referring to the index number,
inside square brackets.

In this example, we access the value of the first element in cars:

Example
val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
println(cars[0])
// Outputs Volvo

Note: Just like with Strings, Array indexes start with 0: [0] is the first
element. [1] is the second element, etc.

36
Change an Array Element
To change the value of a specific element, refer to the index number:

Example
cars[0] = "Opel"
Example
val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
cars[0] = "Opel"
println(cars[0])
// Now outputs Opel instead of Volvo

Array Length / Size


To find out how many elements an array have, use the size property:

Example
val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
println(cars.size)
// Outputs 4

Check if an Element Exists


We can use the in operator to check if an element exists in an array:

Example
val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
if ("Volvo" in cars) {
  println("It exists!")
} else {
  println("It does not exist.")
}

37
Loop Through an Array
Often when We work with arrays, We need to loop through all of the
elements.

We can loop through the array elements with the for loop, which We
will learn even more about in the next chapter.

The following example outputs all elements in the cars array:

Example
val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
for (x in cars) {
  println(x)
}

Kotlin For Loop


Often when We work with arrays, We need to loop through all of the
elements.

To loop through array elements, use the for loop together with the in
operator:

38
Example

Output all elements in the cars array:


val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
for (x in cars) {
  println(x)
}

We can loop through all kinds of arrays. In the example above, we


used an array of strings.

In the example above, we loop through an array of integers:

Example
val nums = arrayOf(1, 5, 10, 15, 20)
for (x in nums) {
  println(x)
}

Traditional For Loop


Unlike Java and other programming languages, there is no traditional
for loop in Kotlin.

In Kotlin, the for loop is used to loop through arrays, ranges, and other
things that contains a countable number of values.

We will learn more about ranges in the next chapter - which will
create a range of values.

Kotlin Ranges
With the for loop, We can also create ranges of values with "..":

39
Example

Print the whole alphabet:


for (chars in 'a'..'x') {
  println(chars)
}

We can also create ranges of numbers:

Example
for (nums in 5..15) {
  println(nums)
}

Note: The first and last value is included in the range.

Check if a Value Exists


We can also use the in operator to check if a value exists in a range:

Example
val nums = arrayOf(2, 4, 6, 8)
if (2 in nums) {
  println("It exists!")
} else {
  println("It does not exist.")
}
Example
val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
if ("Volvo" in cars) {
  println("It exists!")
} else {
  println("It does not exist.")
}

40
Break or Continue a Range
We can also use the break and continue keywords in a range/for loop:

Example

Stop the loop when nums is equal to 10:


for (nums in 5..15) {
  if (nums == 10) {
    break
 }
  println(nums)
}
Example

Skip the value of 10 in the loop, and continue with the next iteration:
for (nums in 5..15) {
  if (nums == 10) {
    continue
 }
  println(nums)
}

Kotlin Functions

A function is a block of code which only runs when it is called.

We can pass data, known as parameters, into a function.

Functions are used to perform certain actions, and they are also
known as methods.

41
Predefined Functions
So it turns out We already know what a function is. We have been
using it the whole time through this tutorial!

For example, println() is a function. It is used to output/print text to the


screen:

Example
fun main() {
  println("Hello World")
}

Create our Own Functions


To create our own function, use the fun keyword, and write the name
of the function, followed by parantheses ():

Example

Create a function named "myFunction" that should output some text:


fun myFunction() {
  println("I just got executed!")
}

Call a Function
Now that We have created a function, We can execute it by calling
it.

To call a function in Kotlin, write the name of the function followed


by two parantheses ().

42
In the following example, myFunction() will print some text (the action),
when it is called:

Example
fun main() {
  myFunction() // Call myFunction
}

// Outputs "I just got executed!"

A function can be called multiple times, if We want:

Example
fun main() {
  myFunction()
  myFunction()
  myFunction()
}

// I just got executed!


// I just got executed!
// I just got executed!

Function Parameters
Information can be passed to functions as parameter.

Parameters are specified after the function name, inside the


parentheses. We can add as many parameters as We want, just
separate them with a comma. Just note that We must specify the type
of each parameter (Int, String, etc).

The following example has a function that takes a String called fname
as parameter. When the function is called, we pass along a first name,
which is used inside the function to print the full name:

43
Example
fun myFunction(fname: String) {
  println(fname + " Doe")
}

fun main() {
  myFunction("John")
  myFunction("Jane")
  myFunction("George")
}

// John Doe
// Jane Doe
// George Doe

When a parameter is passed to the function, it is called an


argument. So, from the example above: fname is a parameter, while
John, Jane and George are arguments.

Multiple Parameters
We can have as many parameters as We like:

Example
fun myFunction(fname: String, age: Int) {
  println(fname + " is " + age)
}

fun main() {
  myFunction("John", 35)
  myFunction("Jane", 32)
  myFunction("George", 15)
}

// John is 35
44
// Jane is 32
// George is 15

Note: When working with multiple parameters, the function call must
have the same number of arguments as there are parameters, and the
arguments must be passed in the same order.

Return Values
In the examples above, we used functions to output a value. In the
following example, we will use a function to return a value and
assign it to a variable.

To return a value, use the return keyword, and specify the return type
after the function's parantheses (Int in this example):

Example

A function with one Int parameter, and Int return type:


fun myFunction(x: Int): Int {
  return (x + 5)
}

fun main() {
  var result = myFunction(3)
  println(result)
}

// 8 (3 + 5)

Using two parameters:

Example

A function with two Int parameters, and Int return type:

45
fun myFunction(x: Int, y: Int): Int {
  return (x + y)
}

fun main() {
  var result = myFunction(3, 5)
  println(result)
}

// 8 (3 + 5)

Shorter Syntax for Return Values


There is also a shorter syntax for returning values. We can use the =
operator instead of return without specifying the return type. Kotlin is
smart enough to automatically find out what it is:

Example
fun myFunction(x: Int, y: Int) = x + y

fun main() {
  var result = myFunction(3, 5)
  println(result)
}

// 8 (3 + 5)

Kotlin - What is OOP?


OOP stands for Object-Oriented Programming.

46
Procedural programming is about writing procedures or methods that
perform operations on the data, while object-oriented programming is
about creating objects that contain both data and methods.

Object-oriented programming has several advantages over procedural


programming:
 OOP is faster and easier to execute
 OOP provides a clear structure for the programs
 OOP helps to keep the Kotlin code DRY "Don't Repeat Ourself", and
makes the code easier to maintain, modify and debug
 OOP makes it possible to create full reusable applications with less code
and shorter development time

Tip: The "Don't Repeat Ourself" (DRY) principle is about reducing


the repetition of code. We should extract out the codes that are
common for the application, and place them at a single place and
reuse them instead of repeating it.

Kotlin - What are Classes and Objects?


Classes and objects are the two main aspects of object-oriented
programming.

Look at the following illustration to see the difference between class


and objects:

class
Fruit

objects
Apple

Banana

Mango

47
Another example:

class
Car

objects
Volvo

Audi

Toyota

So, a class is a template for objects, and an object is an instance of a


class.

When the individual objects are created, they inherit all the variables
and methods from the class.

We will learn much more about classes and objects in the next
chapter.

Kotlin Classes/Objects
Everything in Kotlin is associated with classes and objects, along with
its properties and functions. For example: in real life, a car is an
object. The car has properties, such as brand, weight and color, and
functions, such as drive and brake.

A Class is like an object constructor, or a "blueprint" for creating


objects.

48
Create a Class
To create a class, use the class keyword, and specify the name of the
class:

Example

Create a Car class along with some properties (brand, model and
year)
class Car {
  var brand = ""
  var model = ""
  var year = 0
}

A property is basically a variable that belongs to the class.

Good to Know: It is considered good practice to start the name of a


class with an upper case letter, for better organization.

Create an Object
Now we can use the class named Car to create objects.

In the example below, we create an object of Car called c1, and then
we access the properties of c1 by using the dot syntax (.), just like we
did to access array and string properties:

Example
// Create a c1 object of the Car class
val c1 = Car()

// Access the properties and add some values to it


c1.brand = "Ford"
49
c1.model = "Mustang"
c1.year = 1969

println(c1.brand)   // Outputs Ford


println(c1.model)   // Outputs Mustang
println(c1.year)    // Outputs 1969

Multiple Objects
We can create multiple objects of one class:

Example
val c1 = Car()
c1.brand = "Ford"
c1.model = "Mustang"
c1.year = 1969

val c2 = Car()
c2.brand = "BMW"
c2.model = "X5"
c2.year = 1999

println(c1.brand)  // Ford
println(c2.brand)  // BMW

Kotlin Constructor
In the previous chapter, we created an object of a class, and specified
the properties inside the class, like this:

50
Example
class Car {
  var brand = ""
  var model = ""
  var year = 0
}

fun main() {
  val c1 = Car()
  c1.brand = "Ford"
  c1.model = "Mustang"
  c1.year = 1969
}

In Kotlin, there's a faster way of doing this, by using a constructor.

A constructor is like a special function, and it is defined by using two


parantheses () after the class name. We can specify the properties
inside of the parantheses (like passing parameters into a regular
function).

The constructor will initialize the properties when We create an


object of a class. Just remember to specify the type of the
property/variable:

Example
class Car(var brand: String, var model: String, var year: Int)

fun main() {
  val c1 = Car("Ford", "Mustang", 1969)
}

Now it's even easier to specify multiple objects of one class:

Example
class Car(var brand: String, var model: String, var year: Int)

fun main() {

51
  val c1 = Car("Ford", "Mustang", 1969)
  val c2 = Car("BMW", "X5", 1999)
  val c3 = Car("Tesla", "Model S", 2020)
}

Introduction to SQL

SQL is a standard language for accessing and manipulating databases.

What is SQL?
 SQL stands for Structured Query Language
 SQL lets We access and manipulate databases
 SQL became a standard of the American National Standards Institute
(ANSI) in 1986, and of the International Organization for Standardization
(ISO) in 1987

What Can SQL do?


 SQL can execute queries against a database
 SQL can retrieve data from a database
 SQL can insert records in a database
 SQL can update records in a database
 SQL can delete records from a database
 SQL can create new databases
 SQL can create new tables in a database
 SQL can create stored procedures in a database
 SQL can create views in a database
 SQL can set permissions on tables, procedures, and views

52
SQL is a Standard - BUT....
Although SQL is an ANSI/ISO standard, there are different versions
of the SQL language.

However, to be compliant with the ANSI standard, they all support at


least the major commands (such as SELECT, UPDATE, DELETE, INSERT,
WHERE) in a similar manner.

Note: Most of the SQL database programs also have their own
proprietary extensions in addition to the SQL standard!

Using SQL in Our Web Site


To build a web site that shows data from a database, We will need:
 An RDBMS database program (i.e. MS Access, SQL Server, MySQL)
 To use a server-side scripting language, like PHP or ASP
 To use SQL to get the data We want
 To use HTML / CSS to style the page

RDBMS
RDBMS stands for Relational Database Management System.

RDBMS is the basis for SQL, and for all modern database systems
such as MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft
Access.

The data in RDBMS is stored in database objects called tables. A


table is a collection of related data entries and it consists of columns
and rows.

Look at the "Customers" table:

53
Example
SELECT * FROM Customers;

Every table is broken up into smaller entities called fields. The fields
in the Customers table consist of CustomerID, CustomerName,
ContactName, Address, City, PostalCode and Country. A field is a
column in a table that is designed to maintain specific information
about every record in the table.

A record, also called a row, is each individual entry that exists in a


table. For example, there are 91 records in the above Customers table.
A record is a horizontal entity in a table.

A column is a vertical entity in a table that contains all information


associated with a specific field in a table.

The SQL SELECT Statement


The SELECT statement is used to select data from a database.

The data returned is stored in a result table, called the result-set.

SELECT Syntax
SELECT column1, column2, ...
FROM table_name;

Here, column1, column2, ... are the field names of the table We want
to select data from. If We want to select all the fields available in the
table, use the following syntax:
SELECT * FROM table_name;
54
SELECT Column Example
The following SQL statement selects the "CustomerName" and "City"
columns from the "Customers" table:

Example
SELECT CustomerName, City FROM Customers;

SELECT * Example
The following SQL statement selects all the columns from the
"Customers" table:

Example
SELECT * FROM Customers;

The SQL SELECT DISTINCT Statement


The SELECT DISTINCT statement is used to return only distinct
(different) values.

Inside a table, a column often contains many duplicate values; and


sometimes We only want to list the different (distinct) values.

SELECT DISTINCT Syntax


SELECT DISTINCT column1, column2, ...
FROM table_name;

55
SELECT Example Without DISTINCT
The following SQL statement selects all (including the duplicates)
values from the "Country" column in the "Customers" table:

Example
SELECT Country FROM Customers;

Now, let us use the SELECT DISTINCT statement and see the result.

SELECT DISTINCT Examples


The following SQL statement selects only the DISTINCT values from
the "Country" column in the "Customers" table:

Example
SELECT DISTINCT Country FROM Customers;

The following SQL statement lists the number of


different (distinct) customer countries:
Example
SELECT COUNT(DISTINCT Country) FROM Customers;

Note: The example above will not work in Firefox!


Because COUNT(DISTINCT column_name) is not
supported in Microsoft Access databases. Firefox is
using Microsoft Access in our examples.

56
Here is the workaround for MS Access:
Example
SELECT Count(*) AS DistinctCountries
FROM (SELECT DISTINCT Country FROM Customers);

The SQL WHERE Clause


The WHERE clause is used to filter records.

It is used to extract only those records that fulfill a specified


condition.

WHERE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition;

WHERE Clause Example


The following SQL statement selects all the customers from the
country "Mexico", in the "Customers" table:

Example
SELECT * FROM Customers
WHERE Country='Mexico';

Text Fields vs. Numeric Fields

57
SQL requires single quotes around text values (most database systems
will also allow double quotes).

However, numeric fields should not be enclosed in quotes:

Example
SELECT * FROM Customers
WHERE CustomerID=1;

Operators in The WHERE Clause


The following operators can be used in the WHERE clause:

Operator Description
= Equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
Not equal. Note: In some versions of SQL this operator
<>
may be written as !=
BETWEEN Between a certain range
LIKE Search for a pattern

Layouts   
A layout defines the structure for a user interface in your app,
such as in an activity. All elements in the layout are built using
a hierarchy of View and ViewGroup objects. A View usually draws
something the user can see and interact with. Whereas
a ViewGroup is an invisible container that defines the layout

58
structure for View and other ViewGroup objects, as shown in figure
1.

Figure 1. Illustration of a view hierarchy, which defines a UI layout

The View objects are usually called "widgets" and can be one of


many subclasses, such as Button or TextView.
The ViewGroup objects are usually called "layouts" can be one of
many types that provide a different layout structure, such
as LinearLayout or ConstraintLayout .
You can declare a layout in two ways:
 Declare UI elements in XML. Android provides a straightforward
XML vocabulary that corresponds to the View classes and subclasses,
such as those for widgets and layouts.
You can also use Android Studio's Layout Editor to build your
XML layout using a drag-and-drop interface.
 Instantiate layout elements at runtime. Your app can create
View and ViewGroup objects (and manipulate their properties)
programmatically.

Declaring your UI in XML allows you to separate the


presentation of your app from the code that controls its
behavior. Using XML files also makes it easy to provide
different layouts for different screen sizes and orientations
(discussed further in Supporting Different Screen Sizes).
59
The Android framework gives you the flexibility to use either or
both of these methods to build your app's UI. For example, you
can declare your app's default layouts in XML, and then modify
the layout at runtime.
Tip: To debug your layout at runtime, use the Layout Inspector tool.

Write the XML


Using Android's XML vocabulary, you can quickly design UI
layouts and the screen elements they contain, in the same way
you create web pages in HTML — with a series of nested
elements.
Each layout file must contain exactly one root element, which
must be a View or ViewGroup object. Once you've defined the
root element, you can add additional layout objects or widgets
as child elements to gradually build a View hierarchy that
defines your layout. For example, here's an XML layout that
uses a vertical LinearLayout to hold a TextView and a Button:
<?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" >
    <TextView android:id="@+id/text"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="Hello, I am a TextView" />
    <Button android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello, I am a Button" />
</LinearLayout>

After you've declared your layout in XML, save the file with
the .xml extension, in your Android project's res/layout/ directory,
so it will properly compile.

60
More information about the syntax for a layout XML file is
available in the Layout Resources document.

Load the XML Resource


When you compile your app, each XML layout file is compiled
into a View resource. You should load the layout resource from
your app code, in your Activity.onCreate() callback implementation.
Do so by calling setContentView(), passing it the reference to your
layout resource in the form of: R.layout.layout_file_name. For
example, if your XML layout is saved as main_layout.xml, you
would load it for your Activity like so:
KotlinJava
fun onCreate(savedInstanceState: Bundle) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.main_layout)
}

The onCreate() callback method in your Activity is called by the


Android framework when your Activity is launched (see the
discussion about lifecycles, in the Activities document).

Attributes
Every View and ViewGroup object supports their own variety of
XML attributes. Some attributes are specific to a View object
(for example, TextView supports the textSize attribute), but these
attributes are also inherited by any View objects that may
extend this class. Some are common to all View objects,
because they are inherited from the root View class (like
the id attribute). And, other attributes are considered "layout
parameters," which are attributes that describe certain layout
orientations of the View object, as defined by that object's
parent ViewGroup object.

61
ID

Any View object may have an integer ID associated with it, to


uniquely identify the View within the tree. When the app is
compiled, this ID is referenced as an integer, but the ID is
typically assigned in the layout XML file as a string, in
the id attribute. This is an XML attribute common to all View
objects (defined by the View class) and you will use it very often.
The syntax for an ID, inside an XML tag is:
android:id="@+id/my_button"

The at-symbol (@) at the beginning of the string indicates that


the XML parser should parse and expand the rest of the ID
string and identify it as an ID resource. The plus-symbol (+)
means that this is a new resource name that must be created
and added to our resources (in the R.java file). There are a
number of other ID resources that are offered by the Android
framework. When referencing an Android resource ID, you do
not need the plus-symbol, but must add the android package
namespace, like so:
android:id="@android:id/empty"

With the android package namespace in place, we're now


referencing an ID from the android.R resources class, rather than
the local resources class.
In order to create views and reference them from the app, a
common pattern is to:
1. Define a view/widget in the layout file and assign it a unique ID:
<Button android:id="@+id/my_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/my_button_text"/>

62
2. Then create an instance of the view object and capture it from the
layout (typically in the onCreate() method):
KotlinJava
val myButton: Button = findViewById(R.id.my_button)

Defining IDs for view objects is important when creating


a RelativeLayout. In a relative layout, sibling views can define their
layout relative to another sibling view, which is referenced by
the unique ID.
An ID need not be unique throughout the entire tree, but it
should be unique within the part of the tree you are searching
(which may often be the entire tree, so it's best to be completely
unique when possible).
Note: With Android Studio 3.6 and higher, the view binding feature can
replace findViewById() calls and provides compile-time type safety for code that
interacts with views. Consider using view binding instead of findViewById().
Layout Parameters
XML layout attributes named layout_something define layout
parameters for the View that are appropriate for the ViewGroup
in which it resides.
Every ViewGroup class implements a nested class that
extends ViewGroup.LayoutParams. This subclass contains property
types that define the size and position for each child view, as
appropriate for the view group. As you can see in figure 2, the
parent view group defines layout parameters for each child
view (including the child view group).

63
Figure 2. Visualization of a view hierarchy with layout parameters associated with
each view

Note that every LayoutParams subclass has its own syntax for
setting values. Each child element must define LayoutParams
that are appropriate for its parent, though it may also define
different LayoutParams for its own children.
All view groups include a width and height
(layout_width and layout_height), and each view is required to define
them. Many LayoutParams also include optional margins and
borders.
You can specify width and height with exact measurements,
though you probably won't want to do this often. More often,
you will use one of these constants to set the width or height:
 wrap_content tells your view to size itself to the dimensions
required by its content.
 match_parent tells your view to become as big as its parent view
group will allow.

In general, specifying a layout width and height using absolute


units such as pixels is not recommended. Instead, using
relative measurements such as density-independent pixel units
(dp), wrap_content, or match_parent, is a better approach,

64
because it helps ensure that your app will display properly
across a variety of device screen sizes. The accepted
measurement types are defined in the Available
Resources document.

Layout Position
The geometry of a view is that of a rectangle. A view has a
location, expressed as a pair of left and top coordinates, and
two dimensions, expressed as a width and a height. The unit
for location and dimensions is the pixel.
It is possible to retrieve the location of a view by invoking the
methods getLeft() and getTop(). The former returns the left, or X,
coordinate of the rectangle representing the view. The latter
returns the top, or Y, coordinate of the rectangle representing
the view. These methods both return the location of the view
relative to its parent. For instance, when getLeft() returns 20, that
means the view is located 20 pixels to the right of the left edge
of its direct parent.
In addition, several convenience methods are offered to avoid
unnecessary computations, namely getRight() and getBottom().
These methods return the coordinates of the right and bottom
edges of the rectangle representing the view. For instance,
calling getRight() is similar to the following computation: getLeft() +
getWidth().

Size, Padding and Margins


The size of a view is expressed with a width and a height. A
view actually possesses two pairs of width and height values.
The first pair is known as measured width and measured
height. These dimensions define how big a view wants to be
within its parent. The measured dimensions can be obtained by
calling getMeasuredWidth() and getMeasuredHeight().
65
The second pair is simply known as width and height, or
sometimes drawing width and drawing height. These
dimensions define the actual size of the view on screen, at
drawing time and after layout. These values may, but do not
have to, be different from the measured width and height. The
width and height can be obtained by
calling getWidth() and getHeight().
To measure its dimensions, a view takes into account its
padding. The padding is expressed in pixels for the left, top,
right and bottom parts of the view. Padding can be used to
offset the content of the view by a specific number of pixels. For
instance, a left padding of 2 will push the view's content by 2
pixels to the right of the left edge. Padding can be set using
the setPadding(int, int, int, int) method and queried by
calling getPaddingLeft(), getPaddingTop(), getPaddingRight() and getPaddingBo
ttom().

Even though a view can define a padding, it does not provide


any support for margins. However, view groups provide such a
support. Refer to ViewGroup and ViewGroup.MarginLayoutParams for
further information.
For more information about dimensions, see Dimension Values.

Common Layouts
Each subclass of the ViewGroup class provides a unique way to
display the views you nest within it. Below are some of the
more common layout types that are built into the Android
platform.
Note: Although you can nest one or more layouts within another layout to achieve
your UI design, you should strive to keep your layout hierarchy as shallow as
possible. Your layout draws faster if it has fewer nested layouts (a wide view
hierarchy is better than a deep view hierarchy).

66
Linear Layout

A layout that organizes its children into a single horizontal or


vertical row. It creates a scrollbar if the length of the window
exceeds the length of the screen.

Relative Layout

Enables you to specify the location of child objects relative to


each other (child A to the left of child B) or to the parent
(aligned to the top of the parent).

Web View

Displays web pages.

67
Building Layouts with an Adapter
When the content for your layout is dynamic or not pre-
determined, you can use a layout that subclasses AdapterView to
populate the layout with views at runtime. A subclass of
the AdapterView class uses an Adapter to bind data to its layout.
The Adapter behaves as a middleman between the data source
and the AdapterView layout—the Adapter retrieves the data (from a
source such as an array or a database query) and converts
each entry into a view that can be added into
the AdapterView layout.
Common layouts backed by an adapter include:

List View

Displays a scrolling single column list.

Grid View

Displays a scrolling grid of columns and rows.

68
Filling an adapter view with data

You can populate an AdapterView such as ListView or GridView by


binding the AdapterView instance to an Adapter, which retrieves
data from an external source and creates a View that represents
each data entry.
Android provides several subclasses of Adapter that are useful
for retrieving different kinds of data and building views for
an AdapterView. The two most common adapters are:
ArrayAdapter

Use this adapter when your data source is an array. By


default, ArrayAdapter creates a view for each array item by
calling toString() on each item and placing the contents in
a TextView.

For example, if you have an array of strings you want to


display in a ListView, initialize a new ArrayAdapter using a
constructor to specify the layout for each string and the
string array:
KotlinJava
val adapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
myStringArray)

The arguments for this constructor are:


 Your app Context
 The layout that contains a TextView for each string in the array
 The string array

Then simply call setAdapter() on your ListView:


KotlinJava

69
val listView: ListView = findViewById(R.id.listview)
listView.adapter = adapter

To customize the appearance of each item you can


override the toString() method for the objects in your array.
Or, to create a view for each item that's something other
than a TextView (for example, if you want an ImageView for
each array item), extend the ArrayAdapter class and
override getView() to return the type of view you want for
each item.
SimpleCursorAdapter

Use this adapter when your data comes from a Cursor. When
using SimpleCursorAdapter, you must specify a layout to use for each
row in the Cursor and which columns in the Cursor should be
inserted into which views of the layout. For example, if you want to
create a list of people's names and phone numbers, you can
perform a query that returns a Cursor containing a row for each
person and columns for the names and numbers. You then create
a string array specifying which columns from the Cursor you want in
the layout for each result and an integer array specifying the
corresponding views that each column should be placed:

KotlinJava
val fromColumns = arrayOf(ContactsContract.Data.DISPLAY_NAME,
                          ContactsContract.CommonDataKinds.Phone.NUMBER)
val toViews = intArrayOf(R.id.display_name, R.id.phone_number)

When you instantiate the SimpleCursorAdapter, pass the layout


to use for each result, the Cursor containing the results, and
these two arrays:
KotlinJava
val adapter = SimpleCursorAdapter(this,
        R.layout.person_name_and_number, cursor, fromColumns, toViews, 0)
val listView = getListView()

70
listView.adapter = adapter

The SimpleCursorAdapter then creates a view for each row in


the Cursor using the provided layout by inserting
each fromColumns item into the corresponding toViews view.
.

If, during the course of your app's life, you change the
underlying data that is read by your adapter, you should
call notifyDataSetChanged(). This will notify the attached view that the
data has been changed and it should refresh itself.
Handling click events

You can respond to click events on each item in


an AdapterView by implementing
the AdapterView.OnItemClickListener interface. For example:
KotlinJava
listView.onItemClickListener = AdapterView.OnItemClickListener { parent, view,
position, id ->
    // Do something in response to the click
}

Thank You
71

You might also like