Professional Documents
Culture Documents
INTRODUCTION
Android is an open source operating system based on Linux with a Java programming
interface for mobile devices such as Smartphone (Touch Screen Devices who supports
Android OS) as well for Tablets too.
Android is a powerful open source operating system which provides a lot of great features,
those are
It’s an open source and we can customize the OS based on our requirements.
It support connectivity for GSM, CDMA, WIFI, NFC, Bluetooth, etc. for telephony or
data transfer. It will allow us to make or receive a calls / SMS messages and we can
send or retrieve a data across mobile networks.
Android have a multiple APIs to support a location-based services such as GPS
We can perform all data storage related activities by using light weight
database SQLite.
It have a wide range of media supports like AVI, MKV, FLV, MPEG4 etc. to play or
record variety of audio / video and having a different image formats like JPEG, PNG,
GIF, BMP, MP3, etc.
1.3 ANDROID VERSIONS
An android app is a software application running on the android platform.They are generally
developed in the java language using the Android SDK Android applications can be
packaged easily and sold out either through a store such as Google play,etc. There are many
android applications that we already know and uses them few are music ,news ,weathe
r,etc. Many android application are also available for free most of them are already
available in play store.This apps are compatible with almost every platform but few are also
available for the specific platform. Few apps are :
a) Weather
b) Google Drive
c) Waze and Google Maps
d) Google Search / Assistant / Feed
e) You Tube
1.5ANDROID APP DEVELOPMENT
Android App Development is a cycle through which new applications are created for Android
OS. Programming Languages used in Developing Android Applications
1. Java
2. Kotlin
Developing the Android Application using Kotlin is preferred by Google, as Kotlin is made
an official language for Android Development, which is developed and maintained by
JetBrains. Previously before Java is considered the official language for Android
Development. Kotlin is made official for Android Development in Google I/O 2017.
Application components are the essential building blocks of an Android application. These
components are loosely coupled by the application manifest file AndroidManifest.xml that
describes each component of the application and how they interact.
There are following four main components that can be used within an Android application −
1. Activities
An activity represents a single screen with a user interface,in-short Activity performs actions
on the screen. For example, an email application might have one activity that shows a list of
new emails, another activity to compose an email, and another activity for reading emails. If
an application has more than one activity, then one of them should be marked as the activity
that is presented when the application is launched.
A service is a component that runs in the background to perform long-running operations. For
example, a service might play music in the background while the user is in a different
application, or it might fetch data over the network without blocking user interaction with an
activity.
Broadcast Receivers simply respond to broadcast messages from other applications or from
the system. For example, applications can also initiate broadcasts to let other applications
know that some data has been downloaded to the device and is available for them to use, so
this is broadcast receiver who will intercept this communication and will initiate appropriate
action.
A content provider component supplies data from one application to others on request. Such
requests are handled by the methods of the ContentResolver class. The data may be stored in
the file system, the database or somewhere else entirely.
A content provider is implemented as a subclass of ContentProvider class and must
implement a standard set of APIs that enable other applications to perform transactions.
There are additional components which will be used in the construction of above mentioned
entities, their logic, and wiring between them. These components are –
Fragments
1
Represents a portion of user interface in an Activity.
Views
2
UI elements that are drawn on-screen including buttons, lists forms etc.
Layouts
3
View hierarchies that control screen format and appearance of the views.
Intents
4
Messages wiring components together.
Resources
5
External elements, such as strings, constants and drawable pictures.
6 Manifest
Configuration file for the application.
1. ANDROID STUDIO
Android Studio is the official Integrated Development Environment (IDE) for Android app
development, based on IntelliJ IDEA . On top of IntelliJ's powerful code editor and developer
tools, Android Studio offers even more features that enhance your productivity when building
Android apps, such as:
A unified environment where you can develop for all Android devices
Apply Changes to push code and resource changes to your running app without restarting
your app
Code templates and GitHub integration to help you build common app features and import
sample code
Lint tools to catch performance, usability, version compatibility, and other problems
Built-in support for Google Cloud Platform, making it easy to integrate Google Cloud
Messaging and App Engine
Each project in Android Studio contains one or more modules with source code files and
resource files. Types of modules include:
All the build files are visible at the top level under Gradle Scripts and each app module
contains the following folders:
java: Contains the Java source code files, including JUnit test code.
res: Contains all non-code resources, such as XML layouts, UI strings, and bitmap images.
2. SDK
A software development toolkit (SDK) is a set of software tools and programs provided by
hardware and software vendors that developers can use to build applications for specific
platforms. These providers make their SDKs available to help developers easily integrate
their apps with their services.
In order to use a SDK, a developer needs an iOS SDK to build iOS apps, an Android toolkit
for building Android apps, Nordic SDK to build Bluetooth or wireless apps and
a VMware SDK to enable integration with the VMware platform.
Although SDKs are largely associated with native mobile apps, developers can use them in
connection with websites, set-top boxes and other digital platforms.
Tools to help developers do such tasks as debugging, building, running and testing
their applications.
For example, if a developer wanted to share images or text from his or her app directly into
Facebook, he or she could look for Facebook’s Android SDK to find the necessary code that
would work for an Android device. This speeds deployment because the developer doesn’t
have to write the code from scratch.
CHAPTER 2
KOTLIN WORLD
Kotlin is a general purpose, free, open source, statically typed “pragmatic” programming
language initially designed for the JVM (Java Virtual Machine) and Android that combines
object-oriented and functional programming features. It is focused on interoperability, safety,
clarity, and tooling support. Versions of Kotlin targeting JavaScript ES5.1 and native code
(using LLVM) for a number of processors are in production as well.
Kotlin originated at JetBrains, the company behind IntelliJ IDEA, in 2010, and has been open
source since 2012. The Kotlin team currently has more than 90 full-time members from
JetBrains, and the Kotlin project on GitHub has more than 300 contributors. JetBrains uses
Kotlin in many of its products including its flagship IntelliJ IDEA.
In July 2011, JetBrains unveiled Project Kotlin, a new language for the JVM, which
had been under development for a year. JetBrains lead Dmitry Jemerov said that most
languages did not have the features they were looking for, with the exception of Scala.
However, he cited the slow compilation time of Scala as a deficiency. One of the
stated goals of Kotlin is to compile as quickly as Java. In February 2012, JetBrains
open sourced the project under the Apache 2 license.
The name comes from Kotlin Island, near St. Petersburg. Andrey Breslav mentioned
that the team decided to name it after an island, just like Java was named after the
Indonesian island of Java (though the programming language Java was perhaps
named after the coffee rather than the island).
JetBrains hopes that the new language will drive IntelliJ IDEA sales. Kotlin 1.0 was
released on February 15, 2016. This is considered to be the first officially stable
release and JetBrains has committed to long-term backwards compatibility starting
with this version.
At Google I/O 2017, Google announced first-class support for Kotlin on Android.
Kotlin 1.2 was released on November 28, 2017. Sharing code between JVM and
JavaScript platforms feature was newly added to this release (as of version 1.4
multiplatform programming is an alpha feature upgraded from "experimental").
A full-stack demo has been made with the new Kotlin/JS Gradle Plugin.
Kotlin 1.3 was released on 29 October 2018, bringing coroutines for asynchronous
programming.
On 7 May 2019, Google announced that the Kotlin programming language is now its
preferred language for Android app developers.
Kotlin 1.4 was released in August 2020, with e.g. some slight changes to the support
for Apple's platforms, i.e. to the Objective-C/Swift interop.
Kotlin 1.5 was released in May 2021.
Kotlin 1.6 was released in November 2021.
Kotlin 1.7 was released in June 2022, including the alpha version of the new Kotlin
K2 compiler.
1. Kotlin is Open-Source
The very first thing you should know about Kotlin is that it is an open-source programming
language. But, apart from being open-source, Kotlin also provides a single-click tool using
which, developers can convert existing Java code.
And if you’re an Android app developer who is new to Kotlin and interested in learning it
from scratch, we recommend starting with the beginner course available on Udemy and
Udacity. These courses will help you to sharpen your skills
One of the major as well as the best features of Android Kotlin is its deep interoperability
with Java. This, in fact, has attracted many Java developers as well as Android app
developers to learn Kotlin.
It basically runs on JVM and also supports Java libraries as well as tools, providing full Java
interoperability.
Both the languages co-exist, and this makes it easier for developers to be productive.
Developers can easily compile one Android project in both languages with the help of this
feature – interoperability function.
This will allow the developer to switch the programming language instead of changing the
codes. It will also save time for them to develop more Android apps.
It can show 100% interoperable. So, if you need access to a Kotlin method from a Java class
or vice versa, you can do it without any extra parameters.
3. Kotlin Comes With Lazy-Loading Feature
The lazy-loading feature basically increases the startup time, which is very useful when using
it for Android development.
In simple words, it’s the best solution for all developers who want to reduce their Android
app startup time so that their apps’ content can be shown faster.
With the lazy-loading feature, Android developers can load the only resources into main
memory which are necessary. If you are looking for this feature, then Kotlin is the best
choice.
For example, if you have a shopping app, the majority of users will only browse your
selection, that means you could have the payment API be lazy loaded.
4. Data Classes in Kotlin
5. Collection Filtering
We all know that when working with an API, we developers need to deal with collections
quite often. But by using Kotlin’s collection filtering feature, it’s easier to tell what your
resulting list should contain.
In fact, filtering a collection using the built-in Kotlin is very comparable to other
programming languages such as Swift collection types or Java 8 streams.
6. Reduces Crashes at Runtime
This is the most advanced feature, where it is easy to identify the Null Pointer
Exception while compiling your Android app development project.
This will ensure that every variable works as a non-null, and it helps in reducing the number
of crashes at runtime.
Moreover, if you decided to hold on to a null value, then reduce the number of crashes by
appending a question mark at the end of the variable type. This way, you can easily reduce
crashes at runtime.
2.4 VARIABLES AND OPERATORS IN KOTLIN
Variables And Operators used in Kotlin are discussed in below sections.
2.4.1 VARIABLES
A variable is a location in memory (storage area) to hold data.To indicate the storage area,
each variable should be given a unique name (identifier).
val score = 95
The difference in using var and val is discussed later in the article. For now, let's focus on
variable declaration.
Here, language is a variable of type String, and score is a variable of type Int. You don't
have to specify the type of variables; Kotlin implicitly does that for you. The compiler knows
this by initializer expression ("French" is a String, and 95 is an integer value in the above
program). This is called type inference in programming.
However, you can explicitly specify the type if you want to:
We have initialized variable during declaration in above examples. However, it's not
necessary. You can declare variable and specify its type in one statement, and initialize the
variable in another statement later in the program.
... .. ...
... .. ...
Operator Meaning
- Subtraction Operator
* Multiplication Operator
/ Division Operator
% Modulus Operator
Assignment Operators
Assignment operators are used to assign value to a variable. We have already used simple
assignment operator = before.
val age = 5
a -= b a=a-b a.minusAssign(b)
a *= b a=a*b a.timesAssign(b)
a /= b a=a/b a.divAssign(b)
a %= b a=a%b a.modAssign(b)
Here's a table of equality and comparison operators, their meaning, and corresponding
functions:
Logical Operators
in a in b b.contains(a)
Here are some expressions using index access operator with corresponding functions in
Kotlin.
Expression Translated to
a[i] a.get(i)
a[i, n] a.get(i, n)
a[i1, i2, ..., in] a.get(i1, i2, ..., in)
a[i] = b a.set(i, b)
a[i, n] = b a.set(i, n, b)
2.5.1 STRINGS
... .. ...
myString = "Howdy"
Functions Description
compareTo(other: String): Int It compares the current object with
specified object for order. It returns zero if
current is equals to specified other object.
The characters which are present in string are known as elements of string. Element of string
are accessed by indexing operation string[index]. String's index value starts from 0 and ends
at one less than the size of string string[string.length-1]. Index 0 represent first element, index
1 represent second element and so on.
1. val str ="Hello, javatpoint"
2. println(str[0]) //prints H
String templates
String template expression is a piece of code which is evaluated and its result is returned into
string. Both string types (escaped and raw string) contain template expressions. String
templates starts with a dollar sign $ which consists either a variable name or an arbitrary
expression in curly braces.
val i =10
print("i = $i") //i=10
fun main(args: Array<String>) {
val i =10
print("i = $i")//i=10
}
Output:
i=10
2.5.2 FUNCTIONS
Functions are used to break a large program into smaller and modular chunks. For example,
you need to create and color a circle based on input from the user. You can create two
functions to solve this problem:
createCircle() Function
colorCircle() Function
Dividing a complex program into smaller components makes our program more organized
and manageable.
Types of Functions
Depending on whether a function is defined by the user, or available in standard library, there
are two types of functions:
Kotlin Standard Library Function
User-defined functions
The standard library functions are built-in functions in Kotlin that are readily available for
use. For example,
print() is a library function that prints message to the standard output stream
(monitor).
sqrt() returns square root of a number (Double value)
Result = 2.345207879911715
2. User-defined Functions
As mentioned, you can create functions yourself. Such functions are called user-defined
functions.
How to create a user-defined function in Kotlin?
Before you can use (call) a function, you need to define it.
fun callMe() {
// function body
To define a function in Kotlin, fun keyword is used. Then comes the name of the function
(identifier). Here, the name of the function is callMe.
In the above program, the parenthesis ( ) is empty. It means, this function doesn't accept any
argument. You will learn about arguments later in this article.
The codes inside curly braces { } is the body of the function.
2.5.3 ARRAYS
Array is one of the most fundamental data structure in practically all programming
languages. The idea behind an array is to store multiple items of the same data-type,such as
an integer or string under a single variable name.
Arrays are used to organize data in programming so that a related set of values can be
easily sorted or searched.
Here are some basic properties of arrays –
They are stored in contiguous memory locations.
They can be accessed programmatically through their indexes (array[1],
array[0], etc.)
They are mutable.
Their size is fixed.
Creating an array
In Kotlin, arrays are not a native data type, but a mutable collection of similar items which
are represented by the Array class.There are two ways to define an array in Kotlin.
Using the arrayOf() function –
We can use the library function arrayOf() to create an array by passing the values of the
elements to the function.
Syntax:
val num = arrayOf(1, 2, 3, 4) //implicit type declaration
2.6.1 CONDITIONALS
1. Kotlin if expression
println(result)
}
Negative number
val n1 = 3
val n2 = 5
val n3 = -2
println("max = $max")
}
max = 5
2.6.2 LOOPS
2.6.2.1 for-LOOP
The for loop in Kotlin iterates through anything that provides an iterator. In this
article, you learn to create for loop (with the help of examples).
There is no traditional for loop in Kotlin unlike Java and other languages.
In Kotlin, for loop is used to iterate through ranges, arrays, maps and so on
(anything that provides an iterator).
The syntax of for loop in Kotlin is:
// body of loop
2.6.3 LISTS
A list is a collection of items with a specific order. There are two types of lists in Kotlin:
When using List or MutableList, you must specify the type of element that it can contain. For
example, List<Int> holds a list of integers and List<String> holds a list of Strings. If you define
a Car class in your program, you can have a List<Car> that holds a list of Car object instances.
Errors
The error signifies a situation that mostly happens due to the absence of system resources.
The system crash and memory errors are an example of errors. It majorly occurs at runtime.
Exceptions
Exceptions are problems that occur during the program execution and disrupt the
conventional flow. This can occur due to various reasons like invalid arithmetic operation, a
reference to a null object. There are two types of exceptions: Checked exceptions and
Unchecked exceptions.
Kotlin Exception
In Kotlin, there are only unchecked exceptions that are thrown during the runtime execution
of the program. All exception classes descend from the class Throwable. Kotlin uses
the throw keyword to throw an exception object.
Kotlin try-catch block is used for exception handling in the code. The try block encloses the
code which may throw an exception and the catch block is used to handle the exception. This
block must be written within the method. Kotlin try block must be followed by
either catch block or finally block or both.
try{
//code that may throw exception
}catch(e: SomeException){
//code that handles exception
}
Syntax of try with finally block
try{
//code that may throw exception
}finally{
// code finally block
}
Syntax of try catch with finally block
try {
// some code
}
catch (e: SomeException) {
// handler
}
finally {
// optional finally block
}
fun main(args: Array<String>){
val data = 20 / 0 //may throw exception
println("code below exception ...")
}
This above program generates an exception, which causes rest of code below the
exception not executable.
Output:
Excejava.lang.ArithmeticException: / by zero
at ExceptionHandlingKt.main(ExceptionHandling.kt:2)
Let's see an example of try-catch block as an expression which returns a value. In this
example String value to Int which does not generate any exception and returns last statement
of try block.
fun main(args: Array<String>){
val str = getNumber("10")
println(str)
}
fun getNumber(str: String): Int{
return try {
Integer.parseInt(str)
} catch (e: ArithmeticException) {
0
}
}
Output:
10
Let's modify the above code which generate an exception and return the last statement of
catch block.
fun main(args: Array<String>){
val str = getNumber("10.5")
println(str)
}
fun getNumber(str: String): Int{
return try {
Integer.parseInt(str)
} catch (e: NumberFormatException) {
0
}
}
Output:
Next Topic
2.7.2 NULL POINT EXCEPTION
Basically, Kotlin null safety has been proposed to eliminate NullPointerException form the
code. NullPointerException can just only possible on following situations:
A class is a blueprint for the objects which defines a template to be used to create the required
objects.
Classes are the main building blocks of any Object Oriented Programming language. A
Kotlin class is defined using the class keyword. Following is the syntax to create a Kotlin
Class:
//
// Variables or data members
// Member functions or Methods
//
...
...
}
The objects are created from the Kotlin class and they share the common properties and
behaviours defined by a class in form of data members (properties) and member functions
(behaviours) respectively.
We can access the properties and methods of a class using the . (dot) operator as shown
below:
varName.property = <Value>
varName.functionName()
Example
Following is an example where we will create one Kotlin class and its object through which
we will access different data members of that class.
class myClass {
// Property (data member)
private var name: String = "Tutorialspoint.com"
// Member function
fun printMe() {
print("The best Learning website - " + name)
}
}
fun main(args: Array<String>) {
val obj = myClass() // Create object obj of myClass class
obj.printMe() // Call a member function using object
}
Inheritance is one of the key features of object-oriented programming. It allows user to create
a new class (derived class) from an existing class (base class).
The derived class inherits all the features from the base class and can have additional features
of its own.
If you want to add a new feature - eat, you need to implement the same code for each
character. This can easily become error-prone (when copying) and duplicate codes.
It would be a lot easier if we had a Personclass with basic features like talk, walk, eat,
sleep, and add special skills to those features as per our characters. This is done using
inheritance.
Using inheritance, now you don't implement the same code
for walk(), talk() and eat() for each class. You just need to inherit them.
So, for MathTeacher (derived class), you inherit all features of a Person (base class)
and add a new feature teachMath(). Likewise, for the Footballer class, you inherit
all the features of the Person class and add a new feature playFootball() and so on.
This makes your code cleaner, understandable and extendable.
2.9.2 INTERFACE
Creating Interfaces –
The interface definition in Kotlin begins with the interface keyword followed by the name
of the interface, followed by the curly braces within which the members of the interface
reside. The difference is that the members will have no definition of their own. These
definitions will be provided by the conforming types.
Example:
interface Vehicle()
fun start()
fun stop()
}
Implementing Interfaces –
interface Vehicle {
fun start()
fun stop()
println("Car started")
}
{
println("Car stopped")
}
fun main()
obj.start()
obj.stop()
Output:
Car started
Car stopped
Explanation:
In this program, the interface Vehicle declares two methods start() and stop(), which need
to be overridden. The class Car implements the interface using the class-literal syntax and
overrides the two methods using the override keyword. Finally, the main function creates
an object of class Car and calls the two methods.