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.








Monday 22 July 2019

Kotlin : Control Flow (Post 3)

Hi All,

In previous post , I have shared some basics overview of variables , datatypes , arrays etc.
Now in this post we will go through , the control flows : if-else, for loop etc.

if-else:

val a : Int = 5
val b : Int = 3
var max : Int = 0

if(a>b){
max = a
}else{
max = b
}

println("Maximum of a or b is " +max)

Output: Maximum of a or b is 5


When-Else

val x : Int = 1

when(x){
1-> println("x is 1")
2-> println("x is 2")
3-> println("x is 3")
else -> {
println("x is not 1 , 2 or 3")
}
}


Output: x is 1

For-Loop: 

    print("for (i in 1..5) print(i) = ")
    for (i in 1..5) print(i)
    println()
    
    print("for (i in 5..1) print(i) = ")
    for (i in 5..1) print(i)             // prints nothing
    println()
    
    print("for (i in 5 downTo 1) print(i) = ")
    for (i in 5 downTo 1) print(i)
    println()
    
    print("for (i in 1..5 step 2) print(i) = ")
    for (i in 1..5 step 2) print(i)
    println()
    
    print("for (i in 5 downTo 1 step 2) print(i) = ")
    for (i in 5 downTo 1 step 2) print(i)

Output:
for (i in 1..5) print(i) = 12345
for (i in 5..1) print(i) = 
for (i in 5 downTo 1) print(i) = 54321
for (i in 1..5 step 2) print(i) = 135
for (i in 5 downTo 1 step 2) print(i) = 531

While Loop:
var x:Int = 0
println("Example of While Loop--")

while(x<=5){
println(x)
x++
}


Output:
0
1
2
3
4
5

That's it for this post , in next post I will share how we will write classes and objects etc. 

Sunday 21 July 2019

Kotlin : Basics (Post 2)

Hi All ,

Previously , I posted the overview of Kotlin . Kotlin is fully supported in Android Studio 3.0 and higher. 
For Kotlin support , we just need to select the Kotlin language , at the time of configure the new android project in Android Studio. 
Now let's take a look at some basics of Kotlin Language :

=> Declare Variables :

val and var both are used to declare a variable. var is like general variable and it's known as a mutable variable in kotlin and can be assigned multiple times.val is like Final variable and it's known as immutable in kotlin and can be initialized only single time.


=>Numbers : 

The representation of numbers in Kotlin is pretty similar to Java, however, Kotlin does not allow internal conversion of different data types. Here is one example of my Demo Activity :

class MainActivity : AppCompatActivity() {

    val intergerValue: Int = 10    
    val doubleValue: Double = 10.00   
    val floatValue: Float = 10.00f
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        println("Int Value is "+intergerValue)
        println("Double  Value with string is -> $doubleValue ");
        println("Float Value is "+floatValue)
    }

}

 Output: 
Int Value is 10
Double  Value with string is -> 10.0 
Float Value is 10.0

Explanation :
Here in this example , we can see that , in second print statement , I have used semicolon(;), at the end of statement . Semicolon (;) is not mandatory at the end of statement in Kotlin.

Another thing , I have used $ , to print the value of variable within the String . Otherwise , we can used + size to append the value with String (same as JAVA).

=> Characters & Boolean : 

Assigning and defining of character and boolean variables should be done like this :

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

    val letter: Char    // defining a variable 
    letter = 'R'        // Assigning a value to it 
    println("$letter")
   
    val letter1: Boolean   // defining a variable 
    letter1 = true         // Assinging a value to it 
    println("Character value -> "+"$letter1")
}

  Output: 
R
Character value -> true
Explanation
Here ,  we can not reassign any new value for that "val" variable .It will throw compile time error: 
"Val value can not be reassigned! "

=> String :

 var rawString :String ="I am Raw String!\n" 
 println("Hey!!"+rawString) 
  Output: 
Hey!!I am Raw String!
=> Arrays :
Arrays should be defined like following :
var Arr1 = arrayOf(1,10,4,6,15)
var Arr2 = arrayOf<Int>(1,10,4,6,15)
var Arr3 = arrayOf<String>("Surat","Mumbai","Rajkot")
var Arr4 = arrayOf(1,10,4, "Ajay","Prakesh")
var Arr5: IntArray = intArrayOf(5,10,15,20)

