Showing posts with label KOTLIN. Show all posts
Showing posts with label KOTLIN. Show all posts

Monday, 22 August 2022

Advanced Kotlin Coroutines : Introduction

 Hi, 

Today I am unwraping the topic in Kotin world i.e. Coroutine.

If you want to get started with Kotlin coroutine and ease your daily development tasks by using it , then this series is for you. 

In this post , I am starting with introduction , then in future posts we will read more interesting coroutine topics together :) 

So let's get started.

First question which comes in our mind is , 

What is the need of Coroutine?

All the components in an android application , use the same thread of execution i.e. our Main thread.

This main thread is responsible to perform many tasks like drawing the views, executing logical pieces of code in a sequential manner, etc.

So it's developers duty to make sure that main thread must not be blocked. For this reason multi threading comes in picture, with this approach the long or short running tasks which take time should run on a different worker thread to prevent the blocking of main thread and unresponsiveness of the app.

Multithreading in Android has always been a challenge due to it's callback mechanism ,switching between threads and resuming tasks. 

In android multithreading started with Async Task , then RxJava and now we have coroutine to achieve this.

What is Coroutine?

From Kotlin docs:

One can think of a coroutine as a light-weight thread. Like threads, coroutines can run in parallel, wait for each other and communicate. The biggest difference is that coroutines are very cheap, almost free: we can create thousands of them, and pay very little in terms of performance. True threads, on the other hand, are expensive to start and keep around. A thousand threads can be a serious challenge for a modern machine.

A coroutine is a function that can pause its execution to be resumed later. You can think of coroutines as lightweight threads.

Coroutine word is made of two words : co + routine 

Co means cooperate and routine means functions . So we can say coroutine means when functions cooperate, which states : 

  • Coroutines are nothing but lightweight threads. 
  • Coroutines provide us an easy way to do synchronous and asynchronous programming. 
  • Coroutines allow execution to be suspended and resumed later at some point in the future which is best suited for performing non-blocking operations in the case of multithreading.

There are few properties of coroutines

  • They are light-weight
  • Built-in cancellation support
  • Lower chances for memory leaks
  • Jetpack libraries provide coroutines support
It was added to Kotlin in version 1.1. 

Now we understood a little bit about coroutines. 

Also there are some important concepts related to coroutines which will be covered in next posts like :
suspend, Job, Dispatchers, CoroutineScope, CoroutineContext, etc. 


Thursday, 23 April 2020

Kotlin : lateinit keyword vs lazy delegation (Post 21)

Hi ,

Here is my last topic of this Kotlin Basic Series . In this post I will talk about lateinit keyword & lazy delegation

lateinit keyword : 

