Kotlin Basics

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 19

Android

Android is an open source and Linux-based Operating System for mobile devices


such as smartphones and tablet computers. Android was developed by the Open Handset
Alliance, led by Google, and other companies.

Android offers a unified approach to application development for mobile devices


which means developers need only develop for Android, and their applications should be able
to run on different devices powered by Android.

The first beta version of the Android Software Development Kit (SDK) was released
by Google in 2007 where as the first commercial version, Android 1.0, was released in
September 2008.

On June 27, 2012, at the Google I/O conference, Google announced the next Android
version, 4.1 Jelly Bean. Jelly Bean is an incremental update, with the primary aim of
improving the user interface, both in terms of functionality and performance.
Features of Android:
Android is a powerful operating system competing with Apple 4GS and supports great
features. Few of them are listed below –

Sr.No Feature & Description


.

1 Beautiful UI
Android OS basic screen provides a beautiful and intuitive
user interface.

2 Connectivity
GSM/EDGE, IDEN, CDMA, EV-DO, UMTS, Bluetooth,
Wi-Fi, LTE, NFC and WiMAX.

3 Storage
SQLite, a lightweight relational database, is used for data
storage purposes.

4 Media support
H.263, H.264, MPEG-4 SP, AMR, AMR-WB, AAC, HE-
AAC, AAC 5.1, MP3, MIDI, Ogg Vorbis, WAV, JPEG,
PNG, GIF, and BMP.

5 Messaging
SMS and MMS

6 Web browser
Based on the open-source WebKit layout engine, coupled
with Chrome's V8 JavaScript engine supporting HTML5 and
CSS3.

7 Multi-touch
Android has native support for multi-touch which was
initially made available in handsets such as the HTC Hero.
8 Multi-tasking
User can jump from one task to another and same time
various application can run simultaneously.

9 Resizable widgets
Widgets are resizable, so users can expand them to show
more content or shrink them to save space.

10 Multi-Language
Supports single direction and bi-directional text.

11 GCM
Google Cloud Messaging (GCM) is a service that lets
developers send short message data to their users on Android
devices, without needing a proprietary sync solution.

12 Wi-Fi Direct
A technology that lets apps discover and pair directly, over a
high-bandwidth peer-to-peer connection.

13 Android Beam
A popular NFC-based technology that lets users instantly
share, just by touching two NFC-enabled phones together.

Android Libraries

This category encompasses those Kotlin-based libraries that are specific to Android
development. Examples of libraries in this category include the application framework
libraries in addition to those that facilitate user interface building, graphics drawing and
database access. A summary of some key core Android libraries available to the Android
developer is as follows −

android.app − Provides access to the application model and is the cornerstone of all
Android applications.
android.content − Facilitates content access, publishing and messaging between
applications and application components.
android.database − Used to access data published by content providers and includes
SQLite database management classes.
android.opengl − A Java interface to the OpenGL ES 3D graphics rendering API.
android.os − Provides applications with access to standard operating system services
including messages, system services and inter-process communication.
android.text − Used to render and manipulate text on a device display.
android.view − The fundamental building blocks of application user interfaces.
android.widget − A rich collection of pre-built user interface components such as
buttons, labels, list views, layout managers, radio buttons etc.
android.webkit − A set of classes intended to allow web-browsing capabilities to be
built into applications.
Android Layout Types
There are number of Layouts provided by Android which you will use in almost all the
Android applications to provide different view, look and feel.

Sr.No Layout & Description

1 Linear Layout

LinearLayout is a view group that aligns all children in a


single direction, vertically or horizontally.

2 Relative Layout

RelativeLayout is a view group that displays child views in


relative positions.

3 Table Layout

TableLayout is a view that groups views into rows and


columns.

4 Absolute Layout

AbsoluteLayout enables you to specify the exact location of


its children.

5 Frame Layout
The FrameLayout is a placeholder on screen that you can
use to display a single view.

6 List View

ListView is a view group that displays a list of scrollable


items.

7 Grid View

GridView is a ViewGroup that displays items in a two-


dimensional, scrollable grid.

Layout Attributes:

Each layout has a set of attributes which define the visual properties of that layout. There are
few common attributes among all the layouts and their are other attributes which are specific
to that layout. Following are common attributes and will be applied to all the layouts:

Sr.No Attribute & Description

1 android:id
This is the ID which uniquely identifies the view.

2 android:layout_width
This is the width of the layout.

3 android:layout_height
This is the height of the layout

4 android:layout_marginTop
This is the extra space on the top side of the layout.

5 android:layout_marginBottom
This is the extra space on the bottom side of the layout.

6 android:layout_marginLeft
This is the extra space on the left side of the layout.

7 android:layout_marginRight
This is the extra space on the right side of the layout.

8 android:layout_gravity
This specifies how child Views are positioned.

9 android:layout_weight
This specifies how much of the extra space in the layout
should be allocated to the View.

10 android:layout_x
This specifies the x-coordinate of the layout.

11 android:layout_y
This specifies the y-coordinate of the layout.

12 android:layout_width
This is the width of the layout.

