Kotlin Examples

Android Studio Project (GitHub)

Radio Button Group example

Check Box example

Edit Text – Input Types example

Spinner example

List View example

Grid view example

List view with customize row item example

Option menu example

Frame by Frame animation (resource animation) example

Tween Animation example

Drawing example (using canvas and paint to draw in a View subclass)

Content provider example (retrieve contact and media content)

Location Demo (current location, geo coding, reverse geo coding)

Networking API Demo (Http Connection, load web view using http data)

Notification demo with and without notification channel

Android service example to play and stop music


Array example

import java.util.*

// www.raviroza.com
// 28-Jan-22, 6.52 pm
// program to demonstrate various arrays in kotlin

fun main()
{

    var numbers = arrayOf (1,2,3,4,5)
    var names = arrayOf ("raviroza.com","amit","jamnagar")

    var numbers1 = intArrayOf (1,2,3,4,5)

    println(numbers[0])
    println(names[0])
    println(numbers1[0])

    var arr1 = emptyArray<String>();
    arr1 += "one"
    arr1 += "two"
    arr1 += "three"

    //arr1[3] = "four"

    println("empty array element ->")
    arr1.forEach { i-> println(i) }

    var arr = arrayOfNulls<String>(2)
    arr.set(0, "one")
    arr.set(1, "two")

    var words = arrayOf("cat", "rat", "set")

    var ints = Array<String> (3, {it.toString()})

    println(ints[0])

    var p = intArrayOf(1,2,3,4)
    var q = longArrayOf(1,2,3,4)

    var r = byteArrayOf(1,2,3,4)
    var s = shortArrayOf(1,2,3,4)

    println(Arrays.toString(p))
    println(Arrays.toString(q))
    println(Arrays.toString(r))
    println(Arrays.toString(s))

}

Collection example

// www.raviroza.com
// 27-Jan-22, 6.37 pm

fun main()
{
    // to create read only map
    val phoneBook = mapOf (1 to "ravi",2 to "amit")
    println(phoneBook)

    println(phoneBook.get(1))

    // to define mutable map from read only map
    var pb = phoneBook.toMutableMap()

    // add new element in hash map as it is mutable now
    pb[3] = "raviroza.com"

    pb.put(4,"all in one")

    // display using println
    println(pb)

    // display using for loop
    for(x in pb)
    {
        println(x)
    }
}

Collection – Map example

// www.raviroza.com
// 27-Jan-22, 6.37 pm

fun main()
{
    // to create read only map
    val phoneBook = mapOf (1 to "ravi",2 to "amit")
    println(phoneBook)

    println(phoneBook.get(1))

    // to define mutable map from read only map
    var pb = phoneBook.toMutableMap()

    // add new element in hash map as it is mutable now
    pb[3] = "raviroza.com"

    pb.put(4,"all in one")

    // display using println
    println(pb)

    // display using for loop
    for(x in pb)
    {
        println(x)
    }
}

Collection – Mutable List example

// www.raviroza.com
// 27-Jan-2022, 5.18 pm
fun main()
{
    // creating Mutable List with mutableListOf
    var mutableList = mutableListOf ("C","C++","C#","Java")


    println("Display - using println")
    println(mutableList)


    // methods to modify the list as it is a mutable list
    mutableList.set(0,"C Lang.")
    mutableList.add(2,"Swift")
    mutableList.add("Kotlin")
    mutableList.add("www.raviroza.com")

    mutableList.remove("C Lang.")
    mutableList.removeAt(2)
    
    println()
    println("Display - using For loop")

    for (a in mutableList)
    {
        println(a)
    }
    println(mutableList)
}

Collection – Ready only example

// www.raviroza.com
// 27-Jan-2022, 5.18 pm
fun main()
{
    // creating read-only list with listOf
    var readOnlyList = listOf("C","C++","C#","Java","Kotlin","www.raviroza.com")

    println("Display - using println")
    println(readOnlyList)

    println()
    println("Display - using For loop")
    for (a in readOnlyList)
    {
        println(a)
    }

}

Collection – Set example