println("Hey!! I am array Example1->"+Arr1[2])
println("Hey!! I am array Example2->"+Arr2[2])
println("Hey!! I am array Example3->"+Arr3[2])
println("Hey!! I am array Example4->"+Arr4[3])
println("Hey!! I am array Example5->"+Arr5[2])
Output: 
Hey!! I am array Example1->4
Hey!! I am array Example2->4
Hey!! I am array Example3->Rajkot
Hey!! I am array Example4->Ajay
Hey!! I am array Example5->15
Explanation
Here , in Arr4 , we can see that we can also define , integer and String in one array also.
=> ArrayList :
val arrayList = ArrayList<String>()
  arrayList.add("Hello")
  arrayList.add("Hi")
  arrayList.add("Good Morning")
  println("Size of ArrayList->"+arrayList.size)



Output: Size of ArrayList->3

That's it , for this post . In next post we will go through the condition statements and control flows.

Kotlin - Overview (Post 1)

Hi All,

Today I am going to start a new series i.e. Kotlin Tutorial , which facilitates us to write android codes with the help of Kotlin language.

Now the question is what is the need of switching from Java to Kotlin .
Let's take a look for Kotlin Overview.

Kotlin is an open-source, statically-typed programming language that supports both object-oriented and functional programming. Kotlin provides similar syntax and concepts from other languages, including C#, Java, and Scala, among many others. Kotlin does not aim to be unique—instead, it draws inspiration from decades of language development. It exists in variants that target the JVM (Kotlin/JVM), JavaScript (Kotlin/JS), and native code (Kotlin/Native). (As per Developer Site)


Kotlin Advantages :

  • Easy Language 
  •  Reduce lots of boiler plate code
  • Better Runtime and Performance
  • Interoperability 
  • Brand New 

We can use Kotlin , in any exiting application. Also  we can create new application with Kotlin language. JAVA 8 would be needed to installed in system and java path should be added in environment variable.
In next post I will share , some basic variable declaration and many more. 


Monday 14 January 2019

Android Architecture Components : Work Manager (Introduction)

Hi All ,

Continuing the series of Android Architecture Components , I am going to share one more topic i.e. work manager . 

First , 

What is Work Manager :

WorkManager is part of Android Jetpack and an Architecture Component for background work that needs a combination of opportunistic and guaranteed execution. 
Opportunistic execution means that WorkManager will do your background work as soon as it can. Guaranteed execution means that WorkManager will take care of the logic to start your work under a variety of situations, even if you navigate away from your app.


Work Manger attributes :

WorkManager is a simple, but incredibly flexible library that has many additional benefits. These include:
  • Support for both asynchronous one-off and periodic tasks
  • Support for constraints such as network conditions, storage space, and charging status
  • Chaining of complex work requests, including running work in parallel
  • Output from one work request used as input for the next
  • Handles API level compatibility back to API level 14(see note)
  • Works with or without Google Play services
  • Follows system health best practices
  • LiveData support to easily display work request state in UI

Why Work manager-

For background task which needs guaranteed execution and can be deferrable we have lot of options to do.We can use JobScheduler API but it is supported for API≥21 to overcome this we have FirebaseJobDispatcher library which provide backward compatibility upto API 14 but it requires Google Play services.


So to avoid all these handling Work manager comes to rescue.
You don’t need to write device logic to figure out what capabilities the device has and choose an appropriate API; instead, you can just hand your task off to WorkManager and let it choose the best option.It is wrapper on all above concepts.



Work Manager Uses :

WorkManager sits on top of a few APIs such as JobScheduler, FirebaseJobDispatcher and AlarmManager

WorkManager chooses the appropriate way to run your task based on such factors as the device API level and the app state. If WorkManager executes one of your tasks while the app is running, WorkManager can run your task in a new thread in your app's process. If your app is not running, WorkManager chooses an appropriate way to schedule a background task--depending on the device API level and included dependencies, WorkManager might use JobScheduler, Firebase JobDispatcher, or AlarmManager. You don't need to write device logic to figure out what capabilities the device has and choose an appropriate API; instead, you can just hand your task off to WorkManager and let it choose the best option.
The WorkManager library is a good choice for tasks that are useful to complete, even if the user navigates away from the particular screen or your app.
Some examples of tasks that are a good use of WorkManager:
  • Uploading logs
  • Applying filters to images and saving the image
  • Periodically syncing local data with the network
WorkManager offers guaranteed execution, and not all tasks require that. As such, it is not a catch-all for running every task off of the main thread.

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