Showing posts with label Android Developement. Show all posts
Showing posts with label Android Developement. 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. 


Wednesday, 29 April 2020

Accessibility : Adding custom actions

In previous post , the introduction of custom accessibility actions/events was explained . But how it will be implemented ?, will cover it here.

Custom actions help the accessibility users to get all the clicks at one place. It provides a clear picture of the events and actions  of the focused view to the user. Since it is related to events and actions of one view only so all the actions will appear under Local Context Menu .


To understand the implementation , with an example , there is one list view , showing the employee list data , and grouping has already done for each list-view row (Please refer : this post) .

Now here one delete button has also been added, then in this case , there are 2 click listeners exist for each and every list-view row, that are :

  • Employee Details  click
  • Delete click


So here the problem is when the talkback is ON due to grouping of view-group , that delete button will not get focused separately , as it is the child of that view-group (list-view row).
To solve this problem , custom actions can be added. As there are 2 click listeners added , so two custom accessibility actions will be added :
  • Employee Details Action
  • Delete Action
In Adapter class :

setAccessibilityActions(holder.layoutParent)

Function body :
private fun setAccessibilityActions(view : View) {
       ViewCompat.setAccessibilityDelegate(view , object : AccessibilityDelegateCompat() {
           override fun onInitializeAccessibilityNodeInfo(
               host: View,
               info: AccessibilityNodeInfoCompat
           ) {
               super.onInitializeAccessibilityNodeInfo(host, info)
               info.addAction(AccessibilityNodeInfoCompat.AccessibilityActionCompat(R.id.layoutParent,
                   "Employee Details"))
               info.addAction(AccessibilityNodeInfoCompat.AccessibilityActionCompat(R.id.imageView,
                   "Delete"))

           }
           override fun performAccessibilityAction(
               host: View?,
               action: Int,
               args: Bundle?
           ): Boolean {
               super.performAccessibilityAction(host, action, args)
               if (action == R.id.layoutParent) {
                  Toast.makeText(context , "Employee Detail clicked!" , Toast.LENGTH_LONG).show()
               }
               if (action == R.id.imageView) {
                   Toast.makeText(context , "Delete clicked!" , Toast.LENGTH_LONG).show()
               }
               return true
           }
       })
    }

In this , two actions have been added in , onInitializeAccessibilityNodeInfo , which is used to add custom actions/events for the view.

Similarly , performAccessibilityAction , is overridden to perform the action clicks.

Here one thing is noticeable that actions are added in : info. addAction
(AccessibilityNodeInfoCompat.AccessibilityActionCompat(R.id.layoutParent, "Employee Details"))


. In AccessibilityNodeInfoCompat.AccessibilityActionCompat(R.id.layoutParent, "Employee Details") ,


  • The first argument is passed as actionId , which must be unique for each and every action which are added here. On the basis of this actionId , action will perform in performAccessibilityAction
  • In second argument , string is passed, which is the action label , which will appear under local context menu. 
Note : These changes will work only when the accessibility service is enabled. 

Here are the screenshots after adding the custom accessibility actions :








Accessibility : Introduction of custom views

While adding the grouping of views into a view-group , what if there are more than one click-lisnters added on views , how clicks are handled in accessibility grouping?

This can be done with the help of AccessibilityDelegateCompat , which is the part of accessibility api.
This class is helpful for adding the actions and events on any view. Actions will be listed under Local Context Menu and events will announce after the content announcement , like double tap to activate or double tap and hold to long press etc.

For example :

  • If it is required to add anything on double tap when talkback is on , then it will add in event.
  • when it is required to add any custom action like : detail or delete etc. then it will add in actions.
Note
  • All the events for that view will announce after the content announcement
  • All the action will appear under local context menu 
  • All the action names , should covey the exact meaning of that action , not like click here 
As per developer.android.com there are many methods defined , which can be overridden :

 dispatchPopulateAccessibilityEvent : Dispatches an AccessibilityEvent to the host view first and then to its children for adding their text content to the event.

 onInitializeAccessibilityEvent : Initializes an AccessibilityEvent with information about the host view which is the event source.

onInitializeAccessibilityNodeInfo : Initializes an AccessibilityNodeInfoCompat with information about the host view.

onPopulateAccessibilityEvent : Gives a chance to the host View to populate the accessibility event with its text content