// www.raviroza.com
// 27-Jan-2022, 5.55 pm
fun main()
{
    var cities = mutableSetOf("Jam","Raj")

    println("Cities - mutable set")
    cities.add("Jam")
    cities.add("Raj")
    cities.add("Ahm")

    println(cities)

    // creating mutable set of numbers using range
    val numbers = (1..25).toMutableSet()

    // it removes the element with odd indices
    numbers.removeIf { i -> i % 2 == 1 }

    println("\nNumbers - mutable set")
    println(numbers)


    // creating mutable set of chars using range
    val chars = ('a'..'f').toMutableSet()
    println("\nCharacters - mutable set")
    println(chars)


}

Collection with Iterator example

// www.raviroza.com
// 27-Jan-2022, 5.55 pm
fun main()
{
    val fruits = listOf("Apple", "Grapes", "Banana", "Brange")

    var iter = fruits.iterator()

    println("Display - using iterator")
    // while loop to iterate through elements
    while (iter.hasNext())
    {
        println(iter.next())
    }

    // for loop to iterate though elements
    println("\nDisplay - for loop")
    for (i in fruits)
    {
        println(i)
    }
}

Customer Accessor methods example

// www.raviroza.com
// 27-Jan-2022, 5.55 pm
class Student
{
    var name: String=""
    get() = field
    set(value) {field=value}

}

fun main() {
    var o = Student()
    o.name="ravi r oza"
    println(o.name)
}

Default argument example

// www.raviroza.com
// 27-Jan-2022, 5.55 pm
fun DefaultArguDemo(n: Int, msg: String="hi")
{
    var i = 1
    while(i <= n )
    {
        println(msg)
        i++
    }
}
fun main()
{
    DefaultArguDemo(4)
    DefaultArguDemo(4,"hello")
}

Extension function example

// www.raviroza.com
// 27-Jan-2022, 5.55 pm
class ExtensionTest
{
    fun method1()
    {
        println ("Regular method inside of class ")
        println ("Regular ExtensionTest.method1() called")
        println()
    }
}
fun main()
{
    fun ExtensionTest.method2()
    {
        println ("Extension method added from outside of class ")
        println ("ExtensionTest.method2() called")
        println()
    }
    var ex = ExtensionTest();
    ex.method1()
    ex.method2()
}

Function Demo

// www.raviroza.com
// 27-Jan-2022, 5.55 pm
fun displayMsg(n: Int, msg: String)
{
    var i = 1
    while(i <= n )
    {
        println(msg)
        i++
    }
}
fun sum(i: Int, i1: Int): Int {

    return i+i1
}
fun main()
{
    displayMsg(5,"hi")
    //var c = sum(10,20)
    var c = sumInt(10,20)
    println(c)
}
fun sumInt(a: Int, b: Int) = a + b

Getters and Setters example

// www.raviroza.com
// 02-Feb-22, 4.46 pm
class Computer
{
    var name = "no name"

    var model = ""
    // explicit getter
    get()
    {
        return field
    }
    // with short declaration
    // get() = field

    // explicit setter using field Backing field
    set(value)
    {
        field=value
    }
}
fun main() {

    var pc = Computer()

    // implicit setter for name field
    pc.name = "IBM "
    pc.model = "186"

    // implicit getter for name fields
    println("${pc.name} -> ${pc.model}, is an Old Computer ")
    //IBM  -> 186, is an Old Computer

    /*
    var pcs = arrayOf(Computer(),Computer())
    pcs[0].name = "286"
    pcs[1].name = "386"
    for (x in pcs)
        println(x.name)
   */

}

Infix function example – 1

// www.raviroza.com
fun main()
{
    val r = true
    val o = false

    var result: Boolean

    result = r or o // a.or(b)
    println("Result = $result")

    result = r and o // a.and(b)
    println("Result = $result")
}

Infix function example – 2

class MyMath
{
    // user defined infix member function
    infix fun factorial(num : Int): Int
    {
        var t = 1
        var n = num
        while(n>=1)
        {
            t = t * n
            n--
        }
        return t
    }
    infix fun evenOdd(num: Int)
    {
        if(num % 2 == 0)
            println ("$num is EVEN")

        else
            println ("$num is ODD")
    }
}
fun main()
{
    var m = MyMath()
    var x = 5
    var f = m factorial x

    println("Factorial of $x is $f")


    //various way to call infix method
    m.evenOdd(5)

    m evenOdd (7)

    m evenOdd 9

}

Named parameter example

// www.raviroza.com
// 2-Feb-2022, 4.00 pm
fun NamedParaDemo(name:String = "ravi r oza", city:String = "jamnagar", id:Int = 101)
{
    println("ID    : $id")
    println("Name  : $name")
    println("City  : $city")
}
fun main()
{
    NamedParaDemo(name="raviroza.com",id=201)
    NamedParaDemo(id=301,name="Oza Ravi")
}