It is used at the time of variable declaration , there are some rules :

  • It is used with mutable type of variables i.e. var
    • lateinit var name : String  ------  Allowed
    • lateinit val name : String  ------ Not Allowed
    • Allowed only non-nullable data types 
      • lateinit var name : String  ------  Allowed
      • lateinit val name : String?  ------ Not Allowed
    • The value must be assigned before it is used , other it throws UnintializedPropertyAccessException
    lateinit var name : String
    


    lazy Delegation :

    lazy is lazy initialization.

    lazy() is a function that takes a lambda and returns an instance of lazy which can serve as a delegate for implementing a lazy property:
    • The first call to get() executes the lambda passed to lazy() and remembers the result, subsequent calls to get() simply return the remembered result.
    • It is thread safe , it is initialized in thread where it is used for the first time , other threads used the same value remembered result which is stored in cache . 
    • It can be used with var & val both
    • It can be used with nullable & non-nullable values both 

    public class Example{
      val name: String by lazy { "Android" }
    }

    So that's it  for this post and for this series as well . I tried to explore and cover all the basic topics of Kotlin here, and with the help of these topics one can understand and develop android applications in Kotlin as well .

    In next post , I will explore a very interesting & essential topic i.e. Accessibility , till then Happy Coding 😀😀



    Kotlin : Null Safety Operators (Post 20)

    Hi ,

    I am here again to share another important topic of Kotlin , which is  null safety . In Kotlin , it is defined to avoid NullPointerException .
    There are following types of Null Safe Operators which can be used in our code to avoid NPE :


    • Safe Call (?.)
    • Safe Call with let ( ?.let)  
    • Elvis Operator (?:)
    • Non-null Assertion Operator (!!)

    Safe Call (?.) 


    It can be used when null value will not affect the programming flow . 
    Variable will return the value if not null else return null value. 

    var name : String? = null
    var name2 : String = "Hello"
            
    println("Length of NAME:"+ name?.length) //using safe call operator for nullable
    println("Length of NAME2:"+ name2.length)
    

    Output :


    Length of NAME:null
    Length of NAME2:5
    

    Here we can see that Name2 length is 5 , but name is having null value so length is also returning null.

    ======================================================================

    Safe Call with let ( ?.let)  

    Executes the let block only when , if the variable value is NOT NULL

    var name : String? = null
    var name2 : String = "Hello"
    
    name?.let {  println("Length of NAME:"+ name?.length) }
    
    name2.let {   println("Length of NAME2:"+ name2.length) }
    

    Output :


    Length of NAME2:5
    

    Since name is having null value so for that let block will not execute , so it will not print the statement , only name2 , let statement will execute and show the output.

    ========================================================================

    The Elvis Operator 

    It is represented by a question mark followed by a colon: ?: and it can be used with this syntax:
    first operand ?: second operand
    If first operand isn't null, then it will be returned. If it is null, then the second operand will be returned. This can be used to guarantee that an expression won't return a null value, as you'll provide a non-nullable value if the provided value is null.

    var name: String? = null
            
    val length = name?.length ?: -1
    println("Length of NAME: " + length)
    

    Output :


    Length of NAME: -1
    

    Here value of name is null so last statement is executed !

    ========================================================================

    Non-null Assertion Operator(!!) 

    This can be used when it is sure that variable value must not be NULL , it will throw NullPointerException , when variable is found Null .

    var name : String? = null
    var name2 : String = "Hello"
    
    println("Length of NAME2:"+ name2!!.length)
    println("Length of NAME:"+ name!!.length) //this will throw NPE
           
    

    Output :

    Length of NAME2:5
    
    Unable to start activity ComponentInfo: kotlin.KotlinNullPointerException
    

    As operator explains that throw NPE in case variable will contain null value , so when getting the length of name variable , which is having null value , it is throwing NullPointerException.

    So this is the basic practice of how Null Safety has been handled in Kotlin . I will share another post in this series very soon , till then Happy Coding 😀😀









    Kotlin : filter & map (Post 19)

    Hello All,

    Today I am going to share 2 another important operations that are "filter" & "map" ,

    Filter : This is used to apply a condition , on collections elements and get the resultant collections data , then there "filter" is used.

    Map : This is used to transform all the elements of collections data

     override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
           
            var myList =  mutableListOf<Int>(34 , 6 , 29 , 15 , 65 , 9 , 12 , 42)
            var myEvenList = myList.filter { it%2 == 0 }
            for(num in myEvenList){
                println(num)
            }
             println("Double list : ")
    
            var myDoubleList = myEvenList.map { it*2 }
            for(num in myDoubleList){
                println(num)
            }
        }
    

    Output :

    34
    6
    12
    42
    
    Double list : 
    68
    12
    24
    84
    

    Here , we can see that I have added the condition to get even number from the myList , which is returning myEvenList , then I applied the map condition for getting the double numbers of all the elements of myEvenList , which we are getting in myDoubleList .

    Now take one example of Employee Data class :


    override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
         
            var myList = listOf<Employee>(
                Employee(101,"Alen"),
                Employee(102,"Harrey"),
                Employee(103,"John"),
                Employee(104,"Sam"),
                Employee(105,"Alice"))
            var nameList: List<String> = myList.map{it.empName}
    
            for(name in nameList){
                println(name)
            }
            println("Initial List : ")
            var initialList = nameList.filter{ person -> person.startsWith("A")}
            for(num in initialList){
                println(num)
            }
        }
        class Employee (var empId: Int, var empName: String) {
        }
    

    Output :
    Alen
    Harrey
    John
    Sam
    Alice
    
    Initial List : 
    Alen
    Alice
    


    Here I have used one list , which is containing the list of Employees ,
    then in nameList , all the names are fetched using map()
    then from nameList , all the names are fetched starting with 'A'  , returning the initialList .

    Hope this will help to understand these two important topics of Kotlin. Will share another interesting topic in my next post , till then Happy Coding 😀😀

    Kotlin : Collections Set & HashSet (Post 18)

    Hi  ,

    Here I am again going to share how Set and HashSet are working in Kotlin .

    Let's take a look first what is Set and HashSet :

    Set : Always contains unique elements

    HashSet : Always contains unique elements , and output sequence is not guaranteed .

    override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            
            /**
             * Set -> contains unique elements
             * HashSet -> contains unique elements ,but sequence is not same
             */
            //immutable , fixed size , Read only operation
            var mySet = setOf<Int>(13, 4, 32 , 2, 2, 2 , 5, 8 , 13)
            for (element in mySet) {
                println("Immutable Elements: $element ")
            }
    
            //mutable ,not fixed in size ,Read & Write Operations
            var mutableSet1 = hashSetOf<Int>()
            var mutableSet = mutableSetOf<Int>(13, 4, 32 , 2, 2, 2 , 5, 8 , 13)
            mutableSet.add(56)
            mutableSet.remove(5)
    
            for (element in mutableSet) {
                println("mutable Elements : $element")
            }
        }
    

    Output :

    Immutable Elements: 13 
    Immutable Elements: 4 
    Immutable Elements: 32 
    Immutable Elements: 2 
    Immutable Elements: 5 
    Immutable Elements: 8 
    mutable Elements : 13
    mutable Elements : 4
    mutable Elements : 32
    mutable Elements : 2
    mutable Elements : 8
    mutable Elements : 56
    

    Here we can see the for Immutable section

    •  all the elements sequence is same as input , 
    • the duplicate elements has been removed ! 

    But for mutable section :

    • The duplicates elements are removed 
    • Input Elements sequence have been changed
    • Element 5 has been removed using .remove() operation
    • Element 56 has been added using .add() operation
    So this is the simple example of Set and HashSet in Kotlin , this will help to get a basic understanding. In next post I will again explore 1 interesting topic in Kotlin , till then Happy Coding 😀😀




    Tuesday, 21 April 2020

    Kotlin : Collections Map & HashMap (Post 17)

    Hi ,

    Again I am here to share one another topic in Kotlin series i.e. Map & HashMap

    So as we all know that how map & hashmap algorithm , how they save the elements using keys .
    In the same way here in Kotlin , the elements are saved using keys , also elements modifications are also done using keys.

    Now , after talking so much for this , let's directly move to technical stuff :

    override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
           
            //immutable , fixed size , Read only operation
            var myMap = mapOf<Int, String>(13 to "Android", 4 to "iOS", 32 to "Flutter")
            for (key in myMap.keys) {
                println("Elements with Key: $key => ${myMap[key]}")
            }
    
            //mutable ,not fixed in size ,Read & Write Operations
            var mutableMap1 = hashMapOf<Int, String>()
            var mutableMap2 = HashMap<Int, String>()
            var mutableMap = mutableMapOf<Int, String>()
            mutableMap.put(13, "android")
            mutableMap.put(3, "iOS")
            mutableMap.put(6, "flutter")
    
            //remove
            mutableMap.remove(3) //removing
            mutableMap.put(3, "React Native") //adding
            for (key in mutableMap.keys) {
                println("mutable Elements with Key: $key => ${mutableMap[key]}")
            }
        }
    

    So here we can see that , I have added two types of maps one is immutable and another one is mutable .

    In both types of maps , I have added the elements on the basis of keys
    and in mutable type of maps I have also modified the elements using keys.

    That's a small demo foe how maps and hashmaps will work with Kotlin. In next post I will share the functionality of  Set & HashSet , till then Happy Coding 😀😀

    Kotlin : Collections Mutable & Immutable with List & Array List (Post 16)

    Hi ,

    Let's take a look , how collections work in Kotlin . There are basically 2 types of Collections :

    Mutable & Immutable

    Immutable :  Read Only Operations , Fixed Size 

    • Immutable List : listOf
    • Immutable Map : mapOf
    • Immutable Set: setOf
    Mutable :  Read  & Write Operations , Not Fixed Size 

    • Mutable List :  ArrayList , ArrayListOf , mutableListOf
    • Mutable Map : HashMap , HashMapOf, mutableMapOf
    • Mutable Set:    HashSetOf , mutableSetOf

         
    Here I am sharing a basic example of List & ArrayList , to understand how can we use it :

    override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            //immutable , fixed size , Read only operation
            var myList  =  listOf<String>("Android" , "iOS" , "Flutter")
            for(element in myList){
            println(element)
            }
    
            //mutable ,not fixed in size ,Read & Write Operations
            var mutableList1  =  arrayListOf<String>()
            var mutableList2  =  ArrayList<String>()
            var mutableList  =  mutableListOf<String>()
            mutableList.add("android") //0
            mutableList.add("iOS") //1
            mutableList.add("flutter") //2
    
            //remove
            mutableList.remove("iOS") //removing @ 1 index
            mutableList.add("React Native") //adding @ 1 index
            for(element in mutableList){
                println(element)
            }
        }
    

    Output : 
    Android
    iOS
    Flutter

    android
    React Native
    flutter

    Explaination: 
    Here we can see that with immutable list , we can only READ the elements  , but with mutable list I have removed one element from index 1 and then add another element at index 1 .
    Also I have shared all the types of mutable list which we can use it in our code  , let's take a look what are the types of these array lists :

     var mutableList1: ArrayList<String> =  arrayListOf<String>()
     var mutableList2: ArrayList<String> =  ArrayList<String>()
     var mutableList: MutableList<String> =  mutableListOf<String>()
    

    Here one thing is noticable that  MutableList<String> , is also implemented by ArrayList<String>

    So that was very basic explanation of List / ArrayList , which will help to understand the functionality. In next post I will share for Map and Set , till then Happy Coding 😀😀


    Kotlin : "with" & "apply" keywords (Post 15)

    Hi  ,

    Again I am sharing two basic and import keywords that are : "with" & "apply" .Both keywords are part of Kotlin Standard Library

    Let's take a look :

    override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            //with keyword
            with(Mobile()){
                os = "Android"
                version = "10.0.0"
            }
    
            // apply keyword
            Mobile().apply{
                os = "Android"
                version = "10.0.0"
            }.checkStatus()
        }
    
        /**
         * Mobile class
         */
        class Mobile {
            var os: String = ""
            var version: String = ""
    
            fun checkStatus() {
                println("I am in Mobile class!")
            }
        }
    


    Here we can see that we can assign the value to the variables of mobile class using with and apply keyword .

    With the help of apply keyword we can also call the member function of that class.

    That's all for this post , I will again share some new concept of Kotlin Language  , till then Happy Coding 😀

    Sunday, 19 April 2020

    Kotlin : "it" keyword (Post 14)

    Hi ,

    Let's discuss the "it" keyword, with lambda expression.

    it keyword is basically is used as implicit the single parameter.

    If any lambda expression is using one parameter , then it can be replaced with "it" keyword .

    Here is a simple example for understanding : 
    override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            getLength("Android", { a -> a.length })
            getLength("Android", { it.length })
        }
        /**
         * High Level Functions
         */
        fun getLength(a: String, myExp: (String) -> Int) {
            println(myExp(a))
        }
    

    Here we can see that "a" argument is used to get the length of "a" lambda expression is used.
    So it can be replaced as  "a -> a" to "it" , and it is only applicable for single parameter.

    That's all for this post. Will share another post soon , till then Happy Coding :)


    Kotlin : Lambda Expressions (Post 13)

    Hi ,

    Continuing  , the series of Kotlin , here I am again discussing few things about Lambda Expressions.

    The main aim of writing the Lambda Expressions is to simplify the  code and reduce the number of lines  , with easily understandable .

    I am here sharing a simple example of Lambda Expression , and passing it in the argument of one functions . The  functions which are having lambda expressions as an argument , are called High Order Functions.


    override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            /** Lambda Expressions
            variable name : Signature = {Parameters -> method body}
            */
            var myLambdaFunction: (Int, Int) -> Unit = { a, b -> println(a + b) }
            getSum(4, 5, myLambdaFunction)
        }
    
        /**
         * High Level Functions
         */
        fun getSum(a: Int, b: Int, myLambdaFunction: (Int, Int) -> Unit) {
            myLambdaFunction(a, b)
        }
    
    
    

    Also we can call the above method like this as well :

       getSum(4, 5, myLambdaFunction)
    
       getSum(4, 5, { a, b -> println(a + b)})
    
       getSum(4, 5) { a, b -> println(a + b)}
    

    This is very basic expression of Lambdas . For getting more uses of Lambdas we can check out here :

    https://kotlinlang.org/docs/reference/lambdas.html


    Kotlin : Interface (Post 12)

    Hi ,

    Here I am again sharing you one more concept in Kotlin programming language i.e. Interface.

    In kotlin , the interfaces work slightly different . In jave we all know that we need to implement the Interface , then override the functions to execute that interface , but here in Kotlin , we can directly execute the interface and pass the argument within the function using "object" keyword , let's take a look :

    override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            getSum(4,8, object : MyInterface{
                override fun execute(sum: Int) {
                    println(sum)
                }
            })
        }
       fun getSum( a : Int , b : Int , listener : MyInterface ) {
          listener.execute(a+b)
       }
        interface  MyInterface {
            fun execute(sum : Int)
        }
    

    Also one more thing , for interface in Kotlin , few methods can also contains the body also inside the interface , same as abstract class. What makes them different from abstract classes is that interfaces cannot store state :

      interface  MyInterface {
            fun execute(sum : Int)
            fun show (){
                println("Hi I am in interface")
            }
        }
    

    In class level , interface will implement like this :

    class Child : MyInterface {
        override fun execute(sum: Int) {
            // body
        }
    }
    

    So in this way we can implement the interfaces in Kotlin . In next post I will share one more interesting concept in Kotlin Language  , till then Happy Coding :) 

    Friday, 17 April 2020

    Kotlin : TailRec Functions (Post 11)

    Hi ,

    In this post I will share the information  about "TailRec Functions"

    This function helps us to use recursion in more optimised way.

    We all know , that recursion means , calling its own function from within the function, and this recursion if the function has been called 100 or 1000 times , then in Java or C programming  language , we may face the StackOverflowException .

    But in Kotlin this recursion has been done with the help of TailRec Function, which prevents the "StackOverflowException" .

    Let's have a look :

     tailrec private fun getPrint() {
            println("Hello All")
            getPrint()
        }
    

    Like this , we can use the recursion function in a better way in Kotlin. 

    Kotlin : Infix Functions (Part 10)

    Hi ,

    Here I am sharing another topic i.e. Infix Function


    • Infix functions can be a Member Function or Extension Function
    • These functions can have only single parameter
    • They have prefix of "infix"
    • All infix functions are extension function But all extension function are not Infix


    Take a look :


     override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            var  i : Int  = 45
            var j : Int = 91
            var k = i findTheGreaterNum j //calling the infix function
            println("In I: $i & in J: $j , greater number is : "+ k)
        }
        
        /**
         * Extension Function
         */
        infix fun Int.findTheGreaterNum(j :Int) : Int {
            if(this > j)
                return this
            else
                return j
        }
    

    So here , we can say that it improves the readability.

    I will catch you later , till then Happy Coding :)






    Kotlin : Extension Functions (Post 9)

    Hi ,

    Here is another post related to Kotlin basics for beginners , in this post I will discuss the Kotlin Extension Function ,let's get started :

    So sometimes , we feel that one important functionality is missing from a class and
     we want to add that function :
    we need to extend that class, and then add that function and then use that extended class.

    But in Kotlin , helps definitely on this by providing Extension Functions

    Extension Functions are:
    • - can "add" new functions to a class without declaring it 
    • - the new functions added behaves like "static" in java

    So let's take a look in code first , then we will discuss briefly on this :

    
    
    override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      var  i : Int  = 45
      var j : Int = 91
      println("In I: $i & in J: $j , greater number is : "+ i.findTheGreaterNum(j))
    }
    
    /**
     * Extension Function
    */
    fun Int.findTheGreaterNum(j :Int) : Int {
            if(this > j)
                return this
            else
                return j
     }
    
    
    

    Here we can see the there was no function "findTheGreaterNum()" in Int class , but we can make this like extension function of Int class .

    Here this will annotate for i , bcoz  the function is class for i object.

    Same like this we can make the extension functions for our own classes as well.

    That's all for extension functions , will post more for kotlin , till then Happy Coding :) 

    Wednesday, 7 August 2019

    Kotlin : TextViews , EditText & Buttons(Post 8)

    Hi ,

    In previous post , I have started android development , with Kotlin programming language.
    Now let's take a look how Textviews and Edittext will work .

    I have created one layout , having 1 EditText , 1 TextView and 1 Button in it.

    • EditText will use , to get the input from the user. 
    • Input validation will check by clicking on Button . 
    • TextView is used to check the validation status of input and then change its text accordingly.


    labels_layout.xml :


    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">

    <EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="textPersonName"
    android:text="Name"
    android:ems="10"
    android:id="@+id/editText"
    android:layout_margin="20dp"
    />

    <Button
    android:text="Validate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/button"
    android:layout_margin="20dp"/>

    <TextView
    android:text="Check Validation"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/textView2"
    android:layout_margin="20dp"
    android:background="@color/colorPrimary"
    android:padding="10dp"
    android:textColor="#FFFFFF"/>
    </LinearLayout>



    LabelActivity.kt

    package com.kotlin_application 
    import android.os.Bundle 
    import android.support.v7.app.AppCompatActivity 
    import android.widget.Button 
    import android.widget.EditText 
    import android.widget.TextView 
    import android.widget.Toast 
    import kotlinx.android.synthetic.main.labels_layout.* 

    class LabelActivity : AppCompatActivity() 

    var isValid : Boolean = false 

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

    private fun inItView(){ 

    val textView = findViewById<TextView>(R.id.textView2) 
    val button = findViewById<Button>(R.id.button) 
    val ediText = findViewById<EditText>(R.id.editText) editText.setText(R.string.app_name) 

    button.setOnClickListener{ 
    var inputValue : String = ediText.text.toString()

    if (inputValue.isEmpty() || inputValue== null){

    Toast.makeText(this, "Please enter something!", Toast.LENGTH_LONG).show() 
    isValid = false


    else{

    Toast.makeText(this, "You have entered: "+inputValue, Toast.LENGTH_LONG).show()
     isValid = true 

    }

    }

    textView.setOnClickListener 
    var inputValue : String = ediText.text.toString()

    if ((inputValue.isEmpty() || inputValue== null) && !isValid){

     Toast.makeText(this, "Not Validate", Toast.LENGTH_LONG).show()
    textView.text = "Can not login , as input is not valid" 


    else{ 

    Toast.makeText(this, "Validate String : "+inputValue, Toast.LENGTH_LONG).show() 

    textView.text = "Login successful" 

    }
    • Here you can see , the click listeners are different , than java . 
    • To set Text on TextView , we need to just : textView.text = "Login successful"
    • To get the value from the EditText , we have to call it like this:
    •  var inputValue : String = ediText.text.toString()
    • Toast is same as java. 
    Buttons:

    There are below type , by which we can define the click listener for buttons :


    button1.setOnClickListener()
    {              
    Toast.makeText(this,"button 1 clicked", Toast.LENGTH_SHORT).show()         
    }  


    Here are some screenshots: 
      
     

     

    That's it for this post . Will continue with Intents in next post. 

    Tuesday, 6 August 2019

    Kotlin : Hello World Android App (Post 7)

    Hi ,

    After the basic of Kotlin App. Let's start android development with Kotlin language. In this post I am going to share the demo for simple hello world program with Kotlin language.

    For setup of Kotlin Support , android studio will be required of 3.0 version and more.At the time of language selection , we need to select "kotlin" for programming language , when we create a new application.

    When creating the android application with kotlin , we do not need to change the layouts , just src files will be changed.

    Here I will just create one layout having textview in it ,and attach the activity with this textview . Let's have a look :

    activity_main.xml :

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout 
     xmlns:android="http://schemas.android.com/apk/res/android" 
     xmlns:tools="http://schemas.android.com/tools"
     xmlns:app="http://schemas.android.com/apk/res-auto"  
          android:layout_width="match_parent"  
          android:layout_height="match_parent" 
           tools:context=".MainActivity">
    
        <TextView    
          android:id="@+id/textView" 
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="Hello World!"
           app:layout_constraintBottom_toBottomOf="parent"
           app:layout_constraintLeft_toLeftOf="parent"
           app:layout_constraintRight_toRightOf="parent"
           app:layout_constraintTop_toTopOf="parent"/>
    
    </android.support.constraint.ConstraintLayout>
    
    
    
    
    
    MainActivity.kt:

    package com.kotlindemo
    
    import android.support.v7.app.AppCompatActivity
    import android.os.Bundle
    
    class MainActivity : AppCompatActivity() {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
        }
    }
    
    Run the code:


    That's it for this post , in next post I will discuss how TextViews and EditText is used in Kotlin.
    
    
    
    
    
    
    
    

    Wednesday, 31 July 2019

    Kotlin : Arrays (Post 6)

    Hi ,

    In previous post , I explained about default and named parameters of function is Kotlin.
    Now in this post let's take a look how array will work in Kotlin.
    • Kotlin array , can be combination of values of same data types like Int, String etc. 
    • set & get is used for doing modifications and access the elements in array.
    • Kotlin array are mutable in nature , so we can modify the elements.
    • arrayOf<T>  & intArrayOf  is used to declare the arrays
    Declaration of Arrays : 


    var myArray1 = arrayOf(3,7,9,23,65)
    var myArray2 = arrayOf<Int>(1,2,3,4,5)
    var myArray3 = arrayOf("A" , "B" , "C", "D", "E")
    var myArray4 = arrayOf<String>("a" , "b" , "c", "d","e")
    var myArray5= arrayOf(1,10,4, "Java","Android")
    
    //using intArrayOf
    var myArray6 : IntArray = intArrayOf(10,20,30,40,50)
    

    Set the value of element: 

    myArray1.set(2, 10)
    
    myArray1[1] = 4
    
    for(i in myArray1){
    Log.d(TAG, ""+ i)
    }
    


    Output:
    3
    4
    10
    23
    65

    -----------------------------------------------------------------
    Let's take a look how we can modify the array and print the elements with one example :


    override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            //Mutable (can change) and fixed sized
            var myArray = Array<Int>(5) {0}
    
            /*
            index : 0  1  2  3  4
           element: 0  0  0  0  0
             */
    
            myArray[4] = 45
            myArray[2] = 3
            myArray[0] = 21
    
            /*
            index : 0   1   2   3   4
           element: 21  0   3   0   45
             */
    
            // to print all the elements in array
            for (element in myArray){
                println(element)
            }
        }
    

    That's it . Many more different cases are there which should be practiced . 

    Kotlin : Default and Named Argument (Post 5)

    Hi,

    In previous post , I explained about functions . In this post , I will discuss more about arguments in Kotlin .

    In Kotlin , we can assign default value of the parameter in function definition. If any value is pass at the time of function calling , that passed value is used otherwise the default value is used.

    Let's take a look for better understanding:


    Method Body :

    fun run(num:Int= 5, latter: Char ='x'){
    Log.d(TAG,"parameter in function definition $num and $latter")
    }
    


    Case : I 

    calling the function like :
    setContentView(R.layout.activity_main)
    run()
    

    Output:
    parameter in function definition 5 and x

    Explanation: As we can see in function definition , by default value will be printed.
    ------------------------------------------------------------------

    Case :II 


    calling the function like : 
    setContentView(R.layout.activity_main)
    run(3, 'T')
    

    Output:
    parameter in function definition 3 and T

    Explanation: As we can see in function definition , new passed value will override the by default values , hence the value has been changed.
    ------------------------------------------------------------------

    Case :III 

    calling the function like : 
    setContentView(R.layout.activity_main)
    run(3)
    

    Output:
    parameter in function definition 3 and x

    Explanation: As we can see in function definition ,the first parameter with new int value will be override the default one and for second parameter , as nothing has been passed so second value will print the default one.
    -----------------------------------------------------------------

    Case :IV 

    calling the function like : 
    setContentView(R.layout.activity_main)
    run('b')
    

    Output:
    Compile Time Error: The character literal does not conform to the expected type Int

    Explanation: As we can see in function definition ,the first parameter is defined as integer value , so for 'b',compiler will take as a value for first parameter . But passed value type does not match with the first parameter in function definition. Hence compile time error will occur.
    ----------------------------------------------------------------------------------------------------------------------

    Case :V 


    setContentView(R.layout.activity_main)
    run()
    

    calling the function like : 
    setContentView(R.layout.activity_main)
    run(latter='b')
    

    Output:
    parameter in function definition 5 and b

    Explanation: As we can see that here , I am passing name of that parameter name , to assign the value , so compiler will take as a second parameter value, from the calling statement because in this case name of parameter has also been mentioned. So in this way it will show that output. This scenario will called as Named Argument.
    -----------------------------------------------------------------

    Case :VI 

    calling the function like :
    setContentView(R.layout.activity_main)
    run()
    

    And methods are defined like this: 
    fun run(num:Int= 5, latter: Char ='x'){
    Log.d(TAG,"parameter in function definition $num and $latter")
    }
    

    fun run(){
    Log.d(TAG,"function with no parameter")
    }
    

    Output:
    function with no parameter

    Explanation: As we can see there are two methods has been defined so , when we call the method without parameter , so it will call the second function , which doesn't have any parameter defined in function definition. If that function is not defined there , then the first function will get the call.
    -----------------------------------------------------------------------------------------------------------------

    That's it , will be back later with some new concepts in Kotlin, till then happy coding :) 

    Tuesday, 30 July 2019

    Kotlin : Function (Post 4)

    Hi All,

    In previous post , I discussed about the control flow in Kotlin. Now continuing the basics in Kotlin , here in this post we will discuss about how functions are declared and called in this language.

    => Functions are used "fun" keyword to declare it.

    => Here I am showing how user define functions are defined in it.

    Simple function example :


    fun sayHello(){
    Log.d(TAG,"Hello")
    }
    

    Output:
    Hello
    ----------------------------------------------------------------

    Parameterize Function and Return Value :


    fun sum(num1 : Int , num2 : Int) :Int {
    return num1+num2
    }
    


    calling the function : var num3 = sum(a,b)

    Output:
    Sum of two numbers:8
    ------------------------------------------------------------------

    Named Parameters :

    In kotlin we can have  the named parameter , let's take a look how we declare these type of functions:


      findVolumn(height =6, length =4 , width =5 )

    And function body like :

      private fun findVolumn(length: Int, width: Int, height: Int) {
    
            println("Length is:"+length)
            println("Width is:"+width)
            println("Height is :"+height)
        }
    

    Output:
    Length is:4
    Width is:5
    Height is :6

    Here , in named parameter we can see , that with the help of name of that parameter , whatever the order of the argument , it will use on the basis of its names. 

    Benefit of this type of parameter is , with the help of parameters names , safer side function will handle the actual argument , so this will prevent any mistake by defining the values right & clear.

    That's all for this post, I will update more types of functions in Kotlin in my future posts.








    Advanced Kotlin Coroutines : Introduction

     Hi,  Today I am unwraping the topic in Kotin world i.e. Coroutine . If you want to get started with Kotlin coroutine and ease your daily de...