onRequestSendAccessibilityEvent : Called when a child of the host view has requested sending an AccessibilityEvent and gives an opportunity to the parent (the host) to add the event.

sendAccessibilityEvent
: Sends an accessibility event of the given type. If accessibility is not enabled this method has no effect.

sendAccessibilityEventUnchecked : Sends an accessibility event. This method behaves exactly as sendAccessibilityEvent(View, int) but takes as an argument an
 empty AccessibilityEvent and does not perform a check whether accessibility is enabled.

getAccessibilityNodeProvider : Gets the provider for managing a virtual view hierarchy rooted at this View and reported to android.accessibilityservice.AccessibilityService
that explore the window content.

performAccessibilityAction : Performs the specified accessibility action on the view.


Tuesday, 28 April 2020

Accessibility : Links

If one textview contains many links , that can be handled correctly using local context menu . Local context menu has already been covered in this post 

There are some specific rules , which should follow for links :

  • Links should have appropriate meaningful link text , not "click here"
  • All the links which are present in textview , should be listed in local context menu -> under Links category . 
  • Announcement for opening the local context menu should be correct like : "Links available , Swipe up and right to view"
Here are few screenshots , for the correct behaviour of links with accessibility : 


Correct Announcement of actions to open the list of links 
In this textview , 2 clickable links are added that are : SignUp ! & Sign In here!
So both should be listed under local context menu . 


Local Context Menu


Clickable Links under Local Context Menu


 

Accessibility : RecyclerView with grouping

Grouping in accessibility , means that , to add focus on parent layout , and no child layout will get the focus separately .

Traversing the child elements , one by another ,increases the steps , and also visually -impaired persons may face difficulty to understand the whole view-group , so to reduce these issues , grouping can be done.

RecyclerView , is a good example to understand the grouping scenario.

EmployeeData is showing in RecyclerView , having 3 textviews .When the grouping was not done , talkback will traverse each and every textview , like this :

Recycler View before grouping

  • To add grouping , all the child elements need to set android:importantForAccessibility="no" which will hide the child elements from talkback .
  • And add android:importantForAccessibility="yes" to container layout of  row_item , which will set focus to the container layout (ViewGroup) .
  • Also add appropriate content description to container layout .

<androidx.constraintlayout.widget.ConstraintLayout
    android:importantForAccessibility="yes"
    android:id="@+id/layoutParent">

    <ImageView
        android:id="@+id/image_emp"
        android:importantForAccessibility="no"/>

    <TextView
        android:id="@+id/textEmployeeName"
        android:importantForAccessibility="no"/>

    <TextView
        android:id="@+id/textEmployeeId"
        android:importantForAccessibility="no"
       />

    <TextView
        android:id="@+id/textJoining"
        android:importantForAccessibility="no"
        />
</androidx.constraintlayout.widget.ConstraintLayout>

And in adapter class :

textEmployeeName.text = "Employee Name : ${employee.empName}"
textEmployeeId.text = "Employee ID: ${employee.empId}"
textJoining.text = "Joining Date:  ${employee.empJoiningDate }"

layoutParent.contentDescription = textEmployeeName.text.toString()+" " +
                    textEmployeeId.text.toString()+" "+
                    textJoining.text.toString()+" "

Here in adapter class all the 3 textviews' text have been appended and set content description of  layoutParent  , which will look like this :


RecyclerView after grouping





Accessibility : Checkbox

Same as switches , checkbox should also covey all the information once get focused :

As per accessibility guidelines , checkbox should announce its State, its title , and action .

For Example  :

There are 2 example , 1 is incorrect accessibility  behaviour  and another one is correct accessibility behaviour :

Incorrect checkbox accessibility behaviour :

Incorrect checkbox accessibility behaviour 

Incorrect checkbox accessibility behaviour 


Correct checkbox accessibility behaviour :
Correct checkbox accessibility behaviour


























  • Checkbox with Grouping :

For grouping of checkboxes , each and every checkbox of that group should convey the information of it's group title as well , like : 
<Group_name> 
     < check_box1 />
     < check_box2 />  
</Group_name>

So check_box1 will announce like :  <State>  <Check box title +  Group title>  <Action>