Parameter constructor example

// www.raviroza.com
// 15-Jan-2022, 4.00
class Person (_name : String) {
    var name: String

    init {
        name = _name
    }

    override fun toString():String
    {
        return name.toString()
    }
}

fun main() {

    var o = Person("raviroza.com")
    print(o.toString())
}

Secondary constructor example

// www.raviroza.com
// 15-Jan-2022, 4.00
class PersonNew{
    var name: String

    constructor(_name:String) {
        name = _name
    }

    override fun toString():String
    {
        return name.toString()
    }
}

// Emp class with primary constructor and default arguments
class Emp (_name:String, _empid:String = "1001") {
    val name = _name
    val empid = _empid

    override fun toString(): String {
        return "Emp(name='$name', empid='$empid')"
    }
}
class Employee
{
    var name:String = ""
    var empid:String = ""

    // Below secondary constructor doesn’t have a body;
    // Moreover, this constructor invokes another constructor, that accepts 2 arguments.
    constructor(_name: String) : this(_name,"101")

    // Below constructor takes two parameters: a name and an employee id.
    constructor(_name: String, _id:String)
    {
        name = _name
        empid = _id
    }
    override fun toString(): String {
        return "Employee(name='$name', empid='$empid')"
    }
}

fun main() {

    //var o = PersonNew("raviroza.com")
    //print(o.toString())

    var obj = Emp("ravi r oza","101@gmail.com")
    println(obj)

}

if else example

// www.raviroza.com
// 26-Jan-2022, 4.00
fun main()
{
    var day = 1
    if (day == 1) {
        println("Today is Sunday")
    }
    else if (day == 2) {
        println("Today is Monday")
    }
    else if ( day == 3) {
        println("Today is Tuesday")
    }
}

if else as statement example

// www.raviroza.com
// 26-Jan-2022, 4.00
fun main()
{
    var a = 15
    var b = 20

    var c = if(a >= b)
        a
    else
        b
    println ("Maximum number is $c")
}

While loop example

// www.raviroza.com
// 27-Jan-2022, 5.55 pm
fun main()
{
    // while loop demo
    var i = 1
    var n = 5
    while (i <= n)
    {
        println("www.raviroza.com $i")
        i++
    }
}

above program can also written like below, where value of n is read from user using readLine()!!. The readline() function with !! sign will make sure that value is not null.

fun main() 
{
    // while loop demo
    var i = 1
    print ("enter count : ")
    var n = readLine()!!
    while (i <= n.toInt()) 
    {
        println("www.raviroza.com $i")
        i++
    }
}

For loop example

fun main()
{
    // for loop demo
    var i = 1
    print ("for loop demo\nEnter count : ")
    var n = readLine()!!
    
    for (i in 1..n.toInt())
    {
        println("www.raviroza.com $i")
    }
     
    for(i in n.toInt() downTo 1)
    {
        println("www.raviroza.com $i")
    }
}

For loop with Array

fun main()
{
    // for loop -> Iterating an Array
    var heros = arrayOf("amit","rajesh","dilip","raj")
    for(hero in heros)
    {
        println("$hero is a very good actor")
    }


   // for loop -> using indices to get elements
    for(hero in heros.indices)
    {
        println(heros[hero] + " is a very good actor")
    }
}

For loop -> Iterating a String

fun main()
{
    // for loop -> Iterating a String
    var lang = "Android"
    for (ch in lang) {
        println(ch)
    }
}

Loops (all in one)

// www.raviroza.com
// 26-Jan-2022, 4.00

fun main()
{
    forLoopDemo()
    // for loop -> Iterating a String
    /*var lang = "Android"
    for (ch in lang) {
        println(ch)
    }*/
}

fun forLoopWithArray()
{
    // for loop -> Iterating an Array
    var heros = arrayOf("amit","rajesh","dilip","raj")
    for(hero in heros)
    {
        println("$hero is a very good actor")
    }

    // for loop -> using indices to get elements
    for(hero in heros.indices)
    {
        println(heros[hero] + " is a very good actor")
    }
}