13 android:paddingLeft
This is the left padding filled for the layout.

14 android:paddingRight
This is the right padding filled for the layout.

15 android:paddingTop
This is the top padding filled for the layout.

16 android:paddingBottom
This is the bottom padding filled for the layout.

KOTLIN BASICS
Kotlin is a cross platform, statically-typed object-oriented programming language
developed by JetBrains primarily targeting the JVM and Google through the Kotlin
Foundation. KOTLIN is designed to interoperate fully with java but type inference allows its
syntax to be more concise Kotlin is developed with the goals of being quick to compile,
backwardscompatible, very type safe, and 100% interoperable with Java. Kotlin is also
developed with the goal of providing many of the features wanted by Java developers.
Kotlin's standard compiler allows it to be compiled both into Java bytecode for the JVM and
into JavaScript.

The most reason for introducing Kotlin to Android advancement was to decrease the


number of lines of code and make development more convenient to prepare. Everything that
can be done utilizing Java can be done utilizing Kotlin for Android development

Kotlin has a standard IDE plugin for Eclipse and IntelliJ. Kotlin can also be compiled
using Maven, using Ant, and using Gradle, or through the command line. It is worth noting in
$kotlinc Main.kt will output a java class file, in this case MainKt.class (Note the Kt
appended to the class name).

All Kotlin programs start at the main function. Here is an example of a simple Kotlin
"Hello World" program:

package my.program fun main(args: Array)

println("Hello, world!")

}
Dynamic EditText in Kotlin:
 EditText is used to get input from the user.
 EditText is commonly used in login or registration screens. we already learn how to
create an EditText using layout. In this article, we will learn about how to create
android EditText programmatically in kotlin.
 At first, we will create a new android application. Then, we will create an EditText
dynamically.
 If you already created the project then ignore step 1.

Ste
p Description

1. Open Android Studio.

2. Go to File => New => New Project.

3. Then, select Empty Activity and click on next


Ste
p Description

1.Write application name as DynamicEditTextKotlin


2. Select minimum SDK as you need, here we have selected 21 as
minimum SDK
3. Choose language as Kotlin and click on finish button.
4.

If you have followed above process correctly, you will get a newly
5. created project successfully.

After creating project we will modify xml files then.


 Open res/layout/activity_main.xml file and add code into it.

Place the above code into a file named Main.kt (this filename is entirely arbitrary) When
targeting the JVM, the function will be compiled as a static method in a class with a name
derived from the filename. In the above example, the main class to run would be
my.program.MainKt

1. Kotlin file has an extension .kt


2. All classes in Kotlin have a common superclass Any, that is a default super for a class
with no supertypes declared(similar to Object in Java).

3. Variables can be declared as val(immutable- assign once) or var(mutables- value


can be changed)
4. Semicolon is not needed at end of statement.
5. If a function does not return any useful value, its return type is Unit.It is also
optional.
6. Referential equality is checked by the === operation. a === b evaluates to true if and
only if a and b point to the same object.

Data Types:

The most fundamental data type in Kotlin is the Primitive data type and all others are
reference types like array and string. Java needs to use wrappers (java.lang.Integer) for
primitive data types to behave like objects but Kotlin already has all data types as objects.
There are different data types in Kotlin:
1. Integer Data type
2. Floating-point Data Type
3. Boolean Data Type
4. Character Data Type

Data Type Bits

byte 8 bits

short 16 bits

int 32 bits

long 64 bits

float 32 bits

double 64 bits

char 16 bits

boolean 1 bits

Example:

fun main(args : Array<String>)


{
var myint = 35
println("My integer ${myint}") // My integer 35

    // add suffix F for float


    var myfloat = 54F                
    println("My float value ${myfloat}") // My float value 54.0

var alphabet: Char = 'C'

    println("C is a character : ${alphabet is Char}")//C is a character : true


if (true is Boolean)

{
print("Yes,true is a boolean value")
    }
}

Variables:

In Kotlin, every variable should be declared before it’s used. Without declaring a variable, an
attempt to use the variable gives a syntax error. Declaration of the variable type also decides
the kind of data you are allowed to store in the memory location.

In case of local variables, the type of variable can be inferred from the initialized value.

var rollno = 55

var name = "XYZ"

println(rollno) // 55

println(name) // XYZ

Above we have the local variable rollno whose value is 55 and it’s type is Integer
because the literal type is Int and another variable is name whose type is String.In Kotlin,
variables are declared using two types –

1. Immutable using val keyword
2. Mutable using var keyword

1. Immutable is also called read-only variables. Hence, we can not change the value of the
variable declared using val keyword.

val myName = "Gaurav"

myName = "Praveen" // compile time error

// It gives error Kotlin Val cannot be reassigned


Note: Immutable variable is not a constant because it can be initialized with the value of a
variable. It means the value of immutable variable doesn’t need to be known at compile-time,
and if it is declared inside a construct that is called repeatedly, it can take on a different value
on each function call.

var myBirthDate = "02/12/1993"

val myNewBirthDate = myBirthDate

println(myNewBirthDate)

2. In Mutable variable we can change the value of the variable.