For Example :

 <TextView
        android:id="@+id/textView"
        android:text="Preferred technical skills"/>

    <CheckBox
        android:id="@+id/check1"
        android:text="Java"
        android:contentDescription="Java , Preferred technical skills" />

    <CheckBox
        android:id="@+id/check2"
        android:text="Android"
        android:contentDescription="Android , Preferred technical skills" />

    <CheckBox
        android:id="@+id/check3"
        android:text="React Native"
        android:contentDescription="React Native , Preferred technical skills" 



 






Accessibility : Switches

As per the accessibility guidelines  , switches should implement with text , and with talkback it would get focused and announced altogether .

For Example :

 <Switch
        android:id="@+id/switch1"
        android:text="Switch with text"/>

    <LinearLayout
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textView"
            android:text="Switch Without Text"/>
        <Switch
            android:id="@+id/switch2"/>

    </LinearLayout>

Screenshots :

Below is incorrect behaviour as per accessibility guidelines :

   
Incorrect
Incorrect 



Below example is correct behaviour as per accessibility guidelines :

Correct


Accessibility : TextView & ImageView

TextView :

<Element Text> <Element Action(if added)>

  • Minimum text size must be 14sp
  • 48 dp is the recommended touch target size for elements according to Google (height and width, with an 8 dp margin around the element).

 This is not mandatory to set contentDescription here , if some thing is required to announce , which is different from the mentioned in text string , so in that case contentDescription should be added , take a look :

Case -I
  <TextView
        android:text="Hello World!"
        android:contentDescription="This is Accessibility demo!"
       />

In this case , it will only announce : "This is Accessibility demo!"
If contentDescription is not mentioned : "Hello World!"


Case -II

<TextView
        android:text="This is demo!"
        android:clickable="true"
        />

In this case , it will only announce : "This is demo! , double tap to activate"

Here , double tap to activate , will also announced because clickable="true" has been added.




In case of ImageView :

It is mandatory to mention the content description , for imageview ,  it should be the well-descriptive  and convey the correct information of that image.

If in any imageview , content description is not added , it will show the fail result , in accessibility scanner /axe tool .

So if in any imageview , it is not required to announce anything , so in that content description can set it to "@null"

Here is an example :

 <ImageView
        android:id="@+id/imageView3"
        android:contentDescription="@null"
        app:srcCompat="@mipmap/ic_launcher" />

    <ImageView
        android:id="@+id/imageView2"
        android:contentDescription="my profile"
        app:srcCompat="@mipmap/ic_launcher" />

Here we can see that , in imageView2 ,  the my profile description has been added , but in imageView3 , it will not announce anything as contentDescription is set to @null . 



Accessibility :Button

Button :  To announce the button , talkback will announce :

There are many reasons which should follow :
  • content Description should add only when it is required that the announcement is differ from button text 
  • Button (Element name) string should not added in content description string, like :
android:contentDescription="Submit Button"
This is not good example.

  • Similarly  “Double Tap to activate” (Element Action) string should not added in content description string, like :

 android:contentDescription="Submit double tap to activate"

This is not good example.

  • Also , if button’s state like : enable/disable it should also not added in content description string like: 
 android:contentDescription="Submit disabled"

This is also not good example.

Here is the example of 2 types of buttons , in that one it in disabled state :


In this demo ,there is no extra announcement has been added, it is announcing by default.

Accessibility : Global & Local Context Menus

Both Context Menus (https://support.google.com/accessibility/android/answer/6007066?hl=en)
are playing very important part in accessibility .
These menus helps to find the settings , actions & controls for that screen / view.

Accessibility Context Menu can be represent mainly in 2 ways :

  1. Listed view(Showing in post)
  2. Circular view (This will show all the options in circular form)


As mentioned in title , there are 2 types of these context menus :

Global Context Menu :
This menu is mainly related to the whole screen and work everywhere . There are following commands which are added in Global Context Menu :


Gesture to open the global context menu  : Swipe down then right  (which can be changed in talkback settings)




Local Context Menu :
This menu is mainly related to the focused item. It contains all the commands /settings/actions/links related to that focused item .
If any custom action , which are needed to added for that view for accessibility , should be added here only.

There are following commands which are added in Local Context Menu :



Gesture to open the local context menu  : Swipe up then right  (which can be changed in talkback settings)






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 :)


    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...