fun forLoopDemo()
{
    // for loop demo
    var i = 1
    print ("For loop demo\nE nter Limit  : ")
    var n = readLine()!!
    for (i in 1..n.toInt())
    {
        println("www.raviroza.com $i")
    }

    for(i in n.toInt() downTo 1)
    {
        println("www.raviroza.com $i")
    }
}

fun whileLoop()
{
    // while loop demo
    var i = 1
    print ("Enter Limit : ")
    var n = readLine()!!
    while (i <= n.toInt())
    {
        println("www.raviroza.com $i")
        i++
    }
}
    /*
    var zeroToTen = 0..10
    for(t in zeroToTen)
    {
        println(t)
    }
    if (9 in zeroToTen) println("9 is in zeroToTen")

     */

//}

When statement example

When statement is similar to switch statement in Java.

// www.raviroza.com
// 26-Jan-2022, 4.00 pm
fun main()
{
    print("What is your answer to life? : ")
    var response:Int? = readLine()?.toInt()
    val message = when(response){
        32 -> "Very good, and thanks for the all wish"
        33, 34, 35 -> "either 33,34 or 35"
        in 51 .. 100 -> "fifty one to one hundred"
        else -> "Sorry ! It Not what I'm looking forward to"
    }
    println(message)
}
//fun main()
//{
//    print("Enter Day Number: ")
//    var day = readLine()!!
//    var msg =
//    when (day.toInt()) {
//        1 -> "Sunday"
//        2 -> "Monday"
//        3 -> "Tuesday"
//        4 -> "Wednesday"
//        5 -> "Thursday"
//        6 -> "Friday"
//        7 -> "Saturday"
//        else -> "Invalid day number"
//    }
//    println(msg)
//}
/*fun main()
{
    print("Enter Day Number: ")
    var day = readLine()!!
    when (day.toInt()) {
        1 -> println("Sunday")
        2 -> println("Monday")
        3 -> println("Tuesday")
        4 -> println("Wednesday")
        5 -> println("Thursday")
        6 -> println("Friday")
        7 -> println("Saturday")
        else -> println("Invalid day number")
    }
}*/

Classes in Kotlin

// www.raviroza.com
// 10-Jan-2022, 10.15 am

class A
{
    constructor()
    {
        println("A default constr. called")
    }
    constructor(n:Int)
    {
        println("A int constr. called : "+n)
    }
    constructor(n:String)
    {
        println("A int constr. called : "+n)
    }
    fun m1()
    {
        println("A.m1() called")
    }

}
class Student
{
    var name:String=""
    constructor(name:String)
    {
        this.name = name
        //println("name is : "+this.name)
    }
    fun readName()
    {
        print("enter your good name :")
        this.name = readLine().toString()
    }
    fun getName():Any
    {
        return this.name
    }
}
fun main()
{

    var s = Student("Priya")
    s.readName()
    println(s.getName())
    /*var obj = A()
    obj = A(19)
    obj = A("testing is always helpful")
    obj.m1()*/
}
package com.raviroza.sqlitedbdemo

import android.database.sqlite.SQLiteDatabase
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.ArrayAdapter
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity()
{
    lateinit var sql : String
    lateinit var DB : SQLiteDatabase
    lateinit var allData : ArrayList<String>
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        try {
            DB = openOrCreateDatabase("mydb", MODE_PRIVATE,null)
            DB.execSQL("CREATE TABLE IF NOT EXISTS student(rollno VARCHAR,name VARCHAR,marks VARCHAR);")
            loadData()

            Toast.makeText(this, DB.path.toString(), Toast.LENGTH_SHORT).show()

            btnAdd.setOnClickListener()
            {
                sql = "insert into student values (${editRollno.text}, '${editName.text}', ${editMarks.text})"
                DB.execSQL(sql)
                displayMsg("Added")
                loadData()
            }
        }
        catch (e:Exception)
        {
            Log.e("RRR",e.toString())
            displayMsg(e.toString())
        }
    }

    fun loadData()
    {
        val data = DB.rawQuery("Select * from student",null)
        allData = ArrayList()
        while(data.moveToNext())
        {
            allData.add(data.getString(0) + "  |  " + data.getString(1) + "  |  " +data.getString(2))
        }
        val adapter = ArrayAdapter(this,android.R.layout.simple_list_item_1,allData)
        lstData.adapter = adapter
    }
    fun displayMsg(msg:String)
    {
        Toast.makeText(this,msg,Toast.LENGTH_SHORT).show()
    }
}