var myAge = 25

myAge = 26 // compiles successfully

println("My new Age is ${myAge}")

Output:

My new Age is 26

Standard Input/Output:

Kotlin standard I/O operations are performed to flow sequence of bytes or byte
streams from input device such as Keyboard to the main memory of the system and from
main memory to output device such as Monitor. In Java, we use System.out.println(message)
to print output on the screen but, in Kotlin println(message) is used to print. 

Kotlin standard output is the basic operation performed to flow byte streams from
main memory to the output device. You can output any of the data types integer, float and
any patterns or strings on the screen of the system. 
You can use any one of the following function to display output on the screen.  
print() function

println() function

Here is the Kotlin program for standard output.  

fun main(args: Array<String>)

    print("Hello, Geeks! ")

    println("This is Kotlin tutorial.")

Output:

Hello, Geeks! This is Kotlin tutorial

Difference between println() and print() – 


print() function prints the message inside the double quotes. 
println() function prints the message inside the double quotes and moves to the beginning of
the next line.

fun main(args

         : Array<String>)

 print("GeeksforGeeks - ")

    print("A Computer Science portal for Geeks")


}

Output:

GeeksforGeeks - A Computer Science portal for Geeks


Take input from user using readline() method –  

fun main(args : Array<String>) {

    print("Enter text: ")

    var input = readLine()

    print("You entered: $input") // Enter text: Hello, hi

Take input from user without using the Scanner class:  


Here, we will use readline() to take input from the user and no need to import Scanner
class. 

fun main(args: Array<String>) {

    print("Enter an Integer value: ")

//readline()!! take the input as a string and followed by


(!!) to ensure that the input value is not null

    val string1 = readLine()!! 

    // .toInt() function converts the string into Integer

    var integerValue: Int = string1.toInt()

    println("You entered: $integerValue")

    print("Enter a double value: ")


    val string2= readLine()!!

    // .toDouble() function converts the string into Double

    var doubleValue: Double = string2.toDouble()

    println("You entered: $doubleValue")

Type Conversion:

Type conversion (also called as Type casting) refers to changing the entity of one data type
variable into another data type.

But, Kotlin does not support implicit type conversion. An integer value can not be assigned to
the long data type.  

var myNumber = 100

var myLongNumber: Long = myNumber // Compiler error

// Type mismatch: inferred type is Int but Long was expected

In Kotlin, the helper function can be used to explicitly convert one data type to another data
type. 

Example: 

var myNumber = 100

var myLongNumber: Long = myNumber.toLong() // compiles successfully

The following helper function can be used to convert one data type into another:  

 toByte() 
 toShort() 
 toInt() 
 toLong() 
 toFLoat() 
 toDouble() 
 toChar() 

Note: There is No helper function available to convert into boolean type.

Kotlin Program to convert the one data type into another:  

fun main(args: Array<String>)


{
    println("259 to byte: " + (259.toByte()))
    println("50000 to short: " + (50000.toShort()))
    println("21474847499 to Int: " + (21474847499.toInt()))
    println("10L to Int: " + (10L.toInt()))
    println("22.54 to Int: " + (22.54.toInt()))
    println("22 to float: " + (22.toFloat()))
    println("65 to char: " + (65.toChar()))
    println("A to Int: " + ('A'.toInt()))
}

Output: 

259 to byte: 3
50000 to short: -15536
21474847499 to Int: 11019
10L to Int: 10
22.54 to Int: 22
22 to float: 22.0
65 to char: A
A to Int: 65
Functions:

A function is a unit of code that performs a special task. In programming, function is used to
break the code into smaller modules which makes the program more manageable. For
example: If we have to compute sum of two numbers then define a fun sum().

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

return a + b

 In Kotlin, there are two types of function- 

1. Standard library function


2. User defined function

 Standard library function –

In Kotlin, there are different number of built-in functions already defined in standard library
and available for use. We can call them by passing arguments according to requirement. In
below program, we will use built-in functions arrayOf(), sum() and println(). The
function arrayOf() require some arguments like integers, double etc to create an array and we
can find the sum of all elements using sum() which does not require any argument. 

Example:

fun main(args: Array<String>) {

    var num1 = 26

    var num2 = 3

    var result = num1.rem(num2)

    println("The remainder when $num1 is divided by $num2


is: $result")
}

Output:

The remainder when 26 is divided by 3 is: 2

User-defined function –

A function which is defined by the user is called user-defined function. As we know, to


divide a large program in small modules we need to define function. Each defined function
has its own properties like name of function, return type of a function, number of parameters
passed to the function etc.

Creating user-defined function-

In Kotlin, function can be declared at the top, and no need to create a class to hold a function,
which we are used to do in other languages such as Java or Scala. Generally we define a
function as:

fun fun_name(a: data_type, b: data_type, ......): return_type {

// other codes

return

Here,

fun– Keyword to define a function.

fun_name – Name of the function which later used to call the function.

a: data_type – Here, a is an argument passed and data_type specify the data type of
argument like integer or string.

return_type – Specify the type of data value return by the function.


{….} – Curly braces represent the block of function.

You